diff --git a/function.py b/function.py index 7f551ad..03376ee 100644 --- a/function.py +++ b/function.py @@ -50,15 +50,24 @@ def classify0(inX, dataSet, labels,k=3): Returns: - 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] - - from collections import Counter - vote_result = Counter(k_nearest_labels).most_common(1) - - return vote_result[0][0] + # 对距离进行排序,并获取索引 + sortedDistIndicies = distances.argsort() + + # 选择距离最小的k个点 + classCount = {} + for i in range(k): + 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): """