From 7c35d69479e89ee36e020cd0dc34b51d1197fa6b Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Tue, 8 Oct 2024 17:15:57 +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 | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/function.py b/function.py index 878989d..d3c46d9 100644 --- a/function.py +++ b/function.py @@ -40,7 +40,10 @@ name = "章程鸿" # 这里写自己的代码实现 -def classify0(inX, dataSet, labels, k=0): +import numpy as np +from collections import Counter + +def classify0(inX, dataSet, labels, k=3): """ KNN 分类算法。 @@ -48,28 +51,39 @@ 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 = inX - dataSet + sqDiffMat = diffMat ** 2 + sqDistances = sqDiffMat.sum(axis=1) + distances = sqDistances ** 0.5 + + # 排序并选取前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 x: x[1], reverse=True) + return sortedClassCount[0][0] -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__": # 以下代码可用于测试,可自行随意修改 - train_file = "datingTrainSet2.tsv" - + train_data, train_labels = load_data(train_file) - print(classify0([65915, 3.868359, 0.128078], train_data, train_labels)) + # 测试数据点 + test_point = np.array([65915, 3.868359, 0.128078]) + predicted_label = classify0(test_point, train_data, train_labels) + print("预测的分类标签是:", predicted_label) +