更新 function.py
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 11s

This commit is contained in:
2024-10-17 17:09:30 +08:00
parent 3a71bdfd44
commit af30974dcb
+4 -2
View File
@@ -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)