From 8630be16533eea8827884e5b2c82b59e787d8100 Mon Sep 17 00:00:00 2001 From: meixiaodong <3081674342@qq.com> Date: Tue, 22 Oct 2024 02:19: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 | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/function.py b/function.py index 2393b3b..183c427 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423211" +name = "梅晓东" """ @@ -54,6 +54,61 @@ def classify0(inX, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ + # function.py +import numpy as np +import pandas as pd +from collections import Counter + +# 确保填写自己的学号和姓名 +# 学号: YOUR_STUDENT_ID +# 姓名: YOUR_NAME + +def classify(inx, dataset, labels, k=3): + """ + 使用kNN算法对输入样本进行分类。 + + :param inx: 要分类的输入样本(1D数组) + :param dataset: 训练数据集(2D数组) + :param labels: 训练集对应的标签(1D数组) + :param k: 最近邻居的数量 + :return: 输入样本的预测标签 + """ + + # 将输入转换为numpy数组以便于操作 + dataset = np.array(dataset) + labels = np.array(labels) + inx = np.array(inx) + + # 计算输入样本与所有样本的距离 + distances = np.linalg.norm(dataset - inx, axis=1) + + # 获取最近k个邻居的索引 + k_indices = np.argsort(distances)[:k] + + # 获取这k个邻居的标签 + k_nearest_labels = labels[k_indices] + + # 使用多数投票确定预测标签 + most_common = Counter(k_nearest_labels).most_common(1) + return most_common[0][0] + +# 测试代码示例(可选择性运行) +if __name__ == "__main__": + # 加载训练数据集 + train_data = pd.read_csv('datingTrainset2.tsv', sep='\t') + train_labels = train_data['label'].values # 替换'label'为你的实际标签列名 + train_features = train_data.drop('label', axis=1).values # 删除标签列 + + # 加载测试数据集 + test_data = pd.read_csv('datingTestset2.tsv', sep='\t') + test_labels = test_data['label'].values # 替换'label'为你的实际标签列名 + test_features = test_data.drop('label', axis=1).values # 删除标签列 + + # 示例:对一个样本进行分类 + sample = test_features[0] # 使用测试集中第一个样本 + predicted_label = classify(sample, train_features, train_labels, k=3) + print(f"Predicted label: {predicted_label}") + def load_data(file_path):