The running dataset — "Should the club hold practice today?"
Quinlan’s weather data, 14 days. Features: Outlook ∈{S,O,R} (Sunny, Overcast, Rainy), Temperature ∈{H,M,C}, Humidity ∈{H,N}, Wind ∈{F,T} (False / True). Class Play∈{Y,N} — 9 Yes, 5 No.
#
Out
Temp
Hum
Wind
Play
#
Out
Temp
Hum
Wind
Play
1
S
H
H
F
N
8
S
M
H
F
N
2
S
H
H
T
N
9
S
C
N
F
Y
3
O
H
H
F
Y
10
R
M
N
F
Y
4
R
M
H
F
Y
11
S
M
N
T
Y
5
R
C
N
F
Y
12
O
M
H
T
Y
6
R
C
N
T
N
13
O
H
N
F
Y
7
O
C
N
T
Y
14
R
M
H
T
N
Errata in the source
The lecture prints "E(X)=−59log259−149log2149" — a typo. Correct: −149log2149−145log2145=0.940. The “gain ratio” denominator written E(X,f) is the split information (C6). Both are corrected below.
Python helpers — run this block once, the checks below reuse it
from math import log2, sqrt, comb# a node is a tuple of class counts, e.g. (9, 5) = 9 Yes, 5 NoH = lambda *c: -sum(x/sum(c) * log2(x/sum(c)) for x in c if x) # entropyG = lambda *c: 1 - sum((x/sum(c))**2 for x in c) # Ginidef gain(f, parent, kids): # f = H or G n = sum(map(sum, kids)) return f(*parent) - sum(sum(k)/n * f(*k) for k in kids)split_info = lambda *sizes: H(*sizes) # entropy of the branch sizes
C4. Entropy and Information Gain
Intuition
Entropy measures how mixed a set is. A bag with only Yes’s is “pure”: no surprise, entropy 0. A bag half Yes, half No is maximally mixed: entropy 1 bit.
Information gain = how much a question (a feature) reduces the mixing. Pick the question that reduces it most — like playing 20 Questions and always asking the most informative one first.
For a set X with c classes and class proportions pi:
E(X)=∑i=1c−pilog2pi,0log0:=0.
Information gain of feature f:
IG(X,f)=E(X)−∑v∈values(f)∣X∣∣Xv∣E(Xv),Xv={x∈X:f(x)=v}.
Mathematical formulation / properties
E(X)=0 iff all members are in one class.
Two classes: E=1 iff p=21; E∈[0,1].
c classes: 0≤E≤log2c, with equality on the right iff all pi=1/c.
Interpretation: minimum average number of bits to encode the class of a random member.
Derivation (maximum at the uniform distribution, two classes)
E(p)=−plog2p−(1−p)log2(1−p). Differentiate:
E′(p)=−log2p−ln21+log2(1−p)+ln21=log2p1−p.E′(p)=0⟺p=21; E′>0 for p<21 and <0 for p>21 → maximum, E(21)=1. ∎
Why IG≥0: IG equals the mutual information between feature and class, which is non-negative (Jensen’s inequality / concavity of entropy: the weighted average of child entropies cannot exceed the parent entropy).
Key insights
IG is the expected reduction in entropy from learning f.
IG is biased toward features with many values (a unique-ID column gives pure singleton children, IG = full entropy) → fixed by gain ratio (C6).
Greedy: IG is only a one-step lookahead (see C9, XOR failure).
Worked examples
Example 1 — Very Easy · Inspecting a batch of parts
Problem: Compute E for a batch of 8 parts: (a) 8 pass and 0 fail; (b) 4 pass and 4 fail; (c) 1 pass and 3 fail.
The best feature depends on the node; recompute gains on the subset.
Example 5 — Very Hard · Where to cut a temperature scale
Problem: A club records the temperature band x=1,…,8 (cold → hot) and whether the match was played: N,N,Y,Y,Y,N,N,N (too cold and too hot are both bad). Using binary splits ”x<t vs x≥t” at midpoints, find the best threshold by IG. Also state which thresholds need to be considered at all.
Asked: Best t and candidate set.
Concept: IG for continuous features (C4.5-style thresholds).
Approach: Parent entropy; evaluate midpoints; observe that only label-change boundaries can be optimal.
Only midpoints between adjacent values with different labels (2.5 and 5.5) can be optimal, since moving a cut inside a same-label run can only mix classes.
Final answer:t∗=5.5, IG=0.348.
Python check
y = "NNYYYNNN"for t in range(1, 8): # cut after x = t -> threshold t + 0.5 L, R = y[:t], y[t:] kids = [(L.count("Y"), L.count("N")), (R.count("Y"), R.count("N"))] print(t + 0.5, round(gain(H, (3, 5), kids), 4))
Key lesson
For numeric features, scan label-boundary midpoints. The best cut need not be near the median.
Common mistakes
Using ln instead of log2 (changes units, not the argmax, but changes numbers).
Forgetting the weights ∣Xv∣/∣X∣.
Computing IG over the whole data instead of the current node’s subset.
Exam traps
0log0=0 must be stated.
Entropy range [0,1] is only for two classes.
IG favours many-valued features.
Connections: Gain ratio (C6), Gini (C5), mutual information in NMI (C42), cross-entropy loss in logistic regression (C27).
Mastery checklist
Compute E and IG by hand.
Prove the two-class maximum at p=21.
Explain the many-valued bias.
Choose numeric thresholds.
C5. Gini Index and Gini Gain
Intuition
Gini is the probability that two random draws (with replacement) from the node belong to different classes. Pure node → never different → 0.
Formal definition
For a node X with proportions pi:
Gini(X)=1−∑i=1cpi2.
For feature f (weighted over its branches, as in the lecture):
Gini(X,f)=∑v∣X∣∣Xv∣Gini(Xv),GiniGain(X,f)=Gini(X)−Gini(X,f).
Choose the feature with the smallestGini(X,f), equivalently the largest gain.
Mathematical properties
Gini=0 iff pure. Maximum 1−c1 at uniform proportions (two classes: 0.5).
Proof of max: minimise ∑pi2 subject to ∑pi=1 → Lagrange: 2pi=λ ⇒ all pi equal =1/c ⇒ ∑pi2=1/c.
Used by CART; CART splits are binary (e.g. “Outlook = Overcast?” yes / no).
Derivation: Gini as misclassification probability
Label a random item by sampling a label from the node’s class distribution. P(wrong)=∑ipi(1−pi)=∑pi−∑pi2=1−∑pi2. ∎
Key insights
No logarithms → cheaper than entropy.
Tends to isolate the largest class.
Usually ranks features like entropy, but not always (Example 5).
Worked examples
Example 1 — Very Easy · Gini of the weather data
Problem:Gini of (9 Yes, 5 No).
Asked:Gini(X).
Concept: Definition.
Approach:1−(pY2+pN2).
Solution:pY2=81/196=0.4133; pN2=25/196=0.1276. Sum =0.5408. Gini=0.4592.
Final answer:0.459.
Key lesson
Max for two classes is 0.5.
Example 2 — Easy · Range of Gini
Problem: Gini of a pure node, a 50 / 50 node and a 4-class uniform node.
Overcast vs rest: Overcast Gini 0; rest (5Y,5N) =0.5. Weighted 144⋅0+1410⋅0.5=0.3571. Gain 0.102.
Sunny vs rest: Sunny 0.48; rest (7Y,2N) =0.3457. Weighted 0.1714+0.2222=0.3936. Gain 0.066.
Rainy vs rest: Rainy 0.48; rest (6Y,3N) =0.4444. Weighted 0.1714+0.2857=0.4571. Gain 0.002.
Final answer: “Overcast vs not Overcast” (gain 0.102).
Python check
for name, a, b in [("Overcast", (4,0), (5,5)), ("Sunny", (2,3), (7,2)), ("Rainy", (3,2), (6,3))]: print(name, round(gain(G, (9, 5), [a, b]), 4)) # 0.102 0.0655 0.002
Key lesson
Binary-split algorithms must choose which grouping, not just which feature.
Example 5 — Very Hard · Entropy and Gini disagree
Problem: A fraud-screening node has 15 fraud and 15 legitimate cases. Rule A produces children (0 fraud, 4 legit) and (15 fraud, 11 legit). Rule B produces (3 fraud, 9 legit) and (12 fraud, 6 legit). Which rule does information gain prefer? Which does Gini prefer? Explain.
Comparison: IG: 0.148>0.125 → A. Gini: 0.0769<0.0833 → B.
Final answer: Entropy prefers A; Gini prefers B.
IG
Gini gain
Winner
Split A (tiny pure child)
0.148
0.077
entropy
Split B (two moderately pure children)
0.125
0.083
Gini
Python check
A = [(0, 4), (15, 11)]; B = [(3, 9), (12, 6)]for name, f in [("entropy", H), ("gini", G)]: print(name, round(gain(f, (15, 15), A), 4), round(gain(f, (15, 15), B), 4))# entropy 0.1482 0.1245 -> A | gini 0.0769 0.0833 -> B
Key lesson
Entropy rewards carving out a small, perfectly pure node more strongly than Gini. They usually agree but are not equivalent.
Common mistakes
Using entropy’s range for Gini.
Forgetting weights; minimising Gini gain instead of maximising it (or maximising the weighted Gini instead of minimising).
Exam traps
“Smallest Gini index” ⇔ “largest Gini gain” — be consistent.
Max Gini for c classes is 1−1/c, not 0.5.
Connections: Entropy (C4), CART (C9), random forests (C10); for 2 classes Gini=2p(1−p), the Bernoulli variance ×2.
Mastery checklist
Compute Gini and Gini gain.
Do binary subset splits of a categorical feature.
Explain when Gini and IG disagree.
C6. Gain Ratio
Intuition
Information gain loves features with many values — a Day-ID column perfectly “explains” the class by memorising each row. Gain ratio divides by how finely the feature fragments the data (its split information) to penalise that.
Formal definition
SplitInfo(X,f)=−∑v∣X∣∣Xv∣log2∣X∣∣Xv∣,GainRatio(X,f)=SplitInfo(X,f)IG(X,f).
(The lecture writes the denominator as E(X,f); it is the entropy of the partition sizes.) Undefined when SplitInfo=0 (feature has a single value).
Mathematical formulation
SplitInfo is the entropy of the feature’s own value distribution; for k equal-size branches it is log2k.
Derivation (why it penalises ID-like features)
For a feature with n unique values in n rows, IG=E(X) (all children pure) but SplitInfo=log2n. So GR=E(X)/log2n→0 as n grows.
Key insights
Used by C4.5.
It can over-correct (favours very unbalanced splits with tiny SplitInfo).
Worked examples
Example 1 — Very Easy · How fragmented is the split?
Problem:SplitInfo of a binary split with sizes 7 and 7; of a 3-way equal split.
Ranking can stay the same while the gap shrinks (0.247 vs 0.152 becomes 0.156 vs 0.152).
Example 4 — Hard · A useless “Day” column
Problem: Add a “Day” feature with 14 distinct values to the weather data. Compute its IG, SplitInfo, GR and compare to Outlook under both criteria.
Asked: The bias and how much GR corrects it.
Concept: Bias of IG.
Approach: All 14 children are singletons.
Solution: Each child pure → weighted child entropy 0 → IG=0.9403. SplitInfo=log214=3.8074. GR=0.9403/3.8074=0.2470. Under IG, Day beats Outlook 0.940 vs 0.247 (ratio 3.8). Under GR, Day beats Outlook 0.247 vs 0.156 (ratio 1.6).
Final answer: GR greatly reduces but does not remove the bias; a useless ID still wins here.
Key lesson
In practice drop identifier-like columns (or add extra heuristics), regardless of the criterion.
Example 5 — Very Hard · IG and GR choose different winners
Problem: Parent: 6 Yes, 6 No. Feature A (say, postcode) has four values: three singletons each containing 1 No, and one value with (6Y, 3N). Feature B is binary: (0Y, 2N) and (6Y, 4N). Which does IG pick? Which does GR pick?
Asked: Rankings that disagree.
Concept: GR changes the winner.
Approach: Compute IG, SplitInfo, GR of each.
Solution: Parent E=1.
A: three pure children (weight 121 each); big child n=9: p=(32,31), E=0.9183. Weighted =0.6887; IGA=0.3113. SplitInfoA=1.2075; GRA=0.2578.
Final answer: IG picks A (0.311>0.191); GR picks B (0.294>0.258).
Python check
A = [(0,1), (0,1), (0,1), (6,3)]; B = [(0,2), (6,4)]for kids in (A, B): g = gain(H, (6, 6), kids); s = split_info(*[sum(k) for k in kids]) print(round(g, 4), round(s, 4), round(g / s, 4)) # A: .3113 1.2075 .2578 B: .1909 .65 .2936
Key lesson
IG wants the biggest absolute purity gain; GR wants gain per unit of fragmentation.
Common mistakes
Dividing by E(X) (class entropy) instead of SplitInfo.
Using GR when SplitInfo =0.
Exam traps
GR fixes, but does not eliminate, the many-valued bias.
C4.5 uses GR; ID3 uses IG; CART uses Gini.
Connections: C4, C9.
Mastery checklist
Compute SplitInfo and GR.
Explain the ID-column pathology.
Give a case where IG and GR disagree.
C7. Stopping Criteria and Overfitting
Intuition
A tree can keep splitting until every training example sits in its own leaf — perfect on training data, hopeless on new data (it memorised noise). Stopping early (pre-pruning) trades some training accuracy for generalisation. Stop too early and you underfit.
Stopping criteria: (i) maximum depth reached; (ii) all samples in the node share a class; (iii) best split score does not exceed a threshold (or too few samples).
Overfitting (Mitchell): hypothesis h∈H overfits training data if there exists h′∈H with errtrain(h)<errtrain(h′) but errD(h)>errD(h′) (D = true distribution).
Pre-pruning: stop growing early. Post-pruning: grow fully, then cut (C8).
Mathematical formulation
Generalisation gap: errD(h)−errtrain(h). Overfit ⇔ gap grows while training error shrinks.
Derivation: noise makes memorisation costly
Suppose true labels are deterministic given x but each observed label is flipped independently with probability η. A fully grown tree puts a test point in a leaf labelled by a (noisy) training point from the same region. Error =P(train wrong)P(test right)+P(train right)P(test wrong)=η(1−η)+(1−η)η=2η(1−η), whereas a tree that learns the true label has error η (the unavoidable noise). Since 2η(1−η)>η⟺η<21, memorisation is strictly worse.
Key insights
Tight stopping ⇒ small trees ⇒ underfit; loose ⇒ big trees ⇒ overfit.
Choose depth by validation error.
Worked examples
Example 1 — Very Easy · Stop or split?
Problem: Which stops a decision tree: (a) node has only Yes’s; (b) node has 5 Yes and 5 No and a feature exists; (c) max depth reached?
Asked: Stop or continue.
Concept: Stopping criteria.
Approach: Check each criterion.
Solution: (a) pure → stop. (b) impure and a split exists → continue (if no criterion fires). (c) depth limit → stop.
Final answer: (a) stop, (b) continue, (c) stop.
Key lesson
Pure node ⇒ leaf.
Example 2 — Easy · Choosing the depth
Problem: Depth vs (train error, validation error): d=1: (0.30, 0.32); 2: (0.20, 0.22); 3: (0.10, 0.15); 4: (0.05, 0.18); 5: (0.00, 0.25). Choose d and identify under / overfitting.
Asked: Best depth.
Concept: Validation-based depth selection.
Approach: Minimise validation error.
Solution: Validation errors 0.32,0.22,0.15,0.18,0.25; minimum 0.15 at d=3. d=1,2: both errors high → underfit. d=4,5: train falls, validation rises → overfit.
Final answer:d=3.
Key lesson
Training error alone always prefers the deepest tree.
Example 3 — Moderate · A weak split below threshold
Problem: A node’s best split has IG=0.004; threshold θ=0.01. The node has 40 samples (22 Yes, 18 No). What does the tree do, and what is the leaf’s label and training error?
Final answer: Leaf “Yes”, training error 0.45 at this node.
Key lesson
Thresholding saves tree size at the cost of local accuracy.
Example 4 — Hard · Does the big tree overfit?
Problem: 10 training points; a hypothesis h1 (large tree) has training error 0 and true error 0.30. h2 (small tree) has training error 0.20 and true error 0.12. Does h1 overfit? Which would you deploy?
Asked: Overfit judgement.
Concept: Mitchell’s definition.
Approach: Test the definition with h=h1, h′=h2.
Solution:errtrain(h1)=0<0.20=errtrain(h2) ✓; errD(h1)=0.30>0.12=errD(h2) ✓. Both conditions hold ⇒ h1 overfits. Deploy h2.
Final answer: Yes, h1 overfits; deploy h2.
Key lesson
Overfitting is relative: it needs a better-generalising alternative in H.
Example 5 — Very Hard · Noisy labels
Problem: A survey form is mis-transcribed so labels are flipped with noise η=0.10. (a) What error does a fully grown tree achieve on new data (idealised leaf model)? (b) What error does the ideal pruned tree achieve? (c) For what η is the full tree’s error 1.5× the pruned tree’s?
Grow a big tree, then cut off branches that don’t earn their keep. Three ways to decide “earns its keep”.
flowchart LR
A[Grow full tree] --> B{Pruning rule}
B -->|held-out set| REP[REP<br/>prune if accuracy does not drop]
B -->|size vs error| CCP["CCP<br/>prune if α < θ"]
B -->|pessimistic bound| EBP[EBP<br/>keep · leaf · maxchild]
Formal definitions
Notation: ε(T,X) error rate of tree T on X; ∣leaves(T)∣; pruned(T,t) = T with subtree at t replaced by a leaf (majority class).
Reduced-Error Pruning (REP, Quinlan 1987). Hold out a pruning (validation) set. Bottom-up, replace node t by its majority-class leaf if accuracy on the pruning set does not decrease. Stop when any further pruning would decrease accuracy.
Cost-Complexity Pruning (CCP, Breiman; CART). For each internal node t:
α(t)=∣leaves(T)∣−∣leaves(pruned(T,t))∣ε(pruned(T,t),X)−ε(T,X).
Prune if α<θ (preset θ>0). α = error increase per leaf removed.
Error-Based Pruning (EBP; C4.5). Replace the training error by an upper confidence bound:
ε′(T,X)=ε(T,X)+Zα∣X∣ε(T,X)(1−ε(T,X)).
Bottom-up at node t, compare ε′ of: (i) subtree(T,t) on Xt; (ii) pruned(T,t) on Xt; (iii) subtree(T,maxchild(T,t)) on Xmaxchild. Take the minimum: keep, prune to leaf, or replace t by its most-travelled child subtree.
Derivation: where EBP’s formula comes from
ε^ from N samples is approximately normal with mean ε and standard error ε(1−ε)/N (binomial). The one-sided (1−α) upper bound is mean +z⋅ s.e. A tiny node has a large s.e., so its estimated error is inflated: small nodes are distrusted. For α=0.05 (one-sided), Zα=1.645.
Key insights
REP needs held-out data (or cross-validation).
CCP’s α makes a size-versus-error trade-off explicit: small α ⇒ branch barely helps ⇒ prune.
EBP needs no separate pruning set.
Worked examples
Example 1 — Very Easy · REP on one node
Problem (REP): At node t, the pruning set has 20 samples reaching t; the subtree misclassifies 5 and the majority leaf misclassifies 5. Prune?
Asked: Decision.
Concept: REP rule “does not reduce accuracy”.
Approach: Compare errors.
Solution: Accuracy with subtree =15/20; with leaf =15/20. Not reduced → prune.
Final answer: Prune.
Key lesson
Ties prune (simpler wins).
Example 2 — Easy · One CCP decision
Problem (CCP): Subtree at t has 4 leaves. ε(T)=0.05, ε(pruned(T,t))=0.08. Threshold θ=0.02. Prune?
Asked:α and decision.
Concept:α formula.
Approach: Leaves removed =4−1=3.
Solution:α=30.08−0.05=0.01. 0.01<0.02 → prune.
Final answer:α=0.01, prune.
Key lesson
The denominator is leaves removed (3), not 4.
Example 3 — Moderate · Pessimistic error
Problem (EBP): A node has ∣Xt∣=100, training error ε=0.10. With Z=1.645 find ε′.
Problem (CCP ordering): Tree T: ε(T)=0.04, 9 leaves. Candidate nodes: t1: subtree has 3 leaves, pruning gives error 0.07; t2: 2 leaves, pruning gives 0.05; t3: 4 leaves, pruning gives 0.10. Compute each α and the pruning order; with θ=0.015 which are pruned (considered independently)?
Asked:α‘s, order, set.
Concept: Weakest-link idea.
Approach:α=Δε/Δleaves.
Solution:t1: (0.07−0.04)/(3−1)=0.015. t2: (0.05−0.04)/(2−1)=0.010. t3: (0.10−0.04)/(4−1)=0.020. Order (smallest first): t2<t1<t3. With rule "α<θ" and θ=0.015: t2 pruned; t1 (0.015, not strictly less) kept; t3 kept.
Final answer:α=(0.015,0.010,0.020); only t2 is pruned.
Key lesson
Strict inequality matters at the boundary. In a full CCP sequence, α must be recomputed after each prune.
Example 5 — Very Hard · EBP three-way choice
Problem (EBP three-way): Node t has ∣Xt∣=100. subtree(T,t) has ε=0.06 on Xt. pruned(T,t) (leaf) has ε=0.06 on Xt. maxchild receives 40 of the 100 samples; its subtree has ε=0.025 on those 40. With Z=1.645 choose the action.
Asked: Keep / prune / replace by maxchild.
Concept: EBP comparison.
Approach: Compute three ε′.
Solution: (i) 0.06⋅0.94/100=0.02375; ε′=0.06+1.645(0.02375)=0.0991. (ii) leaf: same ε and n → 0.0991. (iii) 0.025⋅0.975/40=0.02469; ε′=0.025+1.645(0.02469)=0.0656. Minimum is (iii).
Final answer: Replace t by its maxchild subtree.
Python check
ebp = lambda e, n, z=1.645: e + z * sqrt(e * (1 - e) / n)print(ebp(.06, 100), ebp(.06, 100), ebp(.025, 40)) # 0.0991 0.0991 0.0656
Key lesson
EBP is a three-way decision; option (iii) can win because a narrower subtree has lower observed error, even though its bound uses a smaller n.
Common mistakes
Using the number of leaves in T (not the number removed) in α.
Pruning using the training set in REP.
Treating ε′ as a probability estimate rather than an upper bound.
C9. ID3, C4.5, CART; Merits and Limits of Decision Trees
Intuition
All three algorithms grow a tree greedily top-down: choose the best split, recurse, never backtrack. They differ in score, branching, numeric / missing support and pruning.
Comparison
ID3 (Quinlan 1986)
C4.5 (Quinlan 1993)
CART (Breiman 1984)
Split score
Information gain
Gain ratio
Gini index
Branching
Multiway on categorical
Multiway
Binary
Stopping
all one class, or best IG ≤0
too few samples to split
—
Pruning
none
error-based pruning
cost-complexity pruning
Numeric / missing
No
Yes
Yes
Regression
No
No
Yes
Merits (lecture)
Handles nominal and numeric features; non-parametric (no distribution assumption); can handle missing values; interpretable — a tree is a rule set.
Limits (lecture)
Optimal tree learning is NP-hard / NP-complete → greedy heuristics; sensitive to training set, noise, irrelevant features; ID3 needs discrete targets.
The tree for the weather data (IG-based, Figure 3.5)
Figure 3.3 in the lecture is a larger tree that tests Temperature under Sunny and Rainy and has “No Instance” leaves — it was built without choosing by information gain. Figure 3.5 is the compact IG-based tree below. The lecture’s point: IG yields a smaller and shallower tree for the same data.
flowchart TD
O{Outlook}
O -->|Sunny| H{Humidity}
O -->|Overcast| Y1([Yes])
O -->|Rainy| W{Wind}
H -->|High| N1([No])
H -->|Normal| Y2([Yes])
W -->|True| N2([No])
W -->|False| Y3([Yes])
Derivation: tree ⇒ rules
Each root-to-leaf path is a conjunction of conditions; the leaf gives the class. The IG-based weather tree yields five rules:
Outlook=Sunny ∧ Humidity=High → No
Outlook=Sunny ∧ Humidity=Normal → Yes
Outlook=Overcast → Yes
Outlook=Rainy ∧ Wind=True → No
Outlook=Rainy ∧ Wind=False → Yes
Worked examples
Example 1 — Very Easy · Match algorithm to score
Problem: Which algorithm uses Gini? Gain ratio? Information gain?
Example 2 — Easy · Classify a day and check training accuracy
Problem: Classify the day (Sunny, Cool, High, True) with the weather tree and compute the tree’s training accuracy.
Asked: Prediction and accuracy.
Concept: Tree traversal.
Approach: Follow the rules.
Solution: Outlook=Sunny → test Humidity=High → rule 1 → No. Training check: Sunny / High rows 1,2,8 → all N ✓; Sunny / Normal rows 9,11 → Y,Y ✓; Overcast rows 3,7,12,13 → all Y ✓; Rainy / Wind=T rows 6,14 → N,N ✓; Rainy / Wind=F rows 4,5,10 → Y,Y,Y ✓. All 14/14.
Final answer: No; training accuracy 100%.
Key lesson
Fully grown trees fit consistent training data exactly.
Example 3 — Moderate · Pick the right tool
Problem: Choose the algorithm: (a) numeric features with missing values, categorical target; (b) predicting a numeric target (e.g. house price) with binary splits; (c) a small, purely categorical dataset with no missing values where simplicity is desired.
Problem: Compare the root choice of ID3 (IG) and CART (binary Gini) for the weather data and count the children each produces at the root split.
Asked: Root splits.
Concept: Split criteria and branching.
Approach: From C4 and C5: IG picks Outlook (0.247); CART’s best binary Gini split is “Outlook = Overcast?” (gain 0.102, from C5 Ex. 4). Check the binary Humidity split: High=(3Y,4N), Normal=(6Y,1N): GH=0.4898, GN=0.2449; weighted 0.3673; gain 0.0918<0.102.
Solution: ID3: 3 children (S, O, R). CART: 2 children (Overcast, not Overcast); the latter (5Y,5N) is then split further.
Final answer: Same feature, different branching: ID3 3-way; CART 2-way.
Branching factor changes tree shape, not necessarily the feature chosen.
Example 5 — Very Hard · The XOR trap
Problem: Eight points (x1,x2,x3∣y) with y=x1⊕x2 and x3 irrelevant: (0,0,0∣0),(0,0,1∣0),(0,1,0∣1),(0,1,1∣1),(1,0,0∣1),(1,0,1∣1),(1,1,0∣0),(1,1,1∣0). Run ID3. What happens, and what is the best tree?
Asked: ID3’s tree vs optimal.
Concept: Greedy one-step look-ahead fails on XOR.
Approach: Compute IG of all features at the root.
Solution: Class counts: 4 Yes(1), 4 No(0) → E=1. x1:x1=0 rows have y=0,0,1,1 → E=1; x1=1 rows y=1,1,0,0 → E=1. Weighted =1, IG=0. x2: same, IG=0. x3: both children y=0,1,1,0 → E=1; IG=0. All gains are 0: ID3’s stopping rule (“best IG not greater than zero”) fires → a single leaf, accuracy 50%. Optimal: split x1 then x2 → 4 leaves, accuracy 100%.
x1 = 0 x1 = 1
x2=0: 0 1
x2=1: 1 0 ← y = XOR; no single feature separates classes
Final answer: ID3 returns a one-leaf tree (50 %); the depth-2 tree on x1,x2 is perfect.
Python check
rows = [(0,0,0,0),(0,0,1,0),(0,1,0,1),(0,1,1,1),(1,0,0,1),(1,0,1,1),(1,1,0,0),(1,1,1,0)]for j in range(3): kids = [(sum(r[3] for r in rows if r[j] == v), sum(1 - r[3] for r in rows if r[j] == v)) for v in (0, 1)] print(f"x{j+1}", gain(H, (4, 4), kids)) # 0.0 for every feature
Key lesson
Greedy splitting cannot see interactions: a feature useless alone may be essential in combination. Random forests and deeper lookahead only partly help.
Common mistakes
Saying C4.5 uses Gini or ID3 uses gain ratio.
Believing greedy trees are optimal.
Exam traps
ID3: no pruning, no numeric, no missing values.
CART is binary; Gini is its splitting measure (the lecture’s “Gini index is used to prune” is a slip: CART prunes by cost-complexity).
Connections: C4–C8, C10.
Mastery checklist
Fill the comparison table from memory.
Convert a tree to rules.
Give the XOR failure example.
C10. Random Forest
Intuition
One tree is unstable: change a few training rows and the tree changes a lot (high variance). Average many different trees and the instabilities cancel — like asking a panel of doctors instead of one. To make the trees different, each sees a bootstrap resample of rows and, at each split, only a random subset of features.
flowchart LR
X[(Training set X)] --> B1[Bootstrap 1] --> T1[Tree 1]
X --> B2[Bootstrap 2] --> T2[Tree 2]
X --> B3[Bootstrap B] --> T3[Tree B]
T1 --> V{{Majority vote}}
T2 --> V
T3 --> V
V --> P[Prediction]
Formal algorithm (lecture)
For b=1,…,B:
Draw a bootstrap sample Zb of size Zwith replacement from the training set X.
Grow a tree on Zb: at each node pick V (=m) features at random from all features F; choose the best split among those by a criterion (e.g. Gini); split.
Predict a test sample by majority vote of the B trees.
Default m=∣F∣. Out-of-bag (OOB) samples = those not drawn for a tree; the error on them is the OOB error, a built-in generalisation estimate.
Mathematical formulation
Probability a given row is not in a bootstrap sample of size n: (1−n1)nn→∞e−1≈0.368.
Variance of the average of B identically distributed trees with pairwise correlation ρ and variance σ2:
Var(B1∑bTb)=ρσ2+B1−ρσ2.
Derivation of the variance formula
Var(B1∑Tb)=B21[∑bVar(Tb)+∑b=b′Cov(Tb,Tb′)]=B21[Bσ2+B(B−1)ρσ2]=Bσ2+B(B−1)ρσ2=ρσ2+B(1−ρ)σ2. ∎
(Standard result, not stated in the lecture; it explains why decorrelating trees via feature subsampling helps.)
Key insights
More trees never overfit more, but the variance floor is ρσ2.
Feature subsampling lowers ρ.
Cost: interpretability is lost compared with one tree.
Worked examples
Example 1 — Very Easy · Features per split
Problem: A dataset has 16 features. What is the default number of features tried per split?
Asked:m.
Concept:m=∣F∣.
Approach: Square root.
Solution:16=4.
Final answer: 4.
Key lesson
The subset size is a fixed small number, not a fraction of the data.
Example 2 — Easy · A vote
Problem: Five trees vote for a test sample: Yes, No, Yes, Yes, No. Output?
Asked: Majority class.
Concept: Majority voting.
Approach: Count.
Solution: Yes: 3, No: 2.
Final answer: Yes.
Key lesson
Use an odd B for two classes to avoid ties.
Example 3 — Moderate · How much is out-of-bag?
Problem: With n=10 rows, find the probability a given row is out-of-bag for one tree, the expected number of distinct rows in one bootstrap sample, and the limit as n→∞.
import numpy as npprint(0.9**10, 10 * (1 - 0.9**10), np.exp(-1)) # 0.3487 6.513 0.3679rng = np.random.default_rng(0)print(np.mean([len(set(rng.integers(0, 10, 10))) for _ in range(20000)])) # ≈ 6.51
Key lesson
About one third of the data is free validation data for each tree.
Example 4 — Hard · A panel of 60 %-accurate doctors
Problem: Each of B independent diagnostic trees is correct with probability 0.6. Find the probability that a majority vote is correct for B=1,3,5.
Asked: Three probabilities.
Concept: Why ensembles help (independence idealisation).
Approach: Binomial tail.
Solution:B=1: 0.6. B=3: need ≥2: 3(0.36)(0.4)+0.216=0.648. B=5: need ≥3: 10(0.216)(0.16)+5(0.1296)(0.4)+0.07776=0.3456+0.2592+0.07776=0.6826.
Final answer:0.600,0.648,0.683.
Python check
maj = lambda B, p=.6: sum(comb(B, k) * p**k * (1-p)**(B-k) for k in range(B//2 + 1, B + 1))print([round(maj(B), 4) for B in (1, 3, 5, 25, 101)]) # 0.6 0.648 0.6826 0.8462 0.9791
Key lesson
Voting improves accuracy — if errors are (nearly) independent, which is what feature subsampling tries to achieve.
Example 5 — Very Hard · Correlation sets the floor
Problem: Each tree has variance σ2=4. Compute the variance of the forest average for (ρ=0.5, B=10), (ρ=0.5, B→∞), and (ρ=0.1, B=10). What does it say about feature subsampling?
Asked: Three variances.
Concept: Variance of correlated averages.
Approach: Use the derived formula.
Solution: (i) 0.5(4)+100.5(4)=2.2. (ii) B→∞: 2. (iii) 0.1(4)+100.9(4)=0.76.
Final answer:2.2,2.0,0.76.
ρ
B
Var
0.5
10
2.2
0.5
∞
2.0 (floor)
0.1
10
0.76
Key lesson
Adding trees only shrinks the B1−ρ term; reducing ρ lowers the floor — the reason random forests restrict features at each split.
Common mistakes
Using the same bootstrap sample for every tree.
Sampling without replacement.
Believing forests are interpretable like a single tree.
Exam traps
OOB samples are the ones left out; OOB error needs no separate validation set.
The feature subset is redrawn at every node, not per tree.
Connections: Trees (C4–C9), bias–variance, bagging, cross-validation (C13).