From e81f14655295b003ef9e981d325d5871debc1cac Mon Sep 17 00:00:00 2001 From: yuhaopan <1159526601@qq.com> Date: Thu, 26 Sep 2024 16:40:21 +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 | 44 +++++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/function.py b/function.py index 89b7dc3..51c0bbd 100644 --- a/function.py +++ b/function.py @@ -23,8 +23,8 @@ import numpy as np """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423226" +name = "潘宇豪" """ @@ -38,23 +38,46 @@ name = "test_name" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels): +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 - Args: + 参数: - inX (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 + - k (int): 使用的邻居数量。 - Returns: + 返回值: - int: 预测的分类标签。 """ + # 计算输入样本与训练数据集中每个样本的欧氏距离 + diffMat = np.tile(inX, (dataSet.shape[0], 1)) - dataSet + sqDiffMat = diffMat**2 + sqDistances = sqDiffMat.sum(axis=1) + distances = np.sqrt(sqDistances) + # 对距离进行排序并找到最近的k个邻居 + sortedDistIndices = distances.argsort() + classCount = {} + + for i in range(k): + voteIlabel = labels[sortedDistIndices[i]] + classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 + + # 返回出现次数最多的类别 + sortedClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True) + return sortedClassCount[0][0] def load_data(file_path): """ - 加载 TSV 格式数据文件。 + 加载TSV格式的数据文件。 + + 参数: + - file_path (str): 数据文件的路径。 + + 返回值: + - tuple: 包含特征数组和标签数组的元组。 """ features = [] labels = [] @@ -68,11 +91,10 @@ def load_data(file_path): return np.array(features), np.array(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)) + # 使用一个测试样本进行测试 + test_result = classify0([65915, 3.868359, 0.128078], train_data, train_labels, k=3) + print("预测结果:", test_result) \ No newline at end of file