AI Wiki中文/EN

ID3 与 C4.5:增益率之前还有一道门槛

ID3 and C4.5

审计类别分裂、标识符偏好与平均增益门槛,区分连续属性、缺失值和剪枝的历史版本。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

序列号为什么赢了一个不该赢的比赛?

假设一家维修站记录了二十台设备:十台正常,十台故障。每台有唯一序列号。某个传感器把设备分成两组,每组十台,其中九台属于同一类,另一台属于另一类。

按序列号分裂,会得到二十个完全纯净的叶子;按传感器分裂,得到两个大体纯净的叶子。在这些训练记录上,信息增益更喜欢序列号。但新设备带着从未出现过的序列号来时,这种表面上的完美并没有提供可复用的分支规则。

这是人为构造的例子,不是“所有标识符都无用”的证据。它要暴露的是评分规则奖励什么。决策树基础已经解释递归划分,本章只审计一个类别测试的选择,再把这项计算与历史上的 ID3、C4.5 系统分开。

Quinlan 的 1986 年论文介绍 ID3 的信息增益规则,并在第 7 节讨论对多值属性的偏好,其中已经给出增益率的“增益达到平均或更高”筛选。因此,“C4.5 把增益除以另一个熵”漏掉了一步会改变结果的候选筛选。原论文,第 90、100—102 页。

比较测试揭示的信息与它划分数据的方式

设 D 是当前节点上一份非空、无样本权重的训练集,标签来自有限类别集合。类别测试 A 把 D 分成实际出现的非空分支 Dᵥ。令 pₖ 为父节点的类别比例,qᵥ 为进入分支 v 的比例。对数以二为底,单位为比特;概率为零的项按零计算。

H(D)=−∑kpklog⁡2pk,G(A)=H(D)−∑vqvH(Dv),qv=∣Dv∣∣D∣.H(D)=-\sum_k p_k\log_2p_k,\qquad G(A)=H(D)-\sum_vq_vH(D_v),\qquad q_v=\frac{|D_v|}{|D|}.

分支熵要按进入分支的频率加权。增益就是测试结果与标签之间的经验互信息,上界为父节点的标签熵。唯一序列号能达到这个上界,因为每个分支只有一行,不论编号过程是否与未来故障有关。

更细的划分不会降低训练信息增益

假设 A′ 是 A 的细化:只把已有分支拆小,不混合原本分开的分支。在一个旧分支内部,令 rⱼ 是新组的比例,pⱼ 是各组类别分布,它们的混合分布 p 就是旧分布。加权熵的变化为:

H(p)−∑jrjH(pj)=∑jrjDKL(pj∥p)≥0.H(p)-\sum_jr_jH(p_j)=\sum_jr_jD_{\mathrm{KL}}(p_j\Vert p)\ge0.

再乘旧分支所占比例,就得到它对 G(A′)−G(A) 的贡献。每项贡献非负;正权重子组的类别分布相同时取等号。这解释了明确的细化偏好,不是说“任何类别更多的无关属性,都必定打败任何类别更少的属性”。细化揭示更多样本内信息,却没有证明新增区别可以泛化。

增益率之前还有一道候选门槛

分裂信息是不看标签、只看分支去向的熵:

S(A)=−∑vqvlog⁡2qv,R(A)=G(A)S(A)when S(A)>0.S(A)=-\sum_vq_v\log_2q_v,\qquad R(A)=\frac{G(A)}{S(A)}\quad\text{when }S(A)>0.

常值特征的 S=0,增益率无定义。对完整数据上的非常值测试,互信息不超过测试结果本身的熵,因此精确算术下 0≤R≤1。这个比率问的是,分支信息中有多少与标签相关。它不是“增益除以类别个数”,分支大小是否均衡也会改变结果。

分母很小时,一个只隔离少数样本的测试,可能在比率上压过信息量更大的测试。Quinlan 陈述的规则先保留增益不低于平均值的候选,再最大化增益率。1986 年论文,第 102 页。对本章明确声明的候选族 E:

Gˉ=1∣E∣∑A∈EG(A),A∗∈arg max⁡A∈E: G(A)>0, G(A)≥GˉR(A).\bar G=\frac1{|E|}\sum_{A\in E}G(A),\qquad A^*\in\operatorname*{arg\,max}_{A\in E:\,G(A)>0,\ G(A)\ge\bar G}R(A).

