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

This commit is contained in:
2024-09-26 17:44:08 +08:00
parent 714a5119d4
commit 7c9a9f8347
+7 -8
View File
@@ -64,20 +64,19 @@ def classify0(inX, dataSet, labels, k=3, dynamic_k=True):
distances = np.array(distances)
sortedDistIndices = distances.argsort()
# 动态调整 k 值
if dynamic_k:
median_distance = np.median(distances)
k_dynamic = min(max(3, int(len(distances) * (median_distance / np.max(distances)))), 10)
k = k_dynamic
# 距离加权投票
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
index = sortedDistIndices[i]
voteIlabel = labels[index]
weight = 1 / (distances[index] + 1e-5) # 使用距离的倒数作为权重,避免除以零
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight
# 返回权重最高的类别
sortedClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True)
return sortedClassCount[0][0]
def load_data(file_path):