From 870aa2fc2d75564592a68fdc151b1e19979f8965 Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Sun, 20 Oct 2024 14:05:01 +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 | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/function.py b/function.py index 03f3774..80ff2f8 100644 --- a/function.py +++ b/function.py @@ -45,15 +45,21 @@ import numpy as np import os from collections import Counter -def classify(input_vector, dataSet, labels, k=1): +def classify(input_vector, dataSet, labels, k=3): """使用 KNN 算法对输入样本进行分类。""" - distances = np.sum((input_vector - dataSet) ** 2, axis=1) + # 计算协方差矩阵和其逆矩阵 + cov_matrix = np.cov(dataSet, rowvar=False) + inv_cov_matrix = np.linalg.inv(cov_matrix + 1e-5 * np.eye(cov_matrix.shape[0])) # 添加小常数以防止奇异矩阵 + + # 计算马氏距离 + diffs = input_vector - dataSet + distances = np.sqrt(np.einsum('ij,jk->i', diffs, np.dot(inv_cov_matrix, diffs.T))) + sorted_indices = distances.argsort() - k_nearest_distances = distances[sorted_indices[:k]] k_nearest_labels = labels[sorted_indices[:k]] # 计算权重(距离的倒数),避免除以零 - weights = 1 / (k_nearest_distances + 1e-5) + weights = 1 / (distances[sorted_indices[:k]] + 1e-5) # 归一化权重 weights /= weights.sum()