正增益条件让没有信息的节点停止。公式必须同时说明 E 是什么。本程序为每个输入特征提供一个多路测试,要求至少两个分支各达到 min_branch 个观测,因此常值特征不能进入 E。合格的零增益测试参与平均值,但不能被选中。接口不包含声明了却没出现的类别、类别子集测试、已用属性或数值阈值搜索。

默认 min_branch=1 有意允许单样本分支,让序列号问题显现。历史手册的默认值则为两个对象,要求至少两个分支达到该值;不是要求每个分支都达到。C4.5 手册,-m 选项。这里明确的候选族与浮点规则是教学约定,不冒称复现每个发行版源码中的全部候选管理细节。

先审计候选,再选择分裂

audit 返回各分支类别计数、增益、分裂信息、增益率、平均值和通过门槛的候选。它同时返回仅按增益的胜者与不加门槛的增益率胜者,让筛选的作用可以直接比较。程序不长出整棵树,也不预测类别。id3_gain 比较也采用本审计器的候选资格和正增益停止规则;字段名表示增益目标,不代表完整历史 ID3 的停止策略。

标签与类别值必须为非空字符串;? 被保留并拒绝,None、数值、布尔值也被拒绝。特征名不得重复。数值类别可以经过明确编码变成字符串,但那会得到无序类别,不是连续阈值。空标签集非法;空特征列表返回 no-admissible-test。输入被复制,不会修改。

计数使用整数,对数与评分使用浮点数。减法造成的微小负增益会截为零;程序用固定 10⁻¹² 门槛判断正增益,平均增益筛选也允许向下同样大小的绝对容差。计算出的评分完全相同时保留输入顺序最早的特征;数学上非常接近的评分可能因舍入而不同。这是可检查的数值规则,不是精确符号排序。

from collections import Counter
from math import fsum, log2

EPS = 1e-12


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return value


def symbol(value):
    if type(value) is not str or not value or value == '?':
        raise ValueError('nonempty string required; ? is reserved for missing data')
    return value


def entropy(counts):
    # Internal helper: nonnegative integer counts with positive total.
    counts = sorted(c for c in counts if c)
    total = sum(counts)
    return fsum(-(c / total) * log2(c / total) for c in counts)


def audit(columns, labels, min_branch=1):
    """Inspect categorical tests; no recursive tree, missing values or pruning."""
    labels = tuple(symbol(y) for y in sequence(labels))
    if not labels:
        raise ValueError('nonempty labels required')
    if type(min_branch) is not int or min_branch < 1:
        raise ValueError('positive integer min_branch required')
    prepared, names = [], set()
    for pair in sequence(columns):
        pair = sequence(pair)
        if len(pair) != 2:
            raise ValueError('each column needs a name and values')
        name = symbol(pair[0])
        values = tuple(symbol(x) for x in sequence(pair[1]))
        if name in names or len(values) != len(labels):
            raise ValueError('unique names and matching lengths required')
        names.add(name)
        prepared.append((name, values))
    n, parent = len(labels), entropy(Counter(labels).values())
    scores = []
    for name, values in prepared:
        groups = {}
        for x, y in zip(values, labels):
            groups.setdefault(x, Counter())[y] += 1
        branches = tuple((x, sum(c.values()), tuple(sorted(c.items())))
                         for x, c in sorted(groups.items()))
        conditional = fsum(size / n * entropy(c for y, c in counts)
                           for x, size, counts in branches)
        gain = max(0.0, parent - conditional)
        split = entropy(size for x, size, counts in branches)
        admissible = sum(size >= min_branch for x, size, counts in branches) >= 2
        scores.append({'name': name, 'branches': branches, 'gain': gain,
                       'split_info': split, 'ratio': gain / split if split else None,
                       'admissible': admissible})
    candidates = [s for s in scores if s['admissible']]
    average = fsum(s['gain'] for s in candidates) / len(candidates) if candidates else None
    positive = [s for s in candidates if s['gain'] > EPS]
    gated = [s for s in positive if s['gain'] + EPS >= average]

    def choose(items, key):
        # max keeps the first input column on an exact computed tie.
        return max(items, key=lambda s: s[key])['name'] if items else None

    return {'entropy': parent, 'scores': tuple(scores), 'average_gain': average,
            'eligible': tuple(s['name'] for s in gated),
            'id3_gain': choose(positive, 'gain'),
            'raw_ratio': choose(positive, 'ratio'),
            'gated_ratio': choose(gated, 'ratio'),
            'status': ('selected' if positive else
                       'no-positive-gain' if candidates else 'no-admissible-test')}


