From ee58302173983c612cf695f26ceeba482ed70b22 Mon Sep 17 00:00:00 2001 From: Xionghaoran <719929980@qq.com> Date: Thu, 7 Nov 2024 16:29:42 +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 | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/function.py b/function.py index dba13aa..2cf3dac 100644 --- a/function.py +++ b/function.py @@ -39,7 +39,7 @@ name = "熊浩燃" - int: 预测的分类标签。 """ -def mahalanobis_distance(x1, x2, cov_inv, mean): +def mahalanobis_distance(x1, x2, cov_inv): """ 计算两点之间的马氏距离。 @@ -47,13 +47,12 @@ def mahalanobis_distance(x1, x2, cov_inv, mean): x1 (numpy array): 第一个点。 x2 (numpy array): 第二个点。 cov_inv (numpy array): 协方差矩阵的逆矩阵。 - mean (numpy array): 数据集的均值。 Returns: float: 两点之间的马氏距离。 """ delta = x1 - x2 - dist = delta @ cov_inv @ delta.T + dist = np.dot(np.dot(delta, cov_inv), delta.T) return dist def classify0(inX, dataSet, labels, k=3): @@ -69,26 +68,22 @@ def classify0(inX, dataSet, labels, k=3): Returns: - int: 预测的分类标签。 """ - # 计算训练数据集的协方差矩阵和均值 + # 计算训练数据集的协方差矩阵和均值,避免重复计算 cov_matrix = np.cov(dataSet, rowvar=False) - mean = np.mean(dataSet, axis=0) cov_inv = np.linalg.inv(cov_matrix + np.eye(cov_matrix.shape[0]) * 1e-5) # 加上一个小的单位矩阵以避免奇异矩阵 - # 计算待分类样本与训练集中每个样本的马氏距离 - distances = np.array([mahalanobis_distance(inX, x, cov_inv, mean) for x in dataSet]) + # 计算所有训练样本与待分类样本的马氏距离 + distances = np.array([mahalanobis_distance(inX, x, cov_inv) for x in dataSet]) + + # 获取与待分类样本距离最近的 k 个样本的索引 + nearest_indices = distances.argsort()[:k] - # 获取距离最近的 k 个样本的索引 - sortedDistIndices = np.argpartition(distances, k)[:k] + # 获取 k 个最近样本的标签 + nearest_labels = [labels[i] for i in nearest_indices] - # 获取这些样本对应的标签 - classCount = {} - for i in sortedDistIndices: - voteLabel = labels[i] - classCount[voteLabel] = classCount.get(voteLabel, 0) + 1 - - # 选择出现次数最多的标签作为预测标签 - sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True) - return sortedClassCount[0][0] + # 返回出现频率最高的标签作为预测结果 + unique_labels, counts = np.unique(nearest_labels, return_counts=True) + return unique_labels[np.argmax(counts)] def load_data(file_path):