From 08e453bb46914da063bd90a25488cf3a6b768a5d Mon Sep 17 00:00:00 2001 From: heart20003 <1789588961@qq.com> Date: Thu, 17 Oct 2024 00:15:30 +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 | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/function.py b/function.py index 6489d55..797de6a 100644 --- a/function.py +++ b/function.py @@ -42,6 +42,7 @@ name = "test_name" # 这里写自己的代码实现 def classify0(inX, dataSet, labels, k=0): + def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -54,21 +55,28 @@ def classify0(inX, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ - print - - -def load_data(file_path): - """ - 加载 TSV 格式数据文件。 - """ - data = np.loadtxt(file_path, delimiter="\t") - features = data[:, :-1] - labels = data[:, -1].astype(int) - return features, labels - - -if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 + + # 计算输入样本与训练集中每个样本的欧氏距离 + distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + + # 获取距离最小的 k 个样本的索引 + sorted_indices = np.argsort(distances)[:k] + + # 获取 k 个最近邻的标签 + nearest_labels = [labels[i] for i in sorted_indices] + + # 统计 k 个最近邻中每个类别的出现次数 + label_count = {} + for label in nearest_labels: + if label in label_count: + label_count[label] += 1 + else: + label_count[label] = 1 + + # 找到出现次数最多的标签 + predicted_label = max(label_count, key=label_count.get) + + return predicted_label train_file = "datingTrainSet2.tsv"