From 2cf474c644b106801a1716e24f5e13f2d3960218 Mon Sep 17 00:00:00 2001 From: heart20003 <1789588961@qq.com> Date: Thu, 17 Oct 2024 16:39:06 +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 | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/function.py b/function.py index 73c6ece..6a2631e 100644 --- a/function.py +++ b/function.py @@ -54,25 +54,28 @@ def classify0(inX, dataSet,labels, k=3): inv_S[nonzero_indices] = 1 / S[nonzero_indices] inv_cov_matrix = VT.T @ np.diag(inv_S) @ U.T - # 计算马氏距离的平方 + # 计算马氏距离 diff = normalized_dataSet - normalized_inX - squared_distances = np.einsum('ij,jk->i', diff, inv_cov_matrix @ diff.T) + 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] - # 统计 k 个最近邻中每个类别的出现次数 - label_count = {} - for label in nearest_labels: - if label in label_count: - label_count[label] += 1 + # 计算每个标签的加权投票 + 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 else: - label_count[label] = 1 + label_weight[label] = weight - # 找到出现次数最多的标签 - predicted_label = max(label_count, key=label_count.get) + # 找到加权投票中出现次数最多的标签 + predicted_label = max(label_weight, key=label_weight.get) return predicted_label