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

This commit is contained in:
2024-10-17 16:58:13 +08:00
parent 774c006062
commit 8aa0001914
+5 -8
View File
@@ -57,24 +57,21 @@ def classify0(inX, dataSet, labels, k=3):
# 计算欧式距离
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inX, (dataSetSize, 1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = np.sqrt(sqDistances)
distances = np.sqrt(np.sum(diffMat ** 2, axis=1))
# 按距离从小到大排序
sortedDistIndices = distances.argsort()
# 选择距离最小的k个点
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
weight = 1 / (distances[sortedDistIndices[i]] + 1e-8) # 防止除以零,加入微小值
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + weight
# 按类别票数从大到小排序
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
# 返回出现频率最高的类别
return sortedClassCount[0][0]
return sortedClassCount[0][0]
def load_data(file_path):