From 4c7715a4b193cd253bc4fe18b90995253421a944 Mon Sep 17 00:00:00 2001 From: llll <2992513220@qq.com> Date: Thu, 21 Nov 2024 09:17:12 +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 | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/function.py b/function.py index d628e93..2cdfd8e 100644 --- a/function.py +++ b/function.py @@ -41,13 +41,15 @@ name = "李燕如" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=5): +import numpy as np + +def classify0(inX, dataSet, labels, k=3): # 数据标准化 dataSet = (dataSet - np.mean(dataSet, axis=0)) / np.std(dataSet, axis=0) inX = (inX - np.mean(dataSet, axis=0)) / np.std(dataSet, axis=0) # 计算距离 - distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + distances = [distance.euclidean(inX, x) for x in dataSet] # 获取k个最近邻的索引 k_indices = np.argsort(distances)[:k] @@ -55,14 +57,16 @@ def classify0(inX, dataSet, labels, k=5): # 获取这些样本对应的标签 k_nearest_labels = labels[k_indices] - # 权重分配(距离的倒数) - weights = 1 / distances[k_indices] - weights /= np.sum(weights) # 归一化权重 + # 投票决定分类 + result = {} + for label in k_nearest_labels: + if label in result: + result[label] += 1 + else: + result[label] = 1 - # 加权投票 - prediction = np.argmax(np.bincount(k_nearest_labels, weights=weights)) - - return prediction + # 返回出现次数最多的类别 + return max(result, key=result.get) def load_data(file_path): data = np.loadtxt(file_path, delimiter="\t")