From 80744d7adad598f36932ad0084c44e5f8b1619af Mon Sep 17 00:00:00 2001 From: zhe <2904040094@qq.com> Date: Wed, 16 Oct 2024 20:44:26 +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 | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index 2393b3b..a6272dc 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,7 @@ # function.py import numpy as np - +from collections import Counter +from sklearn.preprocessing import StandardScaler # 用于数据标准化 """ 挑战说明: - 自行编写实现 KNN 分类算法。 @@ -25,8 +26,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423111" +name = "李劲" """ @@ -54,7 +55,28 @@ def classify0(inX, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ - + # 确保输入样本inX是numpy数组 + inX = np.array(inX) + + # 标准化数据(使用训练数据的均值和标准差来转换输入数据和训练数据) + scaler = StandardScaler().fit(dataSet) + dataSet_scaled = scaler.transform(dataSet) + inX_scaled = scaler.transform([inX]) + + # 计算输入样本与所有训练样本之间的欧几里得距离 + distances = [np.sqrt(np.sum((inX_scaled[0] - x_train) ** 2)) for x_train in dataSet_scaled] + + # 根据距离对训练样本进行排序,并获取前k个最近邻的索引 + k_indices = np.argsort(distances)[:k] + + # 根据索引获取前k个最近邻的标签 + k_nearest_labels = [labels[i] for i in k_indices] + + # 使用Counter找出出现次数最多的标签 + most_common = Counter(k_nearest_labels).most_common(1) + + # 返回出现次数最多的标签(即预测的分类标签) + return most_common[0][0] def load_data(file_path): """ @@ -70,7 +92,7 @@ if __name__ == "__main__": # 以下代码可用于测试,可自行随意修改 train_file = "datingTrainSet2.tsv" - + test_file = "datingTestSet2.tsv" train_data, train_labels = load_data(train_file) print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))