diff --git a/function.py b/function.py index 420ecfb..4c867bf 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423109" +name = "孔祥芷" """ @@ -53,23 +53,45 @@ def classify0(inX, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ + dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1)) + sorted_index = np.argsort(dists) + class_count = {} + for i in range(k): + vote_label = labels[sorted_index[i]] + if vote_label not in class_count.keys(): + class_count[vote_label] = 1 + else: + class_count[vote_label] += 1 + sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True) + return sorted_class_count[0][0] + def load_data(file_path): - """ - 加载 TSV 格式数据文件。 - """ + + #加载 TSV 格式数据文件。 + data = np.loadtxt(file_path, delimiter="\t") features = data[:, :-1] labels = data[:, -1].astype(int) return features, labels + + 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_path = "datingTrainSet2.tsv" + train_features, train_labels = load_data(train_file_path) + + test_file_path = "datingTestSet2.tsv" + test_features, test_labels = load_data(test_file_path) + + correct_count = 0 + for i in range(len(test_features)): + test_feature = test_features[i].reshape(1, -1) + predict_label = classify0(test_feature, train_features, train_labels, k=3) + correct_count += (predict_label == test_labels[i]) + + accuracy = correct_count / len(test_features) + print(f"Accuracy: {accuracy:.2f}") \ No newline at end of file