if __name__ == '__main__':
    labels = ('ok',) * 10 + ('fault',) * 10
    columns = (
        ('serial', tuple('unit-' + str(i) for i in range(20))),
        ('signal', tuple('low' if i < 9 or i == 10 else 'high' for i in range(20))),
        ('rare', tuple('flag' if i == 0 else 'ordinary' for i in range(20))),
    )
    result = audit(columns, labels)
    for score in result['scores']:
        print(score['name'], 'gain=%.6f ratio=%.6f' % (score['gain'], score['ratio']))
    print('average=%.6f eligible=%s' % (result['average_gain'], result['eligible']))
    print('gain / gated:', result['id3_gain'], result['gated_ratio'])
    weak = ('weak', tuple('low' if i < 7 or 10 <= i < 13 else 'high' for i in range(20)))
    contrast = audit((weak, columns[2]), labels)
    print('weak vs rare: raw / gated:', contrast['raw_ratio'], contrast['gated_ratio'])
    print('without rare:', audit(columns[:2], labels)['gated_ratio'])
    print('minimum two:', audit(columns, labels, min_branch=2)['eligible'])
    print('constant:', audit((('fixed', ('same',) * 20),), labels)['status'])

实际输出:

serial gain=1.000000 ratio=0.231378
signal gain=0.531004 ratio=0.531004
rare gain=0.051899 ratio=0.181214
average=0.527635 eligible=('serial', 'signal')
gain / gated: serial signal
weak vs rare: raw / gated: rare weak
without rare: serial
minimum two: ('signal',)
constant: no-admissible-test

父节点熵为一比特。serial 达到这个增益,但用 log₂20 比特区分二十个分支。signal 只剩 9:1 混合的二元熵,增益与增益率都是 0.531004。rare 隔离一个样本后,剩下十九个样本的类别计数为 9 与 10,增益只有 0.051899。平均增益为 0.527635,因此 serial、signal 通过筛选,增益率选择 signal。

第二次比较换成较弱的传感器,两个分支分别为 7:3 与 3:7,增益和增益率都是 0.118709。不加门槛时,rare 的增益率 0.181214 更高,尽管它的增益更低。两者平均增益约为 0.085304,门槛排除 rare,选择 weak。

从第一个候选族删除 rare,平均值会升至约 0.765502,此时只有 serial 通过。这是实际运行过的反例:平均增益门槛加增益率,并非总能击败标识符。候选族改变,门槛也会改变。若设置 min_branch=2,serial 与 rare 都失去资格,只剩 signal。这些都是训练评分演示,不是留出集准确率测量。

设记录数为 n、特征数为 f。校验与建立全部列联表需要期望 O(n(f+1)) 次哈希操作。本实现为使报告顺序可复现,排序类别名称、标签名称和计数列表;在符号比较、计数与对数都按单位成本计时,时间上界为 O(n(f+1) log(n+1))。复制的特征列与审计记录保留 O(n(f+1)) 个槽位。字符串长度、大整数位运算及恶意哈希碰撞另有成本。这是单个节点的界,不是整树训练复杂度。

C4.5 的其余部分也会改变学习过程

连续属性。数值特征提供有序切分,结果为 A≤t 与 A>t。Quinlan 于 1996 年 3 月发表的论文区分 Release 7 与 Release 8:Release 8 按增益选择某个特征的阈值,再以调整后的增益参与最终增益率比较。对 N≥2 个不同值、n 个样本,论文为从可能阈值中选择一个,按每样本 log₂(N−1)/n 比特计费;调整后增益为负可以排除测试。这是特定版本的阈值搜索修正,与除以分支熵不同,本程序未实现。原论文,第 2—4 节,第 78—80 页。

未知值。C4.5 详细输出手册说明:被测试属性未知的样本,按观测分支频率分配带分数权重的副本。后代节点接收加权样本,而不是猜出的确定类别。本程序拒绝未知输入,以免暗中冒充实现这套处理。历史上还有差别:1986 年论文第 6 节在建立选中测试的子树前丢弃该属性未知的训练样本,但分类时会探索带权分支。不能把这些做法合并为一个不分时期的“ID3/C4.5 缺失值规则”。C4.5 详细输出手册,树构建部分;1986 年论文,第 98—99 页。

剪枝。手册描述了树长成后,利用调整的错误计数,比较保留子树、替换为叶子或最大分支;另有默认 25% 的剪枝置信设置。这个参数不是“每次预测错误概率为 25%”的证书。详细输出手册,树剪枝部分;手册,-c 选项。CART 一章讨论另一种剪枝表述。剪枝不会把局部增益排序变成全局最优保证。

