From 2e394360eea54a68201c7a377af66aa2c1fe18dd Mon Sep 17 00:00:00 2001 From: wzy <675163717@qq.com> Date: Tue, 22 Oct 2024 19:53:02 +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 | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/function.py b/function.py index 8cdca64..82b0c00 100644 --- a/function.py +++ b/function.py @@ -59,15 +59,21 @@ def classify(input_vector, dataSet, labels, k=2): Returns: - int: 预测的分类标签。 """ + if dataSet.ndim > 2: + dataSet = dataSet.reshape(dataSet.shape[0], -1) + mean = np.mean(dataSet, axis=0) covmat = np.cov(dataSet, rowvar=0) inv_covmat = np.linalg.inv(covmat) + # 马氏距离计算 dists = [mahalanobis_distance(input_vector, mean, inv_covmat)] - for data in dataSet: dists.append(mahalanobis_distance(data, mean, inv_covmat)) + # 移除第一个距离,因为它是输入向量的马氏距离 + dists.pop(0) + k_indices = np.argsort(dists)[:k] k_nearest_labels = [labels[i] for i in k_indices] @@ -79,7 +85,7 @@ def classify(input_vector, dataSet, labels, k=2): if most_common: return most_common[0][0] else: - return None + return None # 这里也写自己的代码实现