generated from LufsX/Challenge-kNN
This commit is contained in:
+4
-2
@@ -71,11 +71,13 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
# 按距离从小到大排序
|
||||
sortedDistIndices = distances.argsort()
|
||||
|
||||
# **步骤4:选择距离最小的k个点,进行加权投票**
|
||||
classCount = {}
|
||||
for i in range(k):
|
||||
voteIlabel = labels[sortedDistIndices[i]]
|
||||
weight = 1 / (distances[sortedDistIndices[i]] + 1e-8) # 防止除以零,加入微小值
|
||||
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight
|
||||
# 使用距离的倒数作为权重,防止距离为0时除以零
|
||||
weight = 1 / (distances[sortedDistIndices[i]] + 1e-8)
|
||||
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight
|
||||
|
||||
# 按类别票数从大到小排序
|
||||
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
||||
|
||||
Reference in New Issue
Block a user