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

This commit is contained in:
2024-10-23 16:06:36 +08:00
parent 7557b2bf0d
commit 3716ed39e2
+23 -4
View File
@@ -43,25 +43,44 @@ name = "熊浩燃"
# 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=1):
"""
KNN 分类算法。
KNN 分类算法,使用加权多数表决法。
Args:
- input_vector (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
- k (int): kNN 算法参数。
Returns:
- int: 预测的分类标签。
"""
# 计算欧氏距离
distances = np.linalg.norm(dataSet - input_vector, axis=1)
# 获取距离最近的 k 个样本的索引
nearest_neighbors_indices = distances.argsort()[:k]
# 获取这些样本的标签
nearest_labels = np.array(labels)[nearest_neighbors_indices]
# 统计出现次数最多的标签并返回
predicted_label = np.bincount(nearest_labels).argmax()
# 获取这些样本的距离
nearest_distances = distances[nearest_neighbors_indices]
# 防止除以零的情况,添加一个小常数epsilon
epsilon = 1e-5
weights = 1 / (nearest_distances + epsilon) # 距离越小,权重越大
# 对每个标签进行加权投票
label_weights = {}
for i in range(k):
label = nearest_labels[i]
if label not in label_weights:
label_weights[label] = 0
label_weights[label] += weights[i]
# 返回加权得分最高的标签
predicted_label = max(label_weights, key=label_weights.get)
return predicted_label
# 这里也写自己的代码实现