From 53361ec9776bf0f03e32f76ce989d0c3481b667c Mon Sep 17 00:00:00 2001 From: kxz <2897100651@qq.com> Date: Tue, 8 Oct 2024 20:49:45 +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 | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/function.py b/function.py index 2496580..9b34ad5 100644 --- a/function.py +++ b/function.py @@ -71,12 +71,12 @@ def classify0(inX, dataSet, labels, k=3): Returns: - int: 预测的分类标签。 """ - dists = np.sum(np.abs(dataSet - inX), axis=1) + dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1)) sorted_index = np.argsort(dists) class_count = {} for i in range(k): vote_label = labels[sorted_index[i]] - class_count[vote_label] = class_count.get(vote_label, 0) + 1 + class_count[vote_label] = class_count.get(vote_label, 0) + 1 / (dists[sorted_index[i]] + 1e-5) # 加权,防止除零 sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True) if sorted_class_count: return sorted_class_count[0][0] @@ -84,10 +84,19 @@ def classify0(inX, dataSet, labels, k=3): return -1 +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) @@ -109,4 +118,4 @@ if __name__ == "__main__": best_accuracy = accuracy best_k = k - print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}") + print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}") \ No newline at end of file