From eb4fef4ac5793b5433128ff7b5c2af7e77c0e219 Mon Sep 17 00:00:00 2001 From: wzy <675163717@qq.com> Date: Mon, 14 Oct 2024 21:00:53 +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 | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index 6141d77..eca04c2 100644 --- a/function.py +++ b/function.py @@ -1,7 +1,6 @@ # function.py import numpy as np import os -from scipy.spatial.distance import euclidean from collections import Counter """ @@ -43,6 +42,9 @@ name = "万子玉" # 这里写自己的代码实现 +def euclidean_distance(a, b): + return np.sqrt(np.sum((a - b) ** 2)) + def classify(input_vector, dataSet, labels, k=3): """ KNN 分类算法。 @@ -56,21 +58,18 @@ def classify(input_vector, dataSet, labels, k=3): Returns: - int: 预测的分类标签。 """ - dists = [euclidean(input_vector, data) for data in dataSet] + dists = [euclidean_distance(input_vector, data) for data in dataSet] k_indices = np.argsort(dists)[:k] k_nearest_labels = [labels[i] for i in k_indices] - # 确保至少有一个近邻 if not k_nearest_labels: raise ValueError("No neighbors found; possible causes: k is too small or all distances are the same.") most_common = Counter(k_nearest_labels).most_common(1) - # 检查most_common是否为空 if most_common: return most_common[0][0] else: - # 如果为空,返回一个默认值或者抛出异常 return None # 或者 raise ValueError("No common labels found")