From 7c9a9f83474d6163c974b198425fb47ca65e2bb9 Mon Sep 17 00:00:00 2001 From: yuhaopan <1159526601@qq.com> Date: Thu, 26 Sep 2024 17:44:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/function.py b/function.py index 21978c5..5102d74 100644 --- a/function.py +++ b/function.py @@ -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):