generated from LufsX/Challenge-kNN
This commit is contained in:
+4
-3
@@ -1,5 +1,7 @@
|
|||||||
# function.py
|
# function.py
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
from collections import Counter
|
||||||
|
from scipy.spatial import distance
|
||||||
|
|
||||||
"""
|
"""
|
||||||
挑战说明:
|
挑战说明:
|
||||||
@@ -53,14 +55,13 @@ def classify0(inX, dataSet, labels, k=3):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
# 计算输入样本与训练集中每个样本的欧几里得距离
|
# 计算输入样本与训练集中每个样本的欧几里得距离
|
||||||
distances = [np.sqrt(np.sum((x_train - inX) ** 2)) for x_train in dataSet]
|
distances = distance.cdist(dataSet, [inX], metric='euclidean').flatten()
|
||||||
|
|
||||||
# 按距离排序并选择前k个最小的距离
|
# 按距离排序并选择前k个最小的距离
|
||||||
k_indices = np.argsort(distances)[:k]
|
k_indices = np.argsort(distances)[:k]
|
||||||
k_nearest_labels = [labels[i] for i in k_indices]
|
k_nearest_labels = [labels[i] for i in k_indices]
|
||||||
|
|
||||||
# 计算多数标签
|
# 计算多数标签
|
||||||
from collections import Counter
|
|
||||||
label_counts = Counter(k_nearest_labels)
|
label_counts = Counter(k_nearest_labels)
|
||||||
most_common_label = label_counts.most_common(1)[0][0]
|
most_common_label = label_counts.most_common(1)[0][0]
|
||||||
|
|
||||||
@@ -90,7 +91,7 @@ if __name__ == "__main__":
|
|||||||
predicted_label = classify0(test_sample, train_data, train_labels)
|
predicted_label = classify0(test_sample, train_data, train_labels)
|
||||||
print(f"Predicted label: {predicted_label}, Actual label: {test_labels[0]}")
|
print(f"Predicted label: {predicted_label}, Actual label: {test_labels[0]}")
|
||||||
|
|
||||||
# 你也可以遍历整个测试集来评估分类器的性能
|
# 遍历整个测试集来评估分类器的性能
|
||||||
correct_count = 0
|
correct_count = 0
|
||||||
for i in range(len(test_data)):
|
for i in range(len(test_data)):
|
||||||
predicted_label = classify0(test_data[i], train_data, train_labels)
|
predicted_label = classify0(test_data[i], train_data, train_labels)
|
||||||
|
|||||||
Reference in New Issue
Block a user