From 6b2538788ee8e7e9eaad38edfd6ef77299a3b4d5 Mon Sep 17 00:00:00 2001 From: llll <2992513220@qq.com> Date: Thu, 21 Nov 2024 09:07:02 +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 | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/function.py b/function.py index 2393b3b..a09f8b2 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423219" +name = "李燕如" """ @@ -41,7 +41,7 @@ name = "test_name" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=0): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -54,6 +54,26 @@ def classify0(inX, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ + # 计算待分类样本与训练集中每个样本的距离 + distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + + # 获取距离最近的 k 个样本的索引 + k_indices = np.argsort(distances)[:k] + + # 获取这些样本对应的标签 + k_nearest_labels = labels[k_indices] + + # 统计每个类别出现的次数 + count = {} + for label in k_nearest_labels: + if label in count.keys(): + count[label] += 1 + else: + count[label] = 1 + + # 找到出现次数最多的类别 + sorted_count = sorted(count.items(), key=lambda x: x[1], reverse=True) + return sorted_count[0][0] def load_data(file_path): @@ -73,4 +93,4 @@ if __name__ == "__main__": train_data, train_labels = load_data(train_file) - print(classify0([65915, 3.868359, 0.128078], train_data, train_labels)) + print(classify0([65915, 3.868359, 0.128078], train_data, train_labels)) \ No newline at end of file