Files
Challenge-kNN/function.py
T
kkkkkxz 851f5ef048
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 12s
更新 function.py
2024-10-08 19:34:34 +08:00

97 lines
2.8 KiB
Python

# function.py
import numpy as np
"""
挑战说明:
- 自行编写实现 KNN 分类算法。
- 函数输入: 待分类的样本 inX, 训练数据集 dataSet, 训练集对应的标签 labels。
- 函数返回: 预测的分类标签。
注意事项:
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
- 在 function.py 中实现 KNN 分类算法。
- 自动评测脚本仅会加载 classify0 函数,请勿修改函数名。
- 训练集在本目录下的 datingTrainSet2.tsv 中。
- 评测数据集在本目录下的 datingTestSet2.tsv 中。
挑战环境:
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
- OS: Ubuntu 22.04.4 LTS
- Python: 3.10.12
- numpy: 2.1.1
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423109"
name = "孔祥芷"
"""
参数说明:
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
返回值:
- int: 预测的分类标签。
"""
# 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=3):
"""
KNN 分类算法。
Args:
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): KNN 算法参数,请自行设置默认值,评测时仅会使用其默认值。
Returns:
- int: 预测的分类标签。
"""
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
sorted_index = np.argsort(dists)
class_count = {}
for i in range(k):
vote_label = labels[sorted_index[i]]
if vote_label not in class_count.keys():
class_count[vote_label] = 1
else:
class_count[vote_label] += 1
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
return sorted_class_count[0][0]
def load_data(file_path):
#加载 TSV 格式数据文件。
data = np.loadtxt(file_path, delimiter="\t")
features = data[:, :-1]
labels = data[:, -1].astype(int)
return features, labels
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_file_path = "datingTrainSet2.tsv"
train_features, train_labels = load_data(train_file_path)
test_file_path = "datingTestSet2.tsv"
test_features, test_labels = load_data(test_file_path)
correct_count = 0
for i in range(len(test_features)):
test_feature = test_features[i].reshape(1, -1)
predict_label = classify0(test_feature, train_features, train_labels, k=3)
correct_count += (predict_label == test_labels[i])
accuracy = correct_count / len(test_features)
print(f"Accuracy: {accuracy:.2f}")