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