From 8aa000191460f8f3f18de52727a4ff37314780c9 Mon Sep 17 00:00:00 2001 From: Frae19 <515745323@qq.com> Date: Thu, 17 Oct 2024 16:58:13 +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 | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/function.py b/function.py index 3a48f96..8877e42 100644 --- a/function.py +++ b/function.py @@ -57,24 +57,21 @@ def classify0(inX, dataSet, labels, k=3): # 计算欧式距离 dataSetSize = dataSet.shape[0] diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet - sqDiffMat = diffMat**2 - sqDistances = sqDiffMat.sum(axis=1) - distances = np.sqrt(sqDistances) + distances = np.sqrt(np.sum(diffMat ** 2, axis=1)) # 按距离从小到大排序 sortedDistIndices = distances.argsort() - - # 选择距离最小的k个点 + classCount = {} for i in range(k): voteIlabel = labels[sortedDistIndices[i]] - classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 + weight = 1 / (distances[sortedDistIndices[i]] + 1e-8) # 防止除以零,加入微小值 + classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight # 按类别票数从大到小排序 sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) - # 返回出现频率最高的类别 - return sortedClassCount[0][0] + return sortedClassCount[0][0] def load_data(file_path):