ID3 and C4.5: the gain-ratio gate matters
ID3 与 C4.5
Audit categorical split choices, identifier bias and the average-gain gate; distinguish continuous, missing-value and pruning versions.
id3-c45Why the serial number wins the wrong contest
Suppose a workshop records twenty devices: ten work normally and ten have a fault. Each device has a unique serial number. A sensor divides them into two groups of ten, each containing nine devices of one class and one of the other.
A split on the serial number makes twenty perfectly pure leaves. A split on the sensor makes two mostly pure leaves. On these training records, information gain prefers the serial number. For a new device whose serial number has never appeared, that apparent perfection supplies no reusable branch rule.
This is a constructed example, not evidence that every identifier is useless. Its purpose is to expose what the scoring rule rewards. The decision-tree chapter covers recursive partitioning; here we inspect the choice of one categorical test, then separate that calculation from the historical ID3 and C4.5 systems.
Quinlan’s 1986 paper describes ID3’s information-gain rule and, in §7, the bias toward attributes with many outcomes. It already presents the average-or-better-gain restriction used with gain ratio. Thus “C4.5 divides gain by another entropy” leaves out a consequential selection step. Original paper, pp. 90 and 100–102.
Compare what a test reveals with how it divides the data
Let D be a nonempty, unweighted training sample at one node. Its labels belong to a finite set of classes. A categorical test A partitions D into the nonempty observed branches Dᵥ. Write pₖ for the parent class fraction and qᵥ for the fraction entering branch v. Logarithms are base two, so the quantities are measured in bits; terms with probability zero contribute zero.
The branch entropy is weighted by how often the branch occurs. Gain is empirical mutual information between the test outcome and the label. It is bounded by the parent label entropy. A unique serial number reaches that bound because every branch contains one row, regardless of whether the numbering process has any predictive relation to future faults.
More detail cannot reduce training information gain
Suppose A′ refines A: it splits an existing outcome into smaller groups and never mixes previously separate outcomes. Inside one old branch, let rⱼ be the new group proportions and pⱼ their class distributions. Their mixture is the old distribution p. The change in weighted entropy is:
Multiplying this expression by the old branch’s fraction gives that branch’s contribution to G(A′)−G(A). Every contribution is nonnegative. Equality holds when the positive-weight subdivisions have the same class distribution. This explains a precise refinement bias; it does not say that every unrelated attribute with more categories must outrank every smaller one. Refinement reveals more about the observed sample, but does not establish that the extra distinctions generalize.
Gain ratio needs a candidate gate
Split information is the entropy of the branch destination, without looking at labels:
A constant feature has S=0, so its ratio is undefined. For a complete-data nonconstant test, mutual information cannot exceed the entropy of the test outcome, giving 0≤R≤1 in exact arithmetic. The ratio asks how much of the branching information is associated with the label. It is not “gain divided by the number of categories.” Unequal branch sizes matter.
A small denominator can make a test isolating a few cases look attractive relative to a more informative test. Quinlan’s stated rule first retains candidates with at least average gain, then maximizes ratio. 1986 paper, p. 102. For the explicitly declared candidate family E in this chapter:
The positive-gain condition stops an uninformative node. The definition of E must accompany this formula. Our program uses one multiway test per supplied feature and requires at least two branches to reach min_branch observations. Constant features therefore cannot enter E. An admissible zero-gain test does enter the average, but cannot be selected. There are no unobserved declared categories, subset tests, previously used attributes or numeric threshold searches in this interface.
The default min_branch=1 deliberately permits singleton branches so that the serial-number failure is visible. The historical manual instead gives a default minimum of two objects in at least two branches. That condition does not require every branch to meet the minimum. C4.5 manual, option -m. This explicit candidate family and floating-point policy are a teaching specification, not a claim to reproduce every release’s source-level candidate bookkeeping.
Audit the candidates before selecting one
audit returns branch class counts, gains, split information, ratios, the average and the candidates that pass the gate. It also reports the gain-only winner and the unrestricted-ratio winner, making the effect of the gate visible. It does not grow a tree or predict classes. The id3_gain comparison uses this audit’s same admissibility and positive-gain stopping rules; that field names the gain objective, not a complete historical ID3 stopping policy.
Labels and category values must be nonempty strings; ? is reserved and rejected, as are None, numeric values and Booleans. Feature names must be unique. Numeric categories can be deliberately encoded as strings, but doing so creates unordered categories, not continuous thresholds. Empty labels are invalid; an empty feature list returns no-admissible-test. Inputs are copied and never modified.
Counts are integers; logarithms and scores are floating point. The program clamps a tiny negative gain caused by subtraction to zero, uses a fixed 10⁻¹² threshold for positive gain, and allows that same absolute tolerance below the average gate. Exact computed score ties keep the first supplied feature. Nearly equal mathematical scores may round differently; this is an inspectable numerical rule, not an exact symbolic ranking.
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'])
Actual output:
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
The parent entropy is one bit. serial reaches it, but spends log₂20 bits distinguishing twenty branches. signal loses only the binary entropy of a 9:1 mixture, giving gain and ratio 0.531004. The isolated case in rare leaves a nineteen-case branch with class counts 9 and 10. Its gain is only 0.051899. The mean gain is 0.527635, so serial and signal pass; ratio chooses signal.
The second comparison uses a weaker sensor with 7:3 and 3:7 branches. Its gain and ratio are 0.118709. An unrestricted ratio prefers rare at 0.181214, despite its lower gain. Their mean gain is about 0.085304, so the gate excludes rare and selects weak.
Removing rare from the first candidate family raises the average to about 0.765502. Now only serial passes. This is an executed counterexample to the claim that gain ratio with an average gate always defeats identifiers. Changing the candidate family can change the gate. With min_branch=2, both serial and rare become inadmissible, leaving signal. These are training-score demonstrations, not held-out accuracy measurements.
For n records and f features, validation and all contingency tables take expected O(n(f+1)) hash operations. This implementation sorts category names, label names and count lists for reproducible reporting, giving an O(n(f+1) log(n+1)) time bound under unit-cost symbol comparisons, counts and logarithms. It retains copied columns and audit records in O(n(f+1)) slots. String length, large-integer bit operations and adversarial hash collisions add costs. These bounds describe one node; they are not full-tree training bounds.
The rest of C4.5 changes the learning problem too
Continuous attributes. A numeric feature offers ordered cuts, with two outcomes A≤t and A>t. Quinlan’s March 1996 paper distinguishes Release 7 from Release 8: Release 8 chooses a feature’s threshold by gain, then uses an adjusted gain in the final ratio comparison. For N≥2 distinct values and n cases, the paper charges log₂(N−1)/n bits per case for choosing among the possible thresholds. A negative adjusted gain can exclude a test. This is a version-specific threshold-search correction, separate from normalizing by branch entropy; it is not implemented here. Original paper, §§2–4, pp. 78–80.
Unknown values. The C4.5 verbose manual describes a case with an unknown tested value being distributed across branches with fractional weights based on observed branch frequencies. Descendants therefore receive weighted cases, rather than a guessed hard category. Our rejection of unknown inputs avoids silently pretending to implement that procedure. There is also a historical difference: the 1986 paper’s §6 discards unknown-valued training cases before constructing the chosen test’s child trees, even though classification explores weighted branches. These procedures should not be merged into one timeless “ID3/C4.5 missing-value rule.” C4.5 verbose manual, tree building; 1986 paper, pp. 98–99.
Pruning. The manual describes post-growth comparisons with a leaf or the largest branch, using error adjustments; it also exposes a pruning confidence setting, default 25%. That setting is not a certificate that each prediction has a 25% error probability. Verbose manual, tree pruning; manual, option -c. The CART chapter treats a different pruning formulation. No pruning method turns the local gain ranking into a global optimum guarantee.
For a real dataset, exclude accidental record identifiers when the intended use provides no transferable relation, fit every split or encoding using training data, and compare predictive performance on an appropriate held-out split. A legitimate stable entity effect is a different modeling question from memorizing one unique training row. Neither a high gain nor a readable branch label establishes causality.
Change the candidate family and predict the result
-
In the twenty-device example, calculate the serial-number gain, split information and gain ratio. Does its pure training partition imply a rule for a new serial number?
Answer: Gain is 1 bit, split information is log₂20≈4.321928, and ratio is about 0.231378. Every training branch is pure. An unseen serial number has no observed branch, so a classifier would still need an explicit fallback or other prediction rule; this audit provides neither.
-
Why does raw ratio select
rareover the weaker sensor, while the gated criterion selectsweak? State both gains and the average.Answer: Their gains are about 0.051899 and 0.118709; the average is 0.085304. The rare split has the larger ratio, 0.181214 versus 0.118709, but falls below the average gain. Only
weakis eligible. -
A test has branch counts (8,2,1). Is it admissible for
min_branch=2? What happens to a constant feature, an admissible zero-gain test and an empty feature list?Answer: Yes: two branches meet the minimum; the third need not. A constant feature has undefined ratio and is inadmissible. An admissible zero-gain test contributes to the average but cannot be selected. An empty feature list returns no average, no winners and
no-admissible-test. -
Remove
rarefrom the first example, then setmin_branch=2on the original three-feature example. Why do the results differ? Does this prove anything about future accuracy?Answer: With only
serialandsignal, average gain rises to 0.765502, excludingsignal, soserialwins. With all three features and minimum two, the singleton identifier branches and rare split fail admissibility, leavingsignal. Candidate restrictions change the score comparison. No held-out evaluation was performed, so these calculations establish no future accuracy claim.
Read the algorithm name together with its version
The 1986 article is an account of an existing ID3 line, not a claim that decision trees began in that year: its §2 cites earlier ID3 work and Hunt’s CLS. Its §4 also includes an outer windowing procedure. Our program isolates the split decision and does not reproduce that historical shell. Quinlan, 1986, pp. 84 and 88.
The 1996 author’s paper cites the 1993 C4.5 book and explicitly compares Releases 7 and 8. That paper was read for the threshold modifications, not used as evidence that every later implementation behaves identically. The university-hosted manuals were read for candidate minimums, unknown-case weights and pruning controls. No third-party source code was copied or executed. The small device datasets, score audit and tests here are original.
Make a prediction, then check
A rare split has gain 0.051899 and ratio 0.181214; a weak sensor has gain and ratio 0.118709. Under this chapter’s two-candidate average gate, which is selected?
Learning objectives
- Derive why refining a categorical partition cannot reduce empirical information gain.
- Compute split information and audit the average-gain gate, admissible candidates and deterministic numerical choices.
- Separate a categorical root audit from ID3 windowing and version-specific C4.5 thresholds, unknown values and pruning.
Prerequisites & connections
Explore related knowledge →References
- Induction of Decision Trees
J. R. Quinlan · 1986 - Improved Use of Continuous Attributes in C4.5
J. R. Quinlan · 1996 - C4.5 manual page — University of Regina Release 8 course archive
C4.5 documentation; University of Regina archive - Verbose C4.5 manual page — tree building and pruning
C4.5 documentation; University of Regina archive
Version1 · Editorial status: Recorded technical checks completed
View technical check record (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.
- Eight tests pass. Independent 65-digit Decimal joint-distribution KL calculations check gain, split information and ratio for 48 feature tests over 12 small datasets, rather than recomputing parent-minus-child entropy. Sixteen refinement cases plus an equal-distribution case check the nondecrease claim; its general justification is the prose KL identity.
- Executed serial/signal/rare scores and both counterexamples: raw ratio chooses the lower-gain rare test, while removing a third candidate raises the gate enough to select the identifier. Verified minimum 2 means at least two qualifying branches, not every branch; empty features, constant tests, pure labels, admissible zero gain, exact computed ties, input copies, row reversal and replicated counts all pass. Thirteen invalid data cases and five invalid minimums are rejected.
- Both complete articles use six stable anchors, four identical display equations, identical Python and nine verified stdout lines, with four answered exercises. Strict MDX/KaTeX and actual React HTML passed; all four math annotations match across languages. The copied columns and sorted contingency audit are included in the single-node time/space bounds. Fixed EPS, candidate family, gain-only comparison policy and absence of full ID3/C4.5 are explicit.
- Read the existing decision-trees article to avoid repeating its Gini threshold stump. Reread under pinned Humanizer technical/reference guidance. Dates and missing-value differences were checked against the original papers and university manuals; no claims of universal identifier removal, future accuracy, exact source-code replication or human peer review. Review remains written pending independent technical cross-review.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- 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.
Related topics