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

This commit is contained in:
2024-10-15 22:50:55 +08:00
parent 92ab274db8
commit 5c7f54efe8
+14 -8
View File
@@ -37,15 +37,15 @@ name = "潘宇豪"
"""
def classify0(inx, dataSet, labels, k=2, _cache={"VI": None}):
def classify_with_voting_no_loop(inx, dataSet, labels, k_values=[3,4,8,9], _cache={"VI": None}):
"""
KNN 分类算法,使用缓存优化性能。
KNN分类算法,使用多种k值并通过投票机制预测最终结果。此版本不使用显式for循环。
参数:
- inx (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): 使用的邻居数量。
- k_values (list): 使用的邻居数量的不同k值。
- _cache (dict): 缓存数据,用于存储协方差矩阵的逆。
返回值:
@@ -61,14 +61,20 @@ def classify0(inx, dataSet, labels, k=2, _cache={"VI": None}):
# 使用矩阵运算计算马氏距离
distances = np.sum(diff @ _cache["VI"] * diff, axis=1)
# 对距离排序,获取前k个最近的样本索引
# 对距离排序,获取所有样本索引
sortedDistIndices = np.argsort(distances)
# 统计前k个样本的标签
classCount = np.bincount(labels[sortedDistIndices[:k]])
# 创建一个矩阵来保存每个k值的前k个样本的标签
max_k = max(k_values) # 找到最大的k
nearest_labels = labels[sortedDistIndices[:max_k]] # 取最大的k个邻居的标签
# 返回出现次数最多的标签
return np.argmax(classCount)
# 为每个k值计算预测结果,统计不同k值下出现最多的标签
predictions = np.array([np.bincount(nearest_labels[:k]).argmax() for k in k_values])
# 对所有预测结果进行投票,选择出现次数最多的标签作为最终结果
final_prediction = np.bincount(predictions).argmax()
return final_prediction
def load_data(file_path):