From cc43766dcfb5947dae965fba98633a15021e316b Mon Sep 17 00:00:00 2001 From: heart20003 <1789588961@qq.com> Date: Thu, 17 Oct 2024 00:21:59 +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 | 49 +++++++++++++++++-------------------------------- 1 file changed, 17 insertions(+), 32 deletions(-) diff --git a/function.py b/function.py index 207a95d..3627e82 100644 --- a/function.py +++ b/function.py @@ -43,38 +43,23 @@ name = "陈垣豪" # 这里写自己的代码实现 def classify0(inX, dataSet, labels, k=0): def classify0(inX, dataSet, labels, k=3): - """ - KNN 分类算法。 - - Args: - - inX (numpy array): 输入待分类的样本。 - - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 - - Returns: - - int: 预测的分类标签。 - """ + distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + # 获取距离最小的 k 个样本的索引 + sorted_indices = np.argsort(distances)[:k] - # 计算输入样本与训练集中每个样本的欧氏距离 - distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1)) + # 获取 k 个最近邻的标签 + nearest_labels = [labels[i] for i in sorted_indices] - # 获取距离最小的 k 个样本的索引 - sorted_indices = np.argsort(distances)[:k] - - # 获取 k 个最近邻的标签 - nearest_labels = [labels[i] for i in sorted_indices] - - # 统计 k 个最近邻中每个类别的出现次数 - label_count = {} - for label in nearest_labels: - if label in label_count: - label_count[label] += 1 - else: - label_count[label] = 1 - - # 找到出现次数最多的标签 - predicted_label = max(label_count, key=label_count.get) - - return predicted_label + # 统计 k 个最近邻中每个类别的出现次数 + label_count = {} + for label in nearest_labels: + if label in label_count: + label_count[label] += 1 + else: + label_count[label] = 1 + + # 找到出现次数最多的标签 + predicted_label = max(label_count, key=label_count.get) + + return predicted_label