From f6a583863c5a1eb723a5b09e8d7cce62e631218e Mon Sep 17 00:00:00 2001 From: yuhaopan <1159526601@qq.com> Date: Tue, 15 Oct 2024 20:29:54 +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 | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/function.py b/function.py index 05fac37..0f205a1 100644 --- a/function.py +++ b/function.py @@ -38,30 +38,35 @@ name = "潘宇豪" """ -def classify0(inX, dataSet, labels, k): +def classify0(inX, dataSet, labels, k=4): """ - KNN classification using Mahalanobis distance for fast computation. - inX: The input sample to classify - dataSet: The training data - labels: The corresponding labels for the training data - k: The number of nearest neighbors to consider + KNN 分类算法,使用马氏距离,并避免显式循环。 + + 参数: + - inX (numpy array): 输入待分类的样本。 + - dataSet (numpy array): 训练数据集。 + - labels (list or numpy array): 训练集对应的标签。 + - k (int): 使用的邻居数量。 + + 返回值: + - int: 预测的分类标签。 """ - # Calculate covariance matrix and its inverse from the dataset - cov_matrix = np.cov(dataSet.T) + # 计算训练数据集的协方差矩阵和它的逆矩阵 + cov_matrix = np.cov(dataSet, rowvar=False) inv_cov_matrix = inv(cov_matrix) - # Compute the Mahalanobis distance between inX and all points in the dataset - diff = dataSet - inX - distances = np.sqrt(np.sum(np.dot(diff, inv_cov_matrix) * diff, axis=1)) + # 计算马氏距离 + diffMat = dataSet - inX + distances = np.sqrt(np.sum(np.dot(diffMat, inv_cov_matrix) * diffMat, axis=1)) - # Sort by distance and return the indices of the k nearest neighbors - sorted_indices = np.argsort(distances) + # 对距离进行排序并找到最近的k个邻居 + sortedDistIndices = np.argsort(distances)[:k] # 直接选择前k个最近的索引 - # Get the labels of the k nearest neighbors - k_nearest_labels = [labels[i] for i in sorted_indices[:k]] + # 获取这k个邻居的标签 + k_nearest_labels = labels[sortedDistIndices] - # Return the most common label among the k nearest neighbors - most_common_label = Counter(k_nearest_labels).most_common(1)[0][0] + # 使用np.bincount计算每个标签的出现次数,并返回出现次数最多的标签 + most_common_label = np.bincount(k_nearest_labels).argmax() return most_common_label