diff --git a/function.py b/function.py index 3a48f96..8877e42 100644 --- a/function.py +++ b/function.py @@ -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):