From 27c96cca75db2f69888f82a55e1c8dcfb94dfbbf Mon Sep 17 00:00:00 2001 From: dong <2938690875@qq.com> Date: Thu, 17 Oct 2024 16:52:34 +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 | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/function.py b/function.py index d3baf72..5a1d75d 100644 --- a/function.py +++ b/function.py @@ -41,31 +41,27 @@ name = "董秋" # 这里写自己的代码实现 - def classify(input_vector, dataSet, labels, k=3): """ - KNN 分类算法(使用马氏距离)。 + KNN 分类算法。 Args: - input_vector (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,默认值为 3。 + - k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 Returns: - int: 预测的分类标签。 """ - # 计算协方差矩阵及其逆矩阵 - cov_matrix = np.cov(dataSet, rowvar=False) - inv_cov_matrix = np.linalg.inv(cov_matrix) + """ + 使用欧式距离的 kNN 分类算法。 + """ + # 计算欧式距离 + distances = np.linalg.norm(dataSet - input_vector, axis=1) - # 计算马氏距离 - diffMat = dataSet - input_vector - left_term = np.dot(diffMat, inv_cov_matrix) - mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1)) - # 获取距离最近的 k 个样本的索引 - k_indices = np.argsort(mahalanobis_distances)[:k] + k_indices = np.argsort(distances)[:k] # 获取最近邻样本的标签 k_nearest_labels = [labels[i] for i in k_indices]