generated from LufsX/Challenge-kNN
This commit is contained in:
+30
-8
@@ -25,8 +25,8 @@ import numpy as np
|
|||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423xxx"
|
id = "202210423109"
|
||||||
name = "test_name"
|
name = "孔祥芷"
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@@ -53,23 +53,45 @@ def classify0(inX, dataSet, labels, k=0):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- 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):
|
def load_data(file_path):
|
||||||
"""
|
|
||||||
加载 TSV 格式数据文件。
|
#加载 TSV 格式数据文件。
|
||||||
"""
|
|
||||||
data = np.loadtxt(file_path, delimiter="\t")
|
data = np.loadtxt(file_path, delimiter="\t")
|
||||||
features = data[:, :-1]
|
features = data[:, :-1]
|
||||||
labels = data[:, -1].astype(int)
|
labels = data[:, -1].astype(int)
|
||||||
return features, labels
|
return features, labels
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 以下代码可用于测试,可自行随意修改
|
# 以下代码可用于测试,可自行随意修改
|
||||||
|
train_file_path = "datingTrainSet2.tsv"
|
||||||
|
train_features, train_labels = load_data(train_file_path)
|
||||||
|
|
||||||
train_file = "datingTrainSet2.tsv"
|
test_file_path = "datingTestSet2.tsv"
|
||||||
|
test_features, test_labels = load_data(test_file_path)
|
||||||
|
|
||||||
train_data, train_labels = load_data(train_file)
|
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])
|
||||||
|
|
||||||
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
|
accuracy = correct_count / len(test_features)
|
||||||
|
print(f"Accuracy: {accuracy:.2f}")
|
||||||
Reference in New Issue
Block a user