From 0c7bbd67e9137503a23e889f5d57f270b4268b0f Mon Sep 17 00:00:00 2001 From: Dengddd <3149942468@qq.com> Date: Tue, 8 Oct 2024 20:09:16 +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, 20 insertions(+), 7 deletions(-) diff --git a/function.py b/function.py index 6bfe56d..fc6a292 100644 --- a/function.py +++ b/function.py @@ -53,12 +53,15 @@ def classify0(inX, dataSet, labels, k=3): Args: - inX (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 + - labels (numpy array): 训练集对应的标签。 - k (int): KNN 算法参数,默认值为3。 Returns: - int: 预测的分类标签。 """ + # 确保 labels 是 numpy 数组 + labels = np.array(labels) + # 计算待分类样本与训练集中每个样本之间的距离 distances = [euclidean_distance(inX, x) for x in dataSet] @@ -67,13 +70,13 @@ def classify0(inX, dataSet, labels, k=3): k_nearest_indices = sorted_indices[:k] # 获取k个最近样本的标签 - k_nearest_labels = [labels[i] for i in k_nearest_indices] + k_nearest_labels = labels[k_nearest_indices] - # 统计每个标签出现的次数,并返回出现次数最多的标签 - label_counts = np.bincount(k_nearest_labels) - predicted_label = np.argmax(label_counts) + # 使用 np.unique 和 np.bincount 的一个更健壮的方法来找到出现次数最多的标签 + unique_labels, counts = np.unique(k_nearest_labels, return_counts=True) + most_common_label = unique_labels[np.argmax(counts)] - return predicted_label + return int(most_common_label) # 确保返回的是整数 def load_data(file_path): """ @@ -87,10 +90,20 @@ def load_data(file_path): if __name__ == "__main__": # 测试代码 train_file = "datingTrainSet2.tsv" - test_file = "datingTestSet2.tsv" # 假设有一个测试文件用于验证,虽然题目没明确要求 + test_file = "datingTestSet2.tsv" # 假设有一个测试文件用于验证 # 加载训练数据和测试数据 train_data, train_labels = load_data(train_file) + test_data, test_labels = load_data(test_file) # 取消注释以测试整个测试集 + + # 测试 classify0 函数 + sample = [65915, 3.868359, 0.128078] # 示例样本 + predicted_label = classify0(sample, train_data, train_labels) + print(f"Predicted label for sample {sample}: {predicted_label}") + + # 测试整个测试集(可选) + accuracy = np.mean([classify0(test_data[i], train_data, train_labels) == test_labels[i] for i in range(len(test_data))]) + print(f"Accuracy on test set: {accuracy}") # test_data, test_labels = load_data(test_file) # 如果需要测试,可以取消注释并添加相应的测试代码 # 测试 classify0 函数