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

This commit is contained in:
2024-10-17 00:21:59 +08:00
parent 25cfcbed0b
commit cc43766dcf
+17 -32
View File
@@ -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