From 65a57d4383b691008d628b32b83eb603a14b7dd8 Mon Sep 17 00:00:00 2001 From: wujunjie <297081150@qq.com> Date: Sun, 6 Oct 2024 18:12:39 +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 | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/function.py b/function.py index 409b95e..d5db875 100644 --- a/function.py +++ b/function.py @@ -39,7 +39,7 @@ name = "吴俊煯" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels,k=8): +def classify0(inX, dataSet, labels): """ KNN 分类算法。 @@ -51,19 +51,24 @@ def classify0(inX, dataSet, labels,k=8): Returns: - int: 预测的分类标签。 """ - # 确保 k 不大于数据集的大小 - # 计算数据集的协方差矩阵的逆 - VI = np.linalg.inv(np.cov(dataset.T)) -# 计算 inX 与数据集的差值 - diff = dataSet -inX -# 使用矩阵运算计算马氏距离 - distances =np.sqrt(np,sum(diff @ VI * diff,axis=1)) +# 获取数据集的大小 + dataSetSize =dataSet.shape[0] +# 计算数据集的协方差矩阵的逆 + VI = np.linalg.inv(np.cov(dataSet.T)) +# 计算 Mahalanobis 距离 + distances =npzeros(dataSetSize) + for i in range(dataSetSize): + distances[i]=mahalanobis(inX,dataSeti],VI) # 对距离排序,获取前 k 个最近的样本索引 - sortedDistIndices=np.argsort(distances) + sortedDistIndices=distances.argsort) # 统计前 k 个样本的标签 - classCount =np.bincount(labels[sortedDistIndices[:k]]) + classCount ={} + for i in range(9): + voteLabel=labels[sortedDistIndices[i]] + classCount[voteLabel]=classCount.get(voteLabel,0)+1 # 返回出现次数最多的标签 - return np.argmax(classCount) + sortedClasscount=sorted(classCount.items(),key=operator,itemgetter(1),reverse=True + return sortedclassCount[0][0] def load_data(file_path):