generated from LufsX/Challenge-kNN
This commit is contained in:
+9
-3
@@ -2,6 +2,7 @@
|
||||
import numpy as np
|
||||
from collections import Counter
|
||||
from scipy.spatial import distance
|
||||
# from sklearn.preprocessing import StandardScaler
|
||||
|
||||
"""
|
||||
挑战说明:
|
||||
@@ -71,7 +72,6 @@ def classify0(inX, dataSet, labels, k=9):
|
||||
return most_common_label
|
||||
|
||||
|
||||
|
||||
def load_data(file_path):
|
||||
"""
|
||||
加载 TSV 格式数据文件。
|
||||
@@ -81,13 +81,20 @@ def load_data(file_path):
|
||||
labels = data[:, -1].astype(int)
|
||||
return features, labels
|
||||
|
||||
|
||||
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)
|
||||
|
||||
# # 特征缩放
|
||||
# scaler = StandardScaler()
|
||||
# train_data = scaler.fit_transform(train_data)
|
||||
# test_data = scaler.transform(test_data)
|
||||
|
||||
# 测试 classify0 函数
|
||||
test_sample = test_data[0] # 使用测试集中的第一个样本进行测试
|
||||
predicted_label = classify0(test_sample, train_data, train_labels)
|
||||
@@ -100,5 +107,4 @@ if __name__ == "__main__":
|
||||
if predicted_label == test_labels[i]:
|
||||
correct_count += 1
|
||||
accuracy = correct_count / len(test_data)
|
||||
print(f"Accuracy: {accuracy * 100:.2f}%")
|
||||
|
||||
print(f"Accuracy: {accuracy * 100:.2f}%")
|
||||
Reference in New Issue
Block a user