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

This commit is contained in:
2024-10-17 16:52:41 +08:00
parent 8f09311852
commit 774c006062
+19 -10
View File
@@ -1,6 +1,6 @@
# function.py
import numpy as np
from collections import Counter
"""
挑战说明:
- 自行编写实现 KNN 分类算法。
@@ -54,19 +54,28 @@ def classify0(inX, dataSet, labels, k=3):
Returns:
- int: 预测的分类标签。
"""
# 计算输入向量与训练集中每一个样本的欧式距离
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
# 计算欧式距离
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = np.sqrt(sqDistances)
# 通过对距离进行升序排序并选择前k个最近距离的索引
nearest_neighbors_indices = distances.argsort()[:k]
# 按距离从小到大排序
sortedDistIndices = distances.argsort()
# 收集k个最近距离的样本的标签
nearest_labels = [labels[i] for i in nearest_neighbors_indices]
# 选择距离最小的k个点
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
# 使用计数器查找出现频率最高的标签
most_common_label = Counter(nearest_labels).most_common(1)[C_0]()[C_0]()
# 按类别票数从大到小排序
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
# 返回出现频率最高的类别
return sortedClassCount[0][0]
return most_common_label
def load_data(file_path):
"""