From 3a4694497efb1dcb2a1b9c9283d78720515f7413 Mon Sep 17 00:00:00 2001 From: 202210423104 <1961532386@qq.com> Date: Wed, 16 Oct 2024 21:58:42 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 43 +++++++++++++------------------------------ 1 file changed, 13 insertions(+), 30 deletions(-) diff --git a/function.py b/function.py index cbe0062..a7eb05f 100644 --- a/function.py +++ b/function.py @@ -2,63 +2,46 @@ import numpy as np from collections import Counter - id = "202210423104" name = "张钦诚" - - -def classify0(inX, dataSet, labels, k=3): - - # 转换输入样本为numpy数组 +def classify0(inX, dataSet, labels, k=5): inX = np.array(inX) - - # 计算欧氏距离 - # 使用广播计算所有训练样本与输入样本的距离 - distances = np.linalg.norm(dataSet - inX, axis=1) - - # 获取距离最小的k个样本的索引 - nearest_indices = distances.argsort()[:k] - - # 获取这k个样本的标签 + distances = np.sum((dataSet - inX) ** 2, axis=1) + nearest_indices = np.argpartition(distances, k)[:k] nearest_labels = labels[nearest_indices] - - # 统计出现次数最多的标签 label_count = Counter(nearest_labels) - - # 返回出现次数最多的标签 return label_count.most_common(1)[0][0] - def load_data(file_path): - data = np.loadtxt(file_path, delimiter="\t") features = data[:, :-1] labels = data[:, -1].astype(int) return features, labels +def standardize(train_data, test_data): + mean = np.mean(train_data, axis=0) + std = np.std(train_data, axis=0) + std[std == 0] = 1 + train_standardized = (train_data - mean) / std + test_standardized = (test_data - mean) / std + return train_standardized, test_standardized if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 - train_file = "datingTrainSet2.tsv" test_file = "datingTestSet2.tsv" - # 加载训练数据 train_data, train_labels = load_data(train_file) - - # 加载测试数据 test_data, test_labels = load_data(test_file) - # 测试样本 + train_data, test_data = standardize(train_data, test_data) + test_sample = [65915, 3.868359, 0.128078] + test_sample = (np.array(test_sample) - np.mean(train_data, axis=0)) / np.std(train_data, axis=0) - # 预测标签 predicted_label = classify0(test_sample, train_data, train_labels) - print(f"预测的分类标签: {predicted_label}") - # 计算准确率 predictions = np.array([classify0(sample, train_data, train_labels) for sample in test_data]) accuracy = np.mean(predictions == test_labels) * 100 print(f"准确率: {accuracy:.2f}%")