From 28ba6698062ad15e3848b351ecf922aa5e00b09d Mon Sep 17 00:00:00 2001 From: sn <3298564802@qq.com> Date: Wed, 16 Oct 2024 18:58:18 +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 | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/function.py b/function.py index 2393b3b..611595b 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423112" +name = "严锡好" """ @@ -41,7 +41,7 @@ name = "test_name" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=0): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -49,11 +49,26 @@ def classify0(inX, dataSet, labels, k=0): - inX (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 + - k (int): kNN 算法参数,默认值为 3。 Returns: - int: 预测的分类标签。 """ + # 计算待分类样本与训练集中每个样本的距离 + distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + + # 获取距离最近的 k 个样本的索引 + sortedDistIndices = distances.argsort()[:k] + + # 获取这些样本对应的标签 + classCount = {} + for i in sortedDistIndices: + voteLabel = labels[i] + classCount[voteLabel] = classCount.get(voteLabel, 0) + 1 + + # 选择出现次数最多的标签作为预测标签 + sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) + return sortedClassCount[0][0] def load_data(file_path): @@ -68,9 +83,10 @@ def load_data(file_path): if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改 - train_file = "datingTrainSet2.tsv" - train_data, train_labels = load_data(train_file) - print(classify0([65915, 3.868359, 0.128078], train_data, train_labels)) + # 测试一个样本 + test_sample = np.array([65915, 3.868359, 0.128078]) + predicted_label = classify0(test_sample, train_data, train_labels) + print(f"The predicted label for the test sample is: {predicted_label}") \ No newline at end of file