generated from LufsX/Challenge-kNN
This commit is contained in:
+15
-11
@@ -51,17 +51,21 @@ def classify0(inX, dataSet, labels,k=4):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
k=min(k,dataSet.shape[0])
|
# 计算每个训练样本与待分类样本之间的欧氏距离
|
||||||
diffMat =np.tile(inX,(dataSet.shape[0],1))- dataSet
|
distances = [np.sqrt(np.sum((x_train - inX) ** 2)) for x_train in dataSet]
|
||||||
sqDiffMat =diffMat **2
|
|
||||||
distances =np.sqrt(sqDiffMat.sum(axis=1))
|
# 按距离排序,并获取最近的 k 个邻居的索引
|
||||||
sortedDistIndicies=distances.argsort()
|
k_indices = np.argsort(distances)[:k]
|
||||||
classCount={}
|
|
||||||
for i in range(k):
|
# 获取这 k 个邻居的标签
|
||||||
voteIlabel=labels[sortedDistIndicies[i]]
|
k_nearest_labels = [labels[i] for i in k_indices]
|
||||||
classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
|
|
||||||
sortedClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True)
|
# 统计每个标签出现的次数,并找出出现次数最多的标签
|
||||||
return sortedclassCount[0][0]
|
from collections import Counter
|
||||||
|
most_common = Counter(k_nearest_labels).most_common(1)
|
||||||
|
|
||||||
|
# 返回出现次数最多的标签
|
||||||
|
return most_common[0][0]
|
||||||
|
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
|
|||||||
Reference in New Issue
Block a user