From 133eabcf372814a5deba9186d223e247e66f8c9c Mon Sep 17 00:00:00 2001 From: heart20003 <1789588961@qq.com> Date: Thu, 17 Oct 2024 16:45:17 +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 | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/function.py b/function.py index 6a2631e..b1d0793 100644 --- a/function.py +++ b/function.py @@ -59,23 +59,20 @@ def classify0(inX, dataSet,labels, k=3): distances = np.sum(diff @ inv_cov_matrix * diff, axis=1) # 获取距离最小的 k 个样本的索引 - sorted_indices = np.argsort(distances)[:k] + sorted_indices = np.argsort(distances)[:k] - # 获取 k 个最近邻的标签和对应的距离 + # 获取 k 个最近邻的标签 nearest_labels = [labels[i] for i in sorted_indices] - nearest_distances = distances[sorted_indices] - # 计算每个标签的加权投票 - label_weight = {} - for i, label in enumerate(nearest_labels): - # 反距离作为权重,避免距离为0的情况 - weight = 1 / (nearest_distances[i] + 1e-10) # 加一个小值避免除以零 - if label in label_weight: - label_weight[label] += weight + # 统计 k 个最近邻中每个类别的出现次数 + label_count = {} + for label in nearest_labels: + if label in label_count: + label_count[label] += 1 else: - label_weight[label] = weight + label_count[label] = 1 - # 找到加权投票中出现次数最多的标签 - predicted_label = max(label_weight, key=label_weight.get) + # 找到出现次数最多的标签 + predicted_label = max(label_count, key=label_count.get) return predicted_label