From 16b9377f359b60b392a3195e768edb752fbd94f5 Mon Sep 17 00:00:00 2001 From: zhe <2904040094@qq.com> Date: Wed, 23 Oct 2024 11:40:33 +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 | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/function.py b/function.py index ddc4b6c..7faac63 100644 --- a/function.py +++ b/function.py @@ -1,7 +1,8 @@ # function.py import numpy as np import os - +from scipy.spatial.distance import mahalanobis +from collections import Counter """ 实验说明: - 自行编写实现数据加载与 kNN 的手写数字分类算法。 @@ -43,11 +44,15 @@ name = "李劲" # 这里写自己的代码实现 def classify(input_vector, dataSet, labels, k=1): """ - KNN 分类算法。 + KNN 分类算法,使用马氏距离。 """ - # 计算欧式距离 - distances = np.linalg.norm(dataSet - input_vector, axis=1) - + # 计算协方差矩阵及其逆 + cov_matrix = np.cov(dataSet.T) + inv_cov_matrix = np.linalg.inv(cov_matrix) + + # 计算马氏距离 + distances = [mahalanobis(input_vector, point, inv_cov_matrix) for point in dataSet] + # 获取距离最近的 k 个样本的索引 k_indices = np.argsort(distances)[:k] @@ -55,9 +60,8 @@ def classify(input_vector, dataSet, labels, k=1): k_nearest_labels = [labels[i] for i in k_indices] # 找出出现次数最多的标签 - from collections import Counter most_common = Counter(k_nearest_labels).most_common(1)[0][0] - + return most_common def load_dataset(directory):