generated from LufsX/Challenge-kNN
This commit is contained in:
+19
-10
@@ -1,5 +1,4 @@
|
||||
import numpy as np
|
||||
from collections import Counter
|
||||
|
||||
"""
|
||||
挑战说明:
|
||||
@@ -21,14 +20,12 @@ from collections import Counter
|
||||
- numpy: 2.1.1
|
||||
"""
|
||||
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423126"
|
||||
name = "邓杰元"
|
||||
|
||||
|
||||
"""
|
||||
参数说明:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
@@ -42,13 +39,13 @@ name = "邓杰元"
|
||||
def classify0(inX, dataSet, labels, k=20):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,默认值为 20。
|
||||
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
@@ -61,20 +58,33 @@ def classify0(inX, dataSet, labels, k=20):
|
||||
# 获取这 k 个样本的标签
|
||||
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):
|
||||
"""
|
||||
加载 TSV 格式数据文件。
|
||||
|
||||
|
||||
Args:
|
||||
- file_path (str): 数据文件路径。
|
||||
|
||||
|
||||
Returns:
|
||||
- features (numpy array): 数据特征矩阵。
|
||||
- labels (numpy array): 数据对应的标签。
|
||||
@@ -95,5 +105,4 @@ if __name__ == "__main__":
|
||||
test_data, test_labels = load_data(test_file)
|
||||
|
||||
# 测试 classify0 函数
|
||||
# 注意:这里只是演示,实际评测会使用独立的测试集
|
||||
print(classify0([65915, 3.868359, 0.128078], train_data, train_labels))
|
||||
Reference in New Issue
Block a user