generated from LufsX/Challenge-kNN
This commit is contained in:
+17
-8
@@ -50,15 +50,24 @@ def classify0(inX, dataSet, labels,k=3):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
distances = [np.sqrt(np.sum((inX - x) ** 2)) for x in dataSet]
|
dataSetSize = dataSet.shape[0]
|
||||||
|
diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet
|
||||||
|
sqDiffMat = diffMat ** 2
|
||||||
|
sqDistances = sqDiffMat.sum(axis=1)
|
||||||
|
distances = sqDistances ** 0.5
|
||||||
|
|
||||||
k_indices = np.argsort(distances)[:k]
|
# 对距离进行排序,并获取索引
|
||||||
k_nearest_labels = [labels[i] for i in k_indices]
|
sortedDistIndicies = distances.argsort()
|
||||||
|
|
||||||
from collections import Counter
|
# 选择距离最小的k个点
|
||||||
vote_result = Counter(k_nearest_labels).most_common(1)
|
classCount = {}
|
||||||
|
for i in range(k):
|
||||||
return vote_result[0][0]
|
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]
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user