From 2d89a0a7e3d40f7c5d4fe24b01b0711ea9754a07 Mon Sep 17 00:00:00 2001 From: 77 <3298722099@qq.com> Date: Thu, 21 Nov 2024 09:00:12 +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 | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/function.py b/function.py index 2393b3b..ad3460e 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423201" +name = "陈瑞琪祥" """ @@ -41,7 +41,9 @@ name = "test_name" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=0): + + +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -49,12 +51,29 @@ def classify0(inX, dataSet, labels, k=0): - inX (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 + - k (int): kNN 算法参数,默认值为 3。 Returns: - int: 预测的分类标签。 """ - + # 计算待分类样本与训练集中每个样本的欧氏距离 + diffMat = np.tile(inX, (dataSet.shape[0], 1)) - dataSet + sqDiffMat = diffMat**2 + sqDistances = sqDiffMat.sum(axis=1) + distances = sqDistances**0.5 + + # 对距离进行排序,获取距离最近的 k 个样本的索引 + sortedDistIndices = distances.argsort() + + # 提取距离最近的 k 个样本的标签 + classCount = {} + for i in range(k): + voteIlabel = labels[sortedDistIndices[i]] + classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 + + # 根据出现次数最多的标签来预测待分类样本的标签 + sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) + return sortedClassCount[0][0] def load_data(file_path): """ @@ -65,12 +84,8 @@ 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))