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

This commit is contained in:
2024-10-22 19:53:54 +08:00
parent 279037c36f
commit 3f38c59b1e
+2 -9
View File
@@ -27,17 +27,10 @@ def classify(input_vector, dataSet, labels, k=3):
# 获取距离最近的 k 个样本的索引 # 获取距离最近的 k 个样本的索引
sortedDistIndices = distances.argsort() sortedDistIndices = distances.argsort()
classCount = {} classCount = {}
weightSum = {}
# 使用加权多数表决法
for i in range(k): for i in range(k):
voteIlabel = labels[sortedDistIndices[i]] voteIlabel = labels[sortedDistIndices[i]]
# 统计每个类别的出现次数,并使用距离的倒数作为权重 # 统计每个类别的出现次数
weight = 1 / (distances[sortedDistIndices[i]] + 1e-5) # 加上一个小常数防止除以零 classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight
weightSum[voteIlabel] = weightSum.get(voteIlabel, 0) + 1
# 计算加权平均值
for className in classCount:
classCount[className] /= weightSum[className]
# 返回出现次数最多的类别 # 返回出现次数最多的类别
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
return sortedClassCount[0][0] return sortedClassCount[0][0]