generated from LufsX/Challenge-kNN
This commit is contained in:
+2
-3
@@ -71,12 +71,12 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
dists = np.sqrt(((dataSet - inX) ** 2).sum(axis=1))
|
||||
dists = np.sum(np.abs(dataSet - inX), axis=1)
|
||||
sorted_index = np.argsort(dists)
|
||||
class_count = {}
|
||||
for i in range(k):
|
||||
vote_label = labels[sorted_index[i]]
|
||||
class_count[vote_label] = class_count.get(vote_label, 0) + 1 / (dists[sorted_index[i]] + 1e-5) # 加权,防止除零
|
||||
class_count[vote_label] = class_count.get(vote_label, 0) + 1
|
||||
sorted_class_count = sorted(class_count.items(), key=lambda item: item[1], reverse=True)
|
||||
if sorted_class_count:
|
||||
return sorted_class_count[0][0]
|
||||
@@ -96,7 +96,6 @@ if __name__ == "__main__":
|
||||
train_features, train_labels = load_data("datingTrainSet2.tsv")
|
||||
test_features, test_labels = load_data("datingTestSet2.tsv")
|
||||
|
||||
# 归一化特征
|
||||
train_features = normalize(train_features)
|
||||
test_features = normalize(test_features)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user