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")