From 5f7d2a00804f2d947d618b0c98ee33fde956aaf7 Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Mon, 14 Oct 2024 21:27:12 +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 | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/function.py b/function.py index 6b2ab1d..a412777 100644 --- a/function.py +++ b/function.py @@ -1,6 +1,7 @@ # function.py import numpy as np from sklearn.preprocessing import StandardScaler +from sklearn.model_selection import cross_val_score """ 挑战说明: @@ -85,11 +86,29 @@ def load_data(file_path): 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 = "datingTrainSet2.tsv" train_data, train_labels = load_data(train_file) - + + # 找到最佳 k 值 + best_k = find_best_k(train_data, train_labels) + print(f"Best k: {best_k}") + # 预测结果 - print(classify0(np.array([65915, 3.868359, 0.128078]), train_data, train_labels, k=3)) \ No newline at end of file + print(classify0(np.array([65915, 3.868359, 0.128078]), train_data, train_labels, best_k)) \ No newline at end of file