From cfc4e1ef15063a8cd7af9468bf9ee6007bc4600e Mon Sep 17 00:00:00 2001 From: zhe <2904040094@qq.com> Date: Wed, 23 Oct 2024 21:07: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 | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/function.py b/function.py index c0e9816..4d1d1cd 100644 --- a/function.py +++ b/function.py @@ -41,16 +41,20 @@ name = "李劲" """ -def classify(input_vector, dataSet, labels, k=3): - cov_matrix = np.cov(dataSet, rowvar=False) - inv_cov_matrix = np.linalg.inv(cov_matrix) +# 计算欧氏距离 diffMat = dataSet - input_vector - left_term = np.dot(diffMat, inv_cov_matrix) - mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1)) - k_indices = np.argsort(mahalanobis_distances)[:k] + euclidean_distances = np.sqrt(np.sum(diffMat ** 2, axis=1)) + + # 获取距离最近的 k 个样本的索引 + k_indices = np.argsort(euclidean_distances)[:k] + + # 获取最近邻样本的标签 k_nearest_labels = [labels[i] for i in k_indices] + + # 找出出现次数最多的标签 most_common = max(set(k_nearest_labels), key=k_nearest_labels.count) - return most_common + + return most_common def load_dataset(directory): features = []