更新 function.py
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 10s

This commit is contained in:
2024-10-12 20:07:02 +08:00
parent ff4f93d4b7
commit 02a3886dd0
+12 -6
View File
@@ -1,6 +1,6 @@
# function.py # function.py
import numpy as np import numpy as np
from collections import Counter
""" """
挑战说明: 挑战说明:
@@ -43,11 +43,17 @@ name = "邓杰元"
# 这里写自己的代码实现 # 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=20): def classify0(inX, dataSet, labels, k=20):
distances = [np.sqrt(np.sum((x - inX) ** 2)) for x in dataSet] # 计算输入向量与训练集中每个样本的欧氏距离
k_indices = np.argsort(distances)[:k] distances = np.sqrt(np.sum((dataSet - input_vector) ** 2, axis=1))
most_common = Counter(k_nearest_labels).most_common(1) # 获取距离最小的k个样本的索引
return most_common[0][0] k_indices = np.argsort(distances)[:k]
# 获取这k个样本的标签
k_nearest_labels = labels[k_indices]
# 找出出现次数最多的标签
most_common = Counter(k_nearest_labels).most_common(1)