From 52d3419832d35905692205b13a3fe41b7dd93b58 Mon Sep 17 00:00:00 2001 From: kxz <2897100651@qq.com> Date: Tue, 8 Oct 2024 20:34:57 +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 | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/function.py b/function.py index 907ba41..8d0f08f 100644 --- a/function.py +++ b/function.py @@ -83,10 +83,25 @@ def classify0(inX, dataSet, labels, k=3): else: return -1 +def load_data(file_path): + data = np.loadtxt(file_path, delimiter="\t") + features = data[:, :-1] + labels = data[:, -1].astype(int) + return features, labels + +def normalize(features): + min_vals = features.min(axis=0) + max_vals = features.max(axis=0) + ranges = max_vals - min_vals + normalized = (features - min_vals) / ranges + normalized[ranges == 0] = 0 # 防止除以零的情况 + return normalized + if __name__ == "__main__": - # 假设 load_data 和 normalize 函数已经定义 train_features, train_labels = load_data("datingTrainSet2.tsv") test_features, test_labels = load_data("datingTestSet2.tsv") + + # 在这里进行归一化处理 train_features = normalize(train_features) test_features = normalize(test_features) @@ -110,5 +125,13 @@ if __name__ == "__main__": print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}") + accuracy = correct_count / len(test_features) + print(f"Accuracy with k={k}: {accuracy:.2f}") + if accuracy > best_accuracy: + best_accuracy = accuracy + best_k = k + + print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}") +