更新 function.py
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 30s

This commit is contained in:
2024-10-14 21:38:24 +08:00
parent 307307ec0f
commit 91c0d80be0
+12 -15
View File
@@ -1,7 +1,8 @@
# function.py
import numpy as np
import pandas as pd
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)
return label_counts.argmax()
def load_data(file_path):
"""
加载 TSV 格式数据文件。
"""
data = np.loadtxt(file_path, delimiter="\t")
data = pd.read_csv(file_path, sep='\t', header=None).values
features = data[:, :-1]
labels = data[:, -1].astype(int)
return features, labels
def find_best_k(dataSet, labels):
"""
使用交叉验证找到最佳 k 值。
"""
best_score = 0
best_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__":
train_file = "datingTestSet2.tsv"
train_data, train_labels = load_data(train_file)
# 预测结果
print(classify0(np.array([65915, 3.868359, 0.128078]), train_data, train_labels, k=3))
if __name__ == "__main__":