From 35ec76563b6d3755e8a03c8656c6a8de307a0663 Mon Sep 17 00:00:00 2001 From: meixiaodong <3081674342@qq.com> Date: Tue, 22 Oct 2024 11:18:51 +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 | 75 +++++++++++++++++++---------------------------------- 1 file changed, 27 insertions(+), 48 deletions(-) diff --git a/function.py b/function.py index 183c427..4e59d37 100644 --- a/function.py +++ b/function.py @@ -54,60 +54,39 @@ def classify0(inX, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ - # function.py -import numpy as np -import pandas as pd -from collections import Counter - -# 确保填写自己的学号和姓名 -# 学号: YOUR_STUDENT_ID -# 姓名: YOUR_NAME - -def classify(inx, dataset, labels, k=3): + def classify0(inX, dataSet, labels, k=3): """ - 使用kNN算法对输入样本进行分类。 + KNN 分类算法。 - :param inx: 要分类的输入样本(1D数组) - :param dataset: 训练数据集(2D数组) - :param labels: 训练集对应的标签(1D数组) - :param k: 最近邻居的数量 - :return: 输入样本的预测标签 + Args: + - inX (numpy array): 输入待分类的样本。 + - dataSet (numpy array): 训练数据集。 + - labels (list or numpy array): 训练集对应的标签。 + - k (int): KNN 算法参数,请自行设置默认值,评测时仅会使用其默认值。 + + Returns: + - int: 预测的分类标签。 """ + dataSetSize = dataSet.shape[0] - # 将输入转换为numpy数组以便于操作 - dataset = np.array(dataset) - labels = np.array(labels) - inx = np.array(inx) + # 计算协方差矩阵及其逆矩阵 + cov_matrix = np.cov(dataSet, rowvar=False) + inv_cov_matrix = np.linalg.inv(cov_matrix) + + # 计算马氏距离 + diffMat = inX - dataSet + left_term = np.dot(diffMat, inv_cov_matrix) + mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1)) - # 计算输入样本与所有样本的距离 - distances = np.linalg.norm(dataset - inx, axis=1) + # 排序距离并选择前 k 个最近邻 + sortedDistIndicies = mahalanobis_distances.argsort() + classCount = {} + for i in range(k): + vote_label = labels[sortedDistIndicies[i]] + classCount[vote_label] = classCount.get(vote_label, 0) + 1 - # 获取最近k个邻居的索引 - k_indices = np.argsort(distances)[:k] - - # 获取这k个邻居的标签 - k_nearest_labels = labels[k_indices] - - # 使用多数投票确定预测标签 - most_common = Counter(k_nearest_labels).most_common(1) - return most_common[0][0] - -# 测试代码示例(可选择性运行) -if __name__ == "__main__": - # 加载训练数据集 - train_data = pd.read_csv('datingTrainset2.tsv', sep='\t') - train_labels = train_data['label'].values # 替换'label'为你的实际标签列名 - train_features = train_data.drop('label', axis=1).values # 删除标签列 - - # 加载测试数据集 - test_data = pd.read_csv('datingTestset2.tsv', sep='\t') - test_labels = test_data['label'].values # 替换'label'为你的实际标签列名 - test_features = test_data.drop('label', axis=1).values # 删除标签列 - - # 示例:对一个样本进行分类 - sample = test_features[0] # 使用测试集中第一个样本 - predicted_label = classify(sample, train_features, train_labels, k=3) - print(f"Predicted label: {predicted_label}") + sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) + return sortedClassCount[0][0]