From e651b192f7a7fac28a607a70376ad945ba3acb08 Mon Sep 17 00:00:00 2001 From: yuhaopan <1159526601@qq.com> Date: Tue, 15 Oct 2024 20:43:50 +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 | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/function.py b/function.py index 470a4df..9dcfdf1 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,6 @@ # function.py import numpy as np -from numpy.linalg import inv +from numpy.linalg import inv,dot """ 挑战说明: @@ -40,7 +40,7 @@ name = "潘宇豪" def classify0(inX, dataSet, labels, k=3): """ - KNN 分类算法,使用马氏距离,并对特定的第64次错误实例进行修正。 + KNN 分类算法。 参数: - inX (numpy array): 输入待分类的样本。 @@ -51,25 +51,24 @@ def classify0(inX, dataSet, labels, k=3): 返回值: - int: 预测的分类标签。 """ - # 特定实例的手动修正 - # 修正第64次测试错误,数据[5.56500e+03 9.73334e+00 9.77746e-01]被分类到3实际是2 - if np.allclose(inX, [5.56500e+03, 9.73334e+00, 9.77746e-01], atol=1e-2): - return 2 # 返回正确分类 - - # 计算马氏距离 + # 计算均值和协方差的逆 mean = np.mean(dataSet, axis=0) cov_inv = inv(np.cov(dataSet, rowvar=False)) - # 计算每个样本与输入样本的马氏距离 + # 计算输入样本与每个训练样本之间的马氏距离 diff = dataSet - inX distances = np.sqrt(np.einsum('ij,jk->i', diff, np.dot(cov_inv, diff.T))) # 找到最近的k个邻居 sortedDistIndices = np.argsort(distances)[:k] - classCount = np.bincount(labels[sortedDistIndices].astype(int)) + nearest_labels = labels[sortedDistIndices] + + # 使用np.bincount统计类别出现次数 + classCount = np.bincount(nearest_labels.astype(int)) # 返回出现次数最多的类别 return np.argmax(classCount) + def load_data(file_path): """