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