generated from LufsX/Challenge-kNN
This commit is contained in:
+11
-11
@@ -54,16 +54,12 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算待分类样本与训练集中每个样本之间的距离
|
||||
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
|
||||
# 根据距离对训练样本进行排序
|
||||
sorted_index = np.argsort(dists)
|
||||
# 选择距离最近的k个样本
|
||||
class_count = {}
|
||||
for i in range(k):
|
||||
vote_label = labels[sorted_index[i]]
|
||||
class_count[vote_label] = class_count.get(vote_label, 0) + 1
|
||||
# 投票得到最多的标签作为预测结果
|
||||
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
|
||||
if sorted_class_count:
|
||||
return sorted_class_count[0][0]
|
||||
@@ -103,19 +99,23 @@ if __name__ == "__main__":
|
||||
train_features = standardize(train_features)
|
||||
test_features = standardize(test_features)
|
||||
|
||||
# 尝试不同的 K 值
|
||||
best_k = 3
|
||||
best_accuracy = 0.0
|
||||
|
||||
for k in [1, 3, 5, 7, 9]:
|
||||
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)
|
||||
predict_label = classify0(test_feature, train_features, train_labels, k=k)
|
||||
if predict_label == -1:
|
||||
continue
|
||||
correct_count += (predict_label == test_labels[i])
|
||||
|
||||
accuracy = correct_count / len(test_features)
|
||||
print(f"Accuracy: {accuracy:.2f}")
|
||||
print(f"Accuracy with k={k}: {accuracy:.2f}")
|
||||
if accuracy > best_accuracy:
|
||||
best_accuracy = accuracy
|
||||
best_k = k
|
||||
|
||||
|
||||
|
||||
|
||||
accuracy = correct_count / len(test_features)
|
||||
print(f"Accuracy: {accuracy:.2f}")
|
||||
print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}")
|
||||
|
||||
Reference in New Issue
Block a user