generated from LufsX/Challenge-kNN
This commit is contained in:
+5
-8
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user