From a53439dc964440776a8ceff0160734748798f103 Mon Sep 17 00:00:00 2001 From: cy <939601402@qq.com> Date: Tue, 1 Oct 2024 19:29:51 +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 | 47 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/function.py b/function.py index 2ce8f6f..7e1efe0 100644 --- a/function.py +++ b/function.py @@ -23,8 +23,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423117" +name = "程悦" """ @@ -38,7 +38,7 @@ name = "test_name" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=""): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -52,6 +52,20 @@ def classify0(inX, dataSet, labels, k=""): - int: 预测的分类标签。 """ + # 计算输入样本与训练集中每个样本的欧几里得距离 + distances = [np.sqrt(np.sum((x_train - inX) ** 2)) for x_train in dataSet] + + # 按距离排序并选择前k个最小的距离 + k_indices = np.argsort(distances)[:k] + k_nearest_labels = [labels[i] for i in k_indices] + + # 计算多数标签 + from collections import Counter + label_counts = Counter(k_nearest_labels) + most_common_label = label_counts.most_common(1)[0][0] + + return most_common_label + def load_data(file_path): """ @@ -64,10 +78,23 @@ 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)) + # 以下代码可用于测试,可自行随意修改 + train_file = "datingTrainSet2.tsv" + test_file = "datingTestSet2.tsv" + + train_data, train_labels = load_data(train_file) + test_data, test_labels = load_data(test_file) + + # 测试 classify0 函数 + test_sample = test_data[0] # 使用测试集中的第一个样本进行测试 + predicted_label = classify0(test_sample, train_data, train_labels) + print(f"Predicted label: {predicted_label}, Actual label: {test_labels[0]}") + + # 你也可以遍历整个测试集来评估分类器的性能 + correct_count = 0 + for i in range(len(test_data)): + predicted_label = classify0(test_data[i], train_data, train_labels) + if predicted_label == test_labels[i]: + correct_count += 1 + accuracy = correct_count / len(test_data) + print(f"Accuracy: {accuracy * 100:.2f}%")