generated from LufsX/Challenge-kNN
This commit is contained in:
+12
-15
@@ -1,7 +1,8 @@
|
|||||||
# function.py
|
# function.py
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
from sklearn.preprocessing import StandardScaler
|
from sklearn.preprocessing import StandardScaler
|
||||||
from sklearn.model_selection import cross_val_score
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
挑战说明:
|
挑战说明:
|
||||||
@@ -77,28 +78,24 @@ def classify0(inX, dataSet, labels, k=3):
|
|||||||
label_counts = np.bincount(nearest_labels)
|
label_counts = np.bincount(nearest_labels)
|
||||||
return label_counts.argmax()
|
return label_counts.argmax()
|
||||||
|
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
"""
|
"""
|
||||||
加载 TSV 格式数据文件。
|
加载 TSV 格式数据文件。
|
||||||
"""
|
"""
|
||||||
data = np.loadtxt(file_path, delimiter="\t")
|
data = pd.read_csv(file_path, sep='\t', header=None).values
|
||||||
features = data[:, :-1]
|
features = data[:, :-1]
|
||||||
labels = data[:, -1].astype(int)
|
labels = data[:, -1].astype(int)
|
||||||
return features, labels
|
return features, labels
|
||||||
|
|
||||||
def find_best_k(dataSet, labels):
|
if __name__ == "__main__":
|
||||||
"""
|
train_file = "datingTestSet2.tsv"
|
||||||
使用交叉验证找到最佳 k 值。
|
train_data, train_labels = load_data(train_file)
|
||||||
"""
|
|
||||||
best_score = 0
|
# 预测结果
|
||||||
best_k = 3
|
print(classify0(np.array([65915, 3.868359, 0.128078]), train_data, train_labels, k=3))
|
||||||
for k in range(1, 11):
|
|
||||||
predictions = [classify0(x, dataSet, labels, k) for x in dataSet]
|
|
||||||
score = np.mean(predictions == labels)
|
|
||||||
if score > best_score:
|
|
||||||
best_score = score
|
|
||||||
best_k = k
|
|
||||||
return best_k
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user