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

This commit is contained in:
2024-09-26 10:31:39 +08:00
parent 69e94abac7
commit 04fccf8179
+17 -8
View File
@@ -50,15 +50,24 @@ def classify0(inX, dataSet, labels,k=3):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
distances = [np.sqrt(np.sum((inX - x) ** 2)) for x in dataSet] dataSetSize = dataSet.shape[0]
diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMat = diffMat ** 2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances ** 0.5
k_indices = np.argsort(distances)[:k] # 对距离进行排序,并获取索引
k_nearest_labels = [labels[i] for i in k_indices] sortedDistIndicies = distances.argsort()
from collections import Counter # 选择距离最小的k个点
vote_result = Counter(k_nearest_labels).most_common(1) classCount = {}
for i in range(k):
return vote_result[0][0] voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
# 多数投票
sortedClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True)
return sortedClassCount[0][0]
def load_data(file_path): def load_data(file_path):
""" """