对真实数据,如果使用场景中没有可迁移关系,应排除偶然的记录标识符;所有分裂与编码都在训练数据上拟合,再用适合任务的留出方式比较预测表现。真实、稳定的实体效应,与记住唯一训练行,是不同的建模问题。增益高或分支名称易读,都不建立因果关系。

改变候选族,预判选择结果

  1. 在二十台设备的例子中,计算序列号的增益、分裂信息与增益率。训练分支完全纯净,是否意味着能处理新序列号?

    答案:增益为 1 比特,分裂信息为 log₂20≈4.321928,增益率约为 0.231378。每个训练分支都纯净,但新序列号没有已观察分支,分类器仍需明确的回退或其他预测规则;本审计器不提供这些规则。

  2. 为什么不加门槛的增益率选 rare,筛选后却选较弱传感器 weak?给出两个增益与平均值。

    答案:两个增益约为 0.051899 与 0.118709,平均值为 0.085304。稀有分裂的增益率更高,为 0.181214,而弱传感器为 0.118709;但前者增益低于平均值,所以只有 weak 合格。

  3. 某测试的分支大小为 (8,2,1),在 min_branch=2 时是否合格?常值特征、合格的零增益测试、空特征列表各如何处理?

    答案:合格,因为两个分支达到最小值,第三个不必达到。常值特征增益率无定义且不合格。合格的零增益测试参与平均值,却不会被选中。空特征列表没有平均值与胜者,返回 no-admissible-test。

  4. 先从第一个例子删掉 rare,再对原来的三个特征设置 min_branch=2。为什么两次结果不同?这证明了未来准确率吗?

    答案:只剩 serial 与 signal 时,平均增益升至 0.765502,排除 signal,所以 serial 获胜。保留三列且最小值为二时,序列号的单样本分支和稀有分裂不合格,只剩 signal。候选限制改变评分比较;没有留出评测,计算不建立未来准确率结论。

把算法名与版本一起读

1986 年文章整理的是已有的 ID3 路线,不是在宣称决策树诞生于当年:第 2 节引用更早的 ID3 工作与 Hunt 的 CLS,第 4 节还包括外层窗口迭代过程。本程序只抽出分裂决策,没有复现那套历史外层流程。Quinlan,1986,第 84、88 页。

1996 年作者论文引用 1993 年 C4.5 著作,并明确比较 Release 7 与 Release 8。本次读取该文是为了核对阈值修改,不把它当作后来所有实现都相同的证据。大学托管手册用于核对候选最小值、未知样本权重和剪枝参数。没有复制或执行第三方源码;本章设备数据、评分审计器与测试均为原创。

先判断,再看解释

稀有分裂增益 0.051899、增益率 0.181214;弱传感器增益和增益率均为 0.118709。本章两个候选的平均门槛会选哪个?

选择一个答案

学习目标

  • 推导类别划分细化为何不会降低经验信息增益。
  • 计算分裂信息,审计平均增益门槛、候选资格与确定的数值选择。
  • 区分类别根节点审计、ID3 窗口过程和特定版本 C4.5 的阈值、未知值与剪枝。

先修与延伸

查看知识关联图 →

参考文献

  1. Induction of Decision Trees
    J. R. Quinlan · 1986
  2. Improved Use of Continuous Attributes in C4.5
    J. R. Quinlan · 1996
  3. C4.5 manual page — University of Regina Release 8 course archive
    C4.5 documentation; University of Regina archive
  4. Verbose C4.5 manual page — tree building and pruning
    C4.5 documentation; University of Regina archive

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • 8 项测试通过。独立 65 位 Decimal 联合分布 KL 算法核对 12 组小数据的 48 个特征测试的增益、分裂信息及比率,不重复父熵减子熵算法。16 个细化例及一个同分布例核对不减结论;一般论证由正文 KL 恒等式给出。
  • 实际执行序列号、信号、稀有测试与两个反例:原始增益率选择低增益稀有测试,删除第三候选却提高门槛而改选标识符。验证最小值 2 要求至少两个分支合格而非全部;空特征、常值、纯标签、合格零增益、完全同分、输入复制、行逆序与计数复制均通过。13 类非法数据和 5 类非法最小值被拒绝。
  • 完整两语含 6 稳定锚点、4 相同显示式、同一 Python、9 行已核输出与 4 已答练习。严格 MDX/KaTeX 及 React 实际 HTML 通过,全部 4 项数学注解对应。单节点时空界计入复制列与列联表排序;固定 EPS、候选族、仅增益比较规则及未实现完整 ID3/C4.5 均明确。
  • 读取既有决策树正文,避免重复 Gini 阈值树桩;按固定 Humanizer 技术参考文风复读。依据原论文及大学手册核对日期和缺失值差异;不声称必然排除标识符、未来准确率、逐行复现源码或人工审校。保持 written,等待独立技术交叉审查。
  • 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
  • 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。

