更新 1fu1nction.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 14s

This commit is contained in:
2024-10-22 21:43:09 +08:00
parent 2c70be6d1c
commit 916a58a551
+6 -14
View File
@@ -45,26 +45,18 @@ import numpy as np
import os
from collections import Counter
def classify(input_vector, dataSet, labels, k=1):
"""使用 KNN 算法对输入样本进行分类,使用加权多数表决法。"""
def classify(input_vector, dataSet, labels, k=1): # 设置默认值 k=1
"""使用 KNN 算法对输入样本进行分类。"""
# 计算输入向量与训练集之间的欧氏距离
distances = np.linalg.norm(dataSet - input_vector, axis=1)
# 根据距离排序并获取索引
sorted_indices = distances.argsort()
# 选择距离最近的k个点
k_nearest_labels = labels[sorted_indices[:k]]
k_nearest_distances = distances[sorted_indices[:k]]
# 计算权重:距离越小,权重越大
weights = 1 / (k_nearest_distances + 1e-10) # 加小常数防止除零
# 使用加权计数
count = Counter()
for label, weight in zip(k_nearest_labels, weights):
count[label] += weight
# 返回加权计数最多的类别标签
return count.most_common(1)[0][0]
# 统计k个点中各类别的数量
count = Counter(k_nearest_labels)
# 返回数量最多的类别标签
return count.most_common(1)[0][0]
# 为评测系统创建别名
classify = classify