分步实践任务说明
共 3 个核验步骤01
步骤 1:实现信息熵计算函数 entropy
实现 `entropy(labels)` 计算标签列表以 2 为底的香农信息熵 H(D)=-\sum p_k \log₂ p_k,在给定 8 条样本上打印 `root_entropy=<浮点>`。
02
步骤 2:实现信息增益函数 information_gain
实现 `information_gain(rows, labels, feature_idx)` 计算按指定列划分后的信息增益,找出增益最大的根特征并打印 `best_feature=<列索引>` 与 `best_gain=<浮点>`。
03
步骤 3:实现递归建树 build_id3_tree 与预测 predict_one
实现 `build_id3_tree(rows, labels, feature_names)` 与 `predict_one(tree, sample_dict, default_label='yes')`,在训练集上验证拟合准确率并打印 `train_acc=<浮点>`。
起步代码框架预览
Pythonimport math
from collections import Counter
def entropy(labels):
"""计算标签列表的信息熵(以 2 为底)。"""
# TODO 1: 统计各类别比例 p,累加 -p * log2(p)
raise NotImplementedError("请补全 entropy")
def information_gain(rows, labels, feature_idx):
"""计算按第 feature_idx 列特征划分数据集后的信息增益。"""
# TODO 2: 计算根熵减去各取值子集的加权条件熵
raise NotImplementedError("请补全 information_gain")
def build_id3_tree(rows, labels, feature_names):
"""递归构建 ID3 决策树。
叶节点直接返回类别标签字符串;内部节点返回 {特征名: {特征值: 子树, ...}}。
"""
# TODO 3: 处理纯类别、无剩余特征等递归终止条件,选择信息增益最大特征划分
raise NotImplementedError("请补全 build_id3_tree")
def predict_one(tree, sample_dict, default_label="yes"):
"""使用构建好的树对字典形式样本进行预测,遇到未见特征值时返回 default_label。"""
# TODO 3: 递归查表直到到达叶节点
raise NotImplementedError("请补全 predict_one")