From e3fd53e88535f5da7afe15019d82204859956fa4 Mon Sep 17 00:00:00 2001 From: hao <19382120447@163.com> Date: Mon, 14 Oct 2024 21:09:00 +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 | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/function.py b/function.py index 2393b3b..6f1692f 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423228" +name = "黎世浩" """ @@ -41,7 +41,7 @@ name = "test_name" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=0): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -56,6 +56,23 @@ def classify0(inX, dataSet, labels, k=0): """ +# 计算待分类样本与数据集中每个样本的距离 + distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + + # 获取距离最近的k个样本的索引 + sortedDistIndices = np.argsort(distances) + classCount = {} + + # 遍历距离最近的k个样本 + for i in range(k): + voteIlabel = labels[sortedDistIndices[i]] + # 统计每个类别的出现次数 + classCount[voteIlabel] = classCount.getvoteIlabel, classCount.getvoteIlabel + 1) + + # 选择出现次数最多的类别作为预测标签 + sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) + return sortedClassCount[0][0] + def load_data(file_path): """ 加载 TSV 格式数据文件。 @@ -65,12 +82,7 @@ def load_data(file_path): labels = data[:, -1].astype(int) return features, labels - if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 - train_file = "datingTrainSet2.tsv" - train_data, train_labels = load_data(train_file) - print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))