From 91c0d80be06f398370d09c66b367a272162730de Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Mon, 14 Oct 2024 21:38:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/function.py b/function.py index a412777..0935b82 100644 --- a/function.py +++ b/function.py @@ -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__":