From 2c70be6d1c0731606c9963a33691e51a81fb4b03 Mon Sep 17 00:00:00 2001 From: Dengddd <3149942468@qq.com> Date: Tue, 22 Oct 2024 20:51:36 +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, 16 insertions(+), 7 deletions(-) diff --git a/function.py b/function.py index 6b18f60..3d7ae56 100644 --- a/function.py +++ b/function.py @@ -45,21 +45,30 @@ import numpy as np import os from collections import Counter -def classify(input_vector, dataSet, labels, k=1): # 设置默认值 k=1 - """使用 KNN 算法对输入样本进行分类。""" +def classify(input_vector, dataSet, labels, k=1): + """使用 KNN 算法对输入样本进行分类,使用加权多数表决法。""" # 计算输入向量与训练集之间的欧氏距离 distances = np.linalg.norm(dataSet - input_vector, axis=1) # 根据距离排序并获取索引 sorted_indices = distances.argsort() # 选择距离最近的k个点 k_nearest_labels = labels[sorted_indices[:k]] - # 统计k个点中各类别的数量 - count = Counter(k_nearest_labels) - # 返回数量最多的类别标签 -return count.most_common(1)[0][0] + k_nearest_distances = distances[sorted_indices[:k]] + + # 计算权重:距离越小,权重越大 + weights = 1 / (k_nearest_distances + 1e-10) # 加小常数防止除零 + + # 使用加权计数 + count = Counter() + for label, weight in zip(k_nearest_labels, weights): + count[label] += weight + + # 返回加权计数最多的类别标签 + return count.most_common(1)[0][0] # 为评测系统创建别名 -classify = classify_mahalanobis +classify = classify + def load_dataset(directory): """加载数据集中的图像,并将其转换为特征向量和标签。"""