From 3f38c59b1e90ea9ec49404679460aaadfa4722d6 Mon Sep 17 00:00:00 2001 From: Ultraman <2900311815@qq.com> Date: Tue, 22 Oct 2024 19:53:54 +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 | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/function.py b/function.py index 2641e0b..a83cdb0 100644 --- a/function.py +++ b/function.py @@ -27,17 +27,10 @@ def classify(input_vector, dataSet, labels, k=3): # 获取距离最近的 k 个样本的索引 sortedDistIndices = distances.argsort() classCount = {} - weightSum = {} - # 使用加权多数表决法 for i in range(k): voteIlabel = labels[sortedDistIndices[i]] - # 统计每个类别的出现次数,并使用距离的倒数作为权重 - weight = 1 / (distances[sortedDistIndices[i]] + 1e-5) # 加上一个小常数防止除以零 - classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight - weightSum[voteIlabel] = weightSum.get(voteIlabel, 0) + 1 - # 计算加权平均值 - for className in classCount: - classCount[className] /= weightSum[className] + # 统计每个类别的出现次数 + classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 返回出现次数最多的类别 sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) return sortedClassCount[0][0]