From c02a62fa2266a06e9a0d5009aea99b0e46667751 Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Sun, 20 Oct 2024 13:44:26 +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, 9 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index aeea5fa..01d1c65 100644 --- a/function.py +++ b/function.py @@ -55,15 +55,19 @@ def classify(input_vector, dataSet, labels, k=2): - input_vector (numpy array): 输入待分类的样本(1xN)。 - dataSet (numpy array): 训练数据集(MxN)。 - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,默认值为 3。 + - k (int): kNN 算法参数,默认值为 2。 返回: - int: 预测的分类标签。 """ - # 计算输入向量与训练集之间的欧氏距离 - distances = np.sum((input_vector - dataSet) ** 2, axis=1) - sorted_indices = distances.argsort() - k_nearest_distances = distances[sorted_indices[:k]] + # 将欧氏距离改为马氏距离 + mean_vector = np.mean(dataSet, axis=0) + cov_matrix = np.cov(dataSet.T) + inv_cov_matrix = np.linalg.inv(cov_matrix) + diff_vector = input_vector - dataSet + mahalanobis_distances = np.sqrt(np.einsum('ij,jk,ik->i', diff_vector, inv_cov_matrix, diff_vector.T)) + sorted_indices = mahalanobis_distances.argsort() + k_nearest_distances = mahalanobis_distances[sorted_indices[:k]] k_nearest_labels = labels[sorted_indices[:k]] # 计算权重(距离的倒数)