From 8793a9b39cd0f83901f64bb1bb5da0790e8d950e Mon Sep 17 00:00:00 2001 From: yuhaopan <1159526601@qq.com> Date: Thu, 26 Sep 2024 16:55:19 +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 | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/function.py b/function.py index 33111b7..25f0261 100644 --- a/function.py +++ b/function.py @@ -38,7 +38,7 @@ name = "潘宇豪" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=5): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -51,24 +51,26 @@ def classify0(inX, dataSet, labels, k=5): 返回值: - int: 预测的分类标签。 """ - # 计算输入样本与训练数据集中每个样本的欧氏距离 - diffMat = np.tile(inX, (dataSet.shape[0], 1)) - dataSet - sqDiffMat = diffMat**2 - sqDistances = sqDiffMat.sum(axis=1) - distances = np.sqrt(sqDistances) + # 计算协方差矩阵及其逆 + 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() + sortedDistIndices = distances.argsort()[:k] + + # 进行简单投票 classCount = {} - - for i in range(k): - voteIlabel = labels[sortedDistIndices[i]] + for i in sortedDistIndices: + voteIlabel = labels[i] classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 - + # 返回出现次数最多的类别 sortedClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True) return sortedClassCount[0][0] - + def load_data(file_path): """ 加载TSV格式的数据文件。