From fd60bbdb34078d35924a42448b5983c18dd8d88d Mon Sep 17 00:00:00 2001 From: kxz <2897100651@qq.com> Date: Tue, 8 Oct 2024 20:09:31 +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 | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/function.py b/function.py index d64a5e5..c9f3001 100644 --- a/function.py +++ b/function.py @@ -54,16 +54,12 @@ def classify0(inX, dataSet, labels, k=3): Returns: - int: 预测的分类标签。 """ - # 计算待分类样本与训练集中每个样本之间的距离 dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1)) - # 根据距离对训练样本进行排序 sorted_index = np.argsort(dists) - # 选择距离最近的k个样本 class_count = {} for i in range(k): vote_label = labels[sorted_index[i]] class_count[vote_label] = class_count.get(vote_label, 0) + 1 - # 投票得到最多的标签作为预测结果 sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True) if sorted_class_count: return sorted_class_count[0][0] @@ -103,19 +99,23 @@ if __name__ == "__main__": train_features = standardize(train_features) test_features = standardize(test_features) - correct_count = 0 - for i in range(len(test_features)): - test_feature = test_features[i].reshape(1, -1) - predict_label = classify0(test_feature, train_features, train_labels, k=3) - if predict_label == -1: - continue - correct_count += (predict_label == test_labels[i]) + # 尝试不同的 K 值 + best_k = 3 + best_accuracy = 0.0 - accuracy = correct_count / len(test_features) - print(f"Accuracy: {accuracy:.2f}") - - - + for k in [1, 3, 5, 7, 9]: + correct_count = 0 + for i in range(len(test_features)): + test_feature = test_features[i].reshape(1, -1) + predict_label = classify0(test_feature, train_features, train_labels, k=k) + if predict_label == -1: + continue + correct_count += (predict_label == test_labels[i]) + + accuracy = correct_count / len(test_features) + print(f"Accuracy with k={k}: {accuracy:.2f}") + if accuracy > best_accuracy: + best_accuracy = accuracy + best_k = k - accuracy = correct_count / len(test_features) - print(f"Accuracy: {accuracy:.2f}") \ No newline at end of file + print(f"Best K: {best_k}, Best Accuracy: {best_accuracy:.2f}")