From 04fccf817952ea69191db026a19e82d1d7d740ca Mon Sep 17 00:00:00 2001 From: wujunjie <297081150@qq.com> Date: Thu, 26 Sep 2024 10:31: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 | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/function.py b/function.py index 7f551ad..03376ee 100644 --- a/function.py +++ b/function.py @@ -50,15 +50,24 @@ def classify0(inX, dataSet, labels,k=3): Returns: - int: 预测的分类标签。 """ - distances = [np.sqrt(np.sum((inX - x) ** 2)) for x in dataSet] + dataSetSize = dataSet.shape[0] + diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet + sqDiffMat = diffMat ** 2 + sqDistances = sqDiffMat.sum(axis=1) + distances = sqDistances ** 0.5 - k_indices = np.argsort(distances)[:k] - k_nearest_labels = [labels[i] for i in k_indices] - - from collections import Counter - vote_result = Counter(k_nearest_labels).most_common(1) - - return vote_result[0][0] + # 对距离进行排序,并获取索引 + sortedDistIndicies = distances.argsort() + + # 选择距离最小的k个点 + classCount = {} + for i in range(k): + voteIlabel = labels[sortedDistIndicies[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): """