核对的来源位置:

  • Induction of Decision Trees · Actually opened the 26-page PDF via web. Read printed p. 84 (§2, lines 99–118) and p. 88 (§4, 281–304) for earlier ID3/CLS references and windowing; pp. 89–91 (319–370) for gain and weighted child uncertainty; pp. 100–102 (§7, 666–755) for refinement bias, singleton identifiers, split information and average-or-better gate. Read pp. 98–99 (§6, 620–647) for discarding unknown-valued training cases after selecting the test versus weighted classification branches. Publisher DOI landing page independently states March 1986; no birth date inferred. Text extraction only, no visual figure audit or paper assets reused.
  • Improved Use of Continuous Attributes in C4.5 · Actually read original CMU-hosted JAIR PDF, 14 pages. First-page journal metadata gives 1996 and publication month 3/96. Printed pp. 78–80, §§2–4, web lines 50–196: default categorical/continuous tests, average-or-better gain, zero-gain stop, N−1 potential thresholds, log2(N−1)/|D| penalty, choosing the threshold by gain and final ranking by adjusted ratio, and explicit Rel 7→Rel 8 comparison. The footnote distinguishes all possible thresholds from label-dependent reduced search candidates. Read p. 88 footnote for 1993 book/Release 5 reference. No current-release equivalence, full-book reading, original benchmark reproduction or library execution claimed.
  • C4.5 manual page — University of Regina Release 8 course archive · Actually opened the university manual HTML. Lines 16–22 describe batch/windowing and post-growth pruning; 27–29 input types and ? marker; 36–45 subset option, gain option, at least two sufficiently populated branches (default 2), and confidence setting (default 25%). The separate installation page tutorial.html lines 20–28 explicitly identifies Release 8. Its tar.gz link failed in web (400) and local curl could not resolve the host; no archive/source-code review is claimed.
  • Verbose C4.5 manual page — tree building and pruning · Actually opened verbose.html. Lines 18–43 describe the candidate gain gate, numeric/discrete branches, fractional weights for unknown-tested cases and no-gain stopping. Lines 53–81 describe post-growth leaf/largest-branch comparisons and adjusted errors. These source claims are kept separate from the original categorical audit, which has no missing data or pruning.
  • Induction of Decision Trees · Actually opened university-hosted original 26-page PDF. Read printed pp. 84/88–91: earlier ID3/CLS lineage, windowing and gain; pp. 98–99 lines 620–647: unknown training cases discarded after test selection, weighted branch classification; pp. 100–102 lines 666–755: refinement bias, singleton identifiers, split information and average-or-better gate. Header confirms Machine Learning 1, 81–106, 1986. Extracted-text review; no visual scan or full-paper claim.
  • Improved Use of Continuous Attributes in C4.5 · Actually opened original 14-page JAIR paper. Header confirms submitted 10/95, published 3/96, volume 4 pp. 77–90. Read §§2–4 printed 78–80, lines 50–196: average gain, zero-gain stopping, all N−1 threshold choices, log2(N−1)/n charge, gain-based threshold selection, final adjusted ratio and explicit Release 7→8 change. Distinction from label-reduced candidate counts checked in footnote. No historical benchmark or current-library equivalence claimed.
  • C4.5 manual page — University of Regina Release 8 course archive · Actually read university manual lines 16–45: batch/windowing, input types, ? marker, gain option, at least two branches with default minimum 2 and confidence default 25%. Separately read tutorial.html lines 20–32 identifying Release 8 installation and linking the manual. The manual has no independently dated release header; no archive/source-code authentication claimed.
  • Verbose C4.5 manual page — tree building and pruning · Actually read manual lines 18–43: gain gate, candidate forms, fractional unknown-case weights, no-gain stopping; lines 53–81: leaf/largest-branch post-pruning and adjusted counts. Confirmed these are explanatory boundaries, not functions implemented by the root audit.

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。