From 485951645e2c81d00c1d5d3c0be6a5c24a936df2 Mon Sep 17 00:00:00 2001 From: yuhaopan <1159526601@qq.com> Date: Thu, 26 Sep 2024 16:59:52 +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 | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/function.py b/function.py index 25f0261..587fc93 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,6 @@ # function.py import numpy as np - +from numpy.linalg import inv, det """ 挑战说明: - 自行编写实现 KNN 分类算法。 @@ -51,20 +51,22 @@ def classify0(inX, dataSet, labels, k=3): 返回值: - int: 预测的分类标签。 """ - # 计算协方差矩阵及其逆 - covariance_matrix = np.cov(dataSet, rowvar=False) - inv_covmat = inv(covariance_matrix) - - # 计算马氏距离 - distances = np.array([mahalanobis(inX, dataSet[i], inv_covmat) for i in range(dataSet.shape[0])]) - - # 对距离进行排序并找到最近的k个邻居 - sortedDistIndices = distances.argsort()[:k] + mean = np.mean(dataSet, axis=0) + cov_inv = inv(np.cov(dataSet, rowvar=False)) - # 进行简单投票 + # 计算输入样本与每个训练样本之间的马氏距离 + distances = [] + for data in dataSet: + diff = inX - data + distance = np.sqrt(np.dot(np.dot(diff, cov_inv), diff.T)) + distances.append(distance) + + # 对距离进行排序并找到最近的k个邻居 + distances = np.array(distances) + sortedDistIndices = distances.argsort() classCount = {} - for i in sortedDistIndices: - voteIlabel = labels[i] + for i in range(k): + voteIlabel = labels[sortedDistIndices[i]] classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 返回出现次数最多的类别