From 12a669957532c2a12699ed419d3054f26484b873 Mon Sep 17 00:00:00 2001 From: cy <939601402@qq.com> Date: Tue, 15 Oct 2024 19:02:26 +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 | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/function.py b/function.py index 6829644..9e9362d 100644 --- a/function.py +++ b/function.py @@ -42,10 +42,15 @@ def classify(input_vector, dataSet, labels, k=2): - int: 预测的分类标签。 """ dataSet_size = dataSet.shape[0] - # 计算曼哈顿距离 + # 计算马氏距离 + cov_matrix = np.cov(dataSet.T) + inv_cov_matrix = np.linalg.inv(cov_matrix) diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet - abs_diff_mat = np.abs(diff_mat) - distances = abs_diff_mat.sum(axis=1) + distances = [] + for i in range(dataSet_size): + distance = np.sqrt(np.dot(np.dot(diff_mat[i], inv_cov_matrix), diff_mat[i].T)) + distances.append(distance) + distances = np.array(distances) # 对距离进行排序 sorted_indices = distances.argsort() class_count = {}