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

This commit is contained in:
2024-10-12 19:07:20 +08:00
parent a8110d351a
commit 9ccc894dba
+14 -25
View File
@@ -20,21 +20,6 @@ import numpy as np
- Python: 3.10.12 - Python: 3.10.12
- numpy: 2.1.1 - numpy: 2.1.1
""" """
# 计算待分类样本与训练集中所有样本的欧氏距离
distances = [np.sqrt(np.sum((x - inX) ** 2)) for x in dataSet]
# 根据距离排序,并获取前k个索引
k_indices = np.argsort(distances)[:k]
# 获取前k个邻居的标签
k_nearest_labels = [labels[i] for i in k_indices]
# 对标签进行投票,选择出现次数最多的标签
from collections import Counter
most_common = Counter(k_nearest_labels).most_common(1)
# 返回投票最多的标签
return most_common[0][0]
""" """
@@ -57,18 +42,22 @@ name = "邓杰元"
# 这里写自己的代码实现 # 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=10): def classify0(inX, dataSet, labels, k=10):
""" # 计算待分类样本与训练集中所有样本的欧氏距离
KNN 分类算法。 distances = [np.sqrt(np.sum((x - inX) ** 2)) for x in dataSet]
Args: # 根据距离排序,并获取前k个索引
- inX (numpy array): 输入待分类的样本。 k_indices = np.argsort(distances)[:k]
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。 # 获取前k个邻居的标签
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 k_nearest_labels = [labels[i] for i in k_indices]
# 对标签进行投票,选择出现次数最多的标签
from collections import Counter
most_common = Counter(k_nearest_labels).most_common(1)
# 返回投票最多的标签
return most_common[0][0]
Returns:
- int: 预测的分类标签。
"""
def load_data(file_path): def load_data(file_path):