generated from LufsX/Challenge-kNN
This commit is contained in:
+7
-8
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user