From c5a7ee51c4030846504c0861d65816040e32dae3 Mon Sep 17 00:00:00 2001 From: cy <939601402@qq.com> Date: Wed, 23 Oct 2024 18:02:32 +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 | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/function.py b/function.py index 7ebb0c9..61879b6 100644 --- a/function.py +++ b/function.py @@ -29,25 +29,17 @@ name = "程悦" -def classify(input_vector, dataSet, labels, k=9): - """ - KNN 分类算法,添加了数据归一化处理。 - - Args: - - input_vector (numpy array): 输入待分类的样本。 - - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数。 - - Returns: - - int: 预测的分类标签。 - """ +def classify(input_vector, dataSet, labels, k=2): dataSet_size = dataSet.shape[0] - # 计算欧氏距离 + # 计算马氏距离 + cov_matrix = np.cov(dataSet.T) + inv_cov_matrix = np.linalg.pinv(cov_matrix) diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet - sq_diff_mat = diff_mat ** 2 - sq_distances = sq_diff_mat.sum(axis=1) - distances = np.sqrt(sq_distances) + 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 = {}