From 16f4b687160d3535efb4a4cc56c2318f1e5ab57e Mon Sep 17 00:00:00 2001 From: Dengddd <3149942468@qq.com> Date: Tue, 22 Oct 2024 20:01:32 +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 | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index 07bed3a..4cb1f3f 100644 --- a/function.py +++ b/function.py @@ -45,18 +45,32 @@ import numpy as np import os from collections import Counter -def classify(input_vector, dataSet, labels, k=3): # 设置默认值 k=1 - """使用 KNN 算法对输入样本进行分类。""" - # 计算输入向量与训练集之间的欧氏距离 - distances = np.linalg.norm(dataSet - input_vector, axis=1) +def classify_mahalanobis(input_vector, dataSet, labels, k=1): + """使用 KNN 算法并基于马氏距离对输入样本进行分类。""" + # 计算数据集的协方差矩阵及其逆矩阵 + cov_matrix = np.cov(dataSet, rowvar=False) + + # 对协方差矩阵添加正则化 + cov_matrix += np.eye(cov_matrix.shape[0]) * 1e-5 + + # 计算协方差矩阵的逆矩阵 + inv_cov_matrix = np.linalg.inv(cov_matrix) + + # 计算马氏距离 + diffMat = dataSet - input_vector + distances = np.sqrt(np.sum(np.dot(diffMat, inv_cov_matrix) * diffMat, 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] +return count.most_common(1)[0][0] def load_dataset(directory): """加载数据集中的图像,并将其转换为特征向量和标签。"""