diff --git a/function.py b/function.py index 89b7dc3..787bfd7 100644 --- a/function.py +++ b/function.py @@ -1,5 +1,7 @@ # function.py import numpy as np +from scipy.spatial.distance import mahalanobis +import operator """ 挑战说明: @@ -23,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423229" +name = "向兴宇" """ @@ -50,6 +52,31 @@ def classify0(inX, dataSet, labels): Returns: - int: 预测的分类标签。 """ + # 获取数据集的大小 + dataSetSize = dataSet.shape[0] + + # 计算数据集的协方差矩阵的逆 + VI = np.linalg.inv(np.cov(dataSet.T)) + + # 计算 Mahalanobis 距离 + distances = np.zeros(dataSetSize) + for i in range(dataSetSize): + distances[i] = mahalanobis(inX, dataSet[i], VI) + + # 对距离排序,获取前 k 个最近的样本索引 + sortedDistIndices = distances.argsort() + + # 统计前 k 个样本的标签 + classCount = {} + for i in range(3): + voteLabel = labels[sortedDistIndices[i]] + classCount[voteLabel] = classCount.get(voteLabel, 0) + 1 + + # 返回出现次数最多的标签 + sortedClassCount = sorted( + classCount.items(), key=operator.itemgetter(1), reverse=True + ) + return sortedClassCount[0][0] def load_data(file_path): @@ -71,8 +98,25 @@ def load_data(file_path): 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) - print(classify0([65915, 3.868359, 0.128078], train_data, train_labels)) + correct = 0 + total = len(test_data) + + for i in range(total): + # 获取测试数据中的每个样本 + result = classify0(test_data[i], train_data, train_labels) + if result == test_labels[i]: + correct += 1 + else: + print( + f"第 {i+1} 次测试错误,数据 {test_data[i]} 被分类到 {result} 实际是 {test_labels[i]}" + ) + + accuracy = correct / total + print(f"测试集正确个数 {correct},总个数 {total},正确率 {accuracy}") diff --git a/requirements.txt b/requirements.txt index 4bb300f..b4c80c3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ numpy==2.1.1 requests==2.32.3 +scipy