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

This commit is contained in:
2024-11-21 09:02:04 +08:00
parent 6404a058ff
commit ab61b3c37a
+23 -3
View File
@@ -25,8 +25,8 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423219"
name = "李燕如"
"""
@@ -41,7 +41,7 @@ name = "test_name"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=0):
def classify0(inX, dataSet, labels, k=3):
"""
KNN 分类算法。
@@ -54,6 +54,26 @@ def classify0(inX, dataSet, labels, k=0):
Returns:
- int: 预测的分类标签。
"""
# 计算待分类样本与训练集中每个样本的距离
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
# 获取距离最近的 k 个样本的索引
k_indices = np.argsort(distances)[:k]
# 获取这些样本对应的标签
k_nearest_labels = labels[k_indices]
# 统计每个类别出现的次数
count = {}
for label in k_nearest_labels:
if label in count.keys():
count[label] += 1
else:
count[label] = 1
# 找到出现次数最多的类别
sorted_count = sorted(count.items(), key=lambda x: x[1], reverse=True)
return sorted_count[0][0]
def load_data(file_path):