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