generated from LufsX/Challenge-kNN
This commit is contained in:
+15
-6
@@ -1,5 +1,4 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from collections import Counter
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
挑战说明:
|
挑战说明:
|
||||||
@@ -21,14 +20,12 @@ from collections import Counter
|
|||||||
- numpy: 2.1.1
|
- numpy: 2.1.1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
请在这里填写学号和姓名,不填写即成绩无效。
|
||||||
"""
|
"""
|
||||||
id = "202210423126"
|
id = "202210423126"
|
||||||
name = "邓杰元"
|
name = "邓杰元"
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
参数说明:
|
参数说明:
|
||||||
- inX (numpy array): 输入待分类的样本。
|
- inX (numpy array): 输入待分类的样本。
|
||||||
@@ -61,11 +58,24 @@ def classify0(inX, dataSet, labels, k=20):
|
|||||||
# 获取这 k 个样本的标签
|
# 获取这 k 个样本的标签
|
||||||
k_nearest_labels = labels[k_indices]
|
k_nearest_labels = labels[k_indices]
|
||||||
|
|
||||||
|
# 手动实现一个计数器,统计每个标签出现的次数
|
||||||
|
label_count = {}
|
||||||
|
for label in k_nearest_labels:
|
||||||
|
if label in label_count:
|
||||||
|
label_count[label] += 1
|
||||||
|
else:
|
||||||
|
label_count[label] = 1
|
||||||
|
|
||||||
# 找出出现次数最多的标签
|
# 找出出现次数最多的标签
|
||||||
most_common = Counter(k_nearest_labels).most_common(1)
|
max_count = -1
|
||||||
|
most_common_label = None
|
||||||
|
for label, count in label_count.items():
|
||||||
|
if count > max_count:
|
||||||
|
max_count = count
|
||||||
|
most_common_label = label
|
||||||
|
|
||||||
# 返回出现次数最多的标签
|
# 返回出现次数最多的标签
|
||||||
return most_common[0][0]
|
return most_common_label
|
||||||
|
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
@@ -95,5 +105,4 @@ if __name__ == "__main__":
|
|||||||
test_data, test_labels = load_data(test_file)
|
test_data, test_labels = load_data(test_file)
|
||||||
|
|
||||||
# 测试 classify0 函数
|
# 测试 classify0 函数
|
||||||
# 注意:这里只是演示,实际评测会使用独立的测试集
|
|
||||||
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
|
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
|
||||||
Reference in New Issue
Block a user