Building a Tree from Examples: ID3
We now have all the pieces. ID3 (Iterative Dichotomiser 3, Ross Quinlan, 1986) builds a tree top-down by repeatedly asking the most informative question. Its descendants C4.5 and CART still power real systems, including random forests and gradient boosting.
The algorithm
function ID3(examples, attributes, parent_examples):
if examples is empty: return PLURALITY(parent_examples)
else if all examples have the same class: return that class
else if attributes is empty: return PLURALITY(examples)
else:
A ← the attribute in attributes with the highest Gain(examples, A)
tree ← a new node testing A
for each value v of A:
exs ← { e in examples : e.A = v }
subtree ← ID3(exs, attributes − {A}, examples)
add a branch to tree labelled (A = v) leading to subtree
return tree
Each of the three base cases has a reason:
- No examples left for some value: we've never seen this combination, so guess the parent's majority class.
- All examples agree: the node is pure, so make a leaf.
- No attributes left but the examples still disagree: identical inputs with different labels. That's noise (or a missing feature), so take a majority vote. Remember \(y = f(x) + \varepsilon\) from Chapter 2.
Worked example: the whole PlayTennis tree by hand
| Day | Outlook | Temp | Humidity | Wind | Play |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Strong | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Weak | Yes |
| D11 | Sunny | Mild | Normal | Strong | Yes |
| D12 | Overcast | Mild | High | Strong | Yes |
| D13 | Overcast | Hot | Normal | Weak | Yes |
| D14 | Rain | Mild | High | Strong | No |
Step 1: the root. From §6.2: Gain(Outlook) = 0.247, Gain(Humidity) = 0.152, Gain(Wind) = 0.048, Gain(Temp) = 0.029. Split on Outlook.
Step 2: Overcast branch {D3, D7, D12, D13}: all Yes, so it's a leaf: Yes.
Step 3: Sunny branch {D1, D2, D8, D9, D11} = [2+, 3−], H = 0.971.
| Attribute | Split | Remainder | Gain |
|---|---|---|---|
| Humidity | High [0+,3−], Normal [2+,0−] | 0 | 0.971 |
| Temp | Hot [0+,2−], Mild [1+,1−], Cool [1+,0−] | \(\tfrac25 \cdot 1 = 0.400\) | 0.571 |
| Wind | Weak [1+,2−], Strong [1+,1−] | \(\tfrac35(0.918) + \tfrac25(1) = 0.951\) | 0.020 |
Split on Humidity: High → No, Normal → Yes. Both children are pure.
Step 4: Rain branch {D4, D5, D6, D10, D14} = [3+, 2−], H = 0.971.
| Attribute | Split | Remainder | Gain |
|---|---|---|---|
| Wind | Weak [3+,0−], Strong [0+,2−] | 0 | 0.971 |
| Humidity | High [1+,1−], Normal [2+,1−] | \(\tfrac25(1) + \tfrac35(0.918) = 0.951\) | 0.020 |
| Temp | Mild [2+,1−], Cool [1+,1−] | 0.951 | 0.020 |
Split on Wind: Weak → Yes, Strong → No.
Done. The tree in §6.1 uses only 3 of the 4 attributes. Temperature was never needed. The algorithm discovered that it's irrelevant given the others, which is automatic feature selection.
Play with it
The builder below runs ID3 live. Untick a few rows to remove those examples and watch the tree change. Remove D6 and D14 (the only "Rain, No" days), and the whole Rain branch collapses into a single "Yes" leaf. Now restore them and remove only D3, a single Overcast day. The root itself flips from Outlook to Humidity (gain 0.219 vs 0.214), and the whole tree reorganizes. Removing D13, another Overcast day, changes nothing. One example out of fourteen can rewrite the whole model: decision trees are high-variance models (§2.3). That's the reason random forests exist (§6.4).
In code
import math
from collections import Counter
ATTRS = ["Outlook", "Temp", "Humidity", "Wind"]
DATA = [("Sunny","Hot","High","Weak","No"), ("Sunny","Hot","High","Strong","No"),
("Overcast","Hot","High","Weak","Yes"), ("Rain","Mild","High","Weak","Yes"),
("Rain","Cool","Normal","Weak","Yes"), ("Rain","Cool","Normal","Strong","No"),
("Overcast","Cool","Normal","Strong","Yes"), ("Sunny","Mild","High","Weak","No"),
("Sunny","Cool","Normal","Weak","Yes"), ("Rain","Mild","Normal","Weak","Yes"),
("Sunny","Mild","Normal","Strong","Yes"), ("Overcast","Mild","High","Strong","Yes"),
("Overcast","Hot","Normal","Weak","Yes"), ("Rain","Mild","High","Strong","No")]
def entropy(rows):
n = len(rows)
return -sum(c / n * math.log2(c / n) for c in Counter(r[-1] for r in rows).values())
def info_gain(rows, i):
rem = 0.0
for v in set(r[i] for r in rows):
sub = [r for r in rows if r[i] == v]
rem += len(sub) / len(rows) * entropy(sub)
return entropy(rows) - rem
def plurality(rows):
return Counter(r[-1] for r in rows).most_common(1)[0][0]
def id3(rows, attrs, parent_rows=None):
if not rows: # no examples: use the parent's majority
return plurality(parent_rows)
labels = set(r[-1] for r in rows)
if len(labels) == 1: # pure node: a leaf
return labels.pop()
if not attrs: # no attributes left: majority vote
return plurality(rows)
best = max(attrs, key=lambda i: info_gain(rows, i))
tree = {"attr": ATTRS[best], "branches": {}}
for v in sorted(set(r[best] for r in DATA)): # every value of the attribute, seen or not
subset = [r for r in rows if r[best] == v]
tree["branches"][v] = id3(subset, [a for a in attrs if a != best], rows)
return tree
def show(tree, indent=""):
if isinstance(tree, str):
print(indent + "-> " + tree); return
for v, sub in tree["branches"].items():
print(f"{indent}{tree['attr']} = {v}")
show(sub, indent + " ")
def classify(tree, x):
while isinstance(tree, dict):
tree = tree["branches"][x[ATTRS.index(tree["attr"])]]
return tree
tree = id3(DATA, list(range(len(ATTRS))))
show(tree)
print("training accuracy:", sum(classify(tree, r) == r[-1] for r in DATA), "/", len(DATA))
print("new day (Sunny, Cool, High, Strong) ->", classify(tree, ("Sunny", "Cool", "High", "Strong")))Outlook = Overcast
-> Yes
Outlook = Rain
Wind = Strong
-> No
Wind = Weak
-> Yes
Outlook = Sunny
Humidity = High
-> No
Humidity = Normal
-> Yes
training accuracy: 14 / 14
new day (Sunny, Cool, High, Strong) -> No
The tree says No for (Sunny, Cool, High, Strong), the same answer naive Bayes gave in §4.2 with 79.5% confidence. Two very different models with different inductive biases agree here. When they disagree, it's worth asking why.
ID3 as search
Viewed through Chapter 3, ID3 is a greedy hill-climbing search through the space of trees:
- State: a partial tree. Move: replace a leaf with a test. Heuristic: information gain.
- No backtracking: once it chooses Outlook at the root, it never reconsiders. Like any hill climber it can reach a local optimum: a tree that's consistent but bigger than necessary. Parity functions fool it completely, because every single attribute has zero gain on its own.
- Uses all examples at every step (statistics, not individual examples), so it is fairly robust to individual noisy examples.
ID3's inductive bias: it prefers shorter trees, and trees that put high-information-gain attributes near the root. This is a preference (search) bias, not a restriction bias: the hypothesis space contains every possible tree, and the algorithm simply tries the simple-looking ones first.
- "Construct the decision tree for this dataset using ID3. Show all information-gain computations." Lay it out exactly like Steps 1–4: a table per node with splits, remainders and gains.
- Remember to remove the used attribute when you recurse, and handle empty branches with the parent's majority.
- Ties: state your tie-breaking rule (e.g. alphabetical, or first in the list).
- "What is ID3's inductive bias?" Shorter trees; high-gain attributes near the root; Occam's razor.