Module 1 — Decision Trees and Random Forests

Source: Lec 3–4 — Decision Tree and Random Forest Classifiers. · Prev: 01_Foundations · Next: Module 2 — Evaluation · Index: 00_INDEX_and_Coverage

The running dataset — "Should the club hold practice today?"

Quinlan’s weather data, 14 days. Features: Outlook (Sunny, Overcast, Rainy), Temperature , Humidity , Wind (False / True). Class Play — 9 Yes, 5 No.

#OutTempHumWindPlay#OutTempHumWindPlay
1SHHFN8SMHFN
2SHHTN9SCNFY
3OHHFY10RMNFY
4RMHFY11SMNTY
5RCNFY12OMHTY
6RCNTN13OHNFY
7OCNTY14RMHTN

Errata in the source

The lecture prints "" — a typo. Correct: . The “gain ratio” denominator written is the split information (C6). Both are corrected below.


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.

 E(p)
 1.0 |            ****
     |         ***    ***
 0.5 |      ***          ***
     |    **                **
 0.0 +---*--------------------*--→ p (share of Yes)
     0          0.5           1

Formal definition

For a set with classes and class proportions : Information gain of feature :

Mathematical formulation / properties

  • iff all members are in one class.
  • Two classes: iff ; .
  • classes: , with equality on the right iff all .
  • Interpretation: minimum average number of bits to encode the class of a random member.

Derivation (maximum at the uniform distribution, two classes)

. Differentiate: ; for and for → maximum, . ∎

Why : 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 .
  • 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 for a batch of 8 parts: (a) 8 pass and 0 fail; (b) 4 pass and 4 fail; (c) 1 pass and 3 fail.
  • Asked: Three entropies.
  • Concept: Entropy definition.
  • Approach: Insert proportions.
  • Solution: (a) : . (b) : . (c) : .
  • Final answer: bits.

Key lesson

Purer ⇒ smaller entropy. A batch where you can already guess the outcome carries no surprise.

Example 2 — Easy · Entropy of the weather data

  • Problem: Entropy of the weather data (9 Yes, 5 No).
  • Asked: .
  • Concept: Entropy.
  • Approach: , .
  • Solution: ; . .
  • Final answer: bits.

Key lesson

Nearly 1 because the classes are fairly balanced.

Example 3 — Moderate · Does wind matter?

  • Problem: Compute for the weather data.
  • Asked: .
  • Concept: Information gain.
  • Approach: Partition by Wind, compute child entropies, weight them.
  • Solution: Wind=F: rows 1,3,4,5,8,9,10,13 → 8 rows; Yes: 3,4,5,9,10,13 (6), No: 1,8 (2). . Wind=T: rows 2,6,7,11,12,14 → 6 rows; Yes: 7,11,12 (3), No: 2,6,14 (3). . Weighted: . .
  • Final answer: .

Key lesson

A tiny gain means the feature barely separates the classes.

Example 4 — Hard · The next split inside the Sunny branch

  • Problem: Within the Sunny branch (rows 1,2,8,9,11: 2 Yes, 3 No), choose the best next feature among Temperature, Humidity, Wind.
  • Asked: The IG of each and the winner.
  • Concept: Recursive greedy splitting.
  • Approach: Compute of the branch, then IG for each feature restricted to this subset.
  • Solution: .
    • Temperature: Hot = rows 1,2 (N,N) ; Mild = rows 8,11 (N,Y) ; Cool = row 9 (Y) . Weighted . .
    • Humidity: High = rows 1,2,8 (all N) ; Normal = rows 9,11 (all Y) . Weighted . .
    • Wind: F = rows 1,8,9 (N,N,Y) ; T = rows 2,11 (N,Y) . Weighted . .
  • Final answer: Split Sunny on Humidity (IG 0.971 — a perfect split).

Key lesson

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 (cold → hot) and whether the match was played: (too cold and too hot are both bad). Using binary splits ” vs ” at midpoints, find the best threshold by IG. Also state which thresholds need to be considered at all.
  • Asked: Best 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.
  • Solution: Parent: 3 Yes, 5 No: .
leftrightIG
1.5N3Y 4N0.092
2.5NN3Y 3N0.204
3.51Y 2N2Y 3N0.003
4.52Y 2N1Y 3N0.049
5.53Y 2N ()NNN ()0.348
6.53Y 3NNN0.204
7.53Y 4NN0.092

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: , .

Key lesson

For numeric features, scan label-boundary midpoints. The best cut need not be near the median.

Common mistakes

  • Using instead of (changes units, not the argmax, but changes numbers).
  • Forgetting the weights .
  • Computing IG over the whole data instead of the current node’s subset.

Exam traps

  • must be stated.
  • Entropy range 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 and by hand.
  • Prove the two-class maximum at .
  • 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 with proportions : For feature (weighted over its branches, as in the lecture): Choose the feature with the smallest , equivalently the largest gain.

Mathematical properties

  • iff pure. Maximum at uniform proportions (two classes: ).
  • Proof of max: minimise subject to → Lagrange: ⇒ all equal ⇒ .
  • 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. . ∎

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: of (9 Yes, 5 No).
  • Asked: .
  • Concept: Definition.
  • Approach: .
  • Solution: ; . Sum . .
  • Final answer: .

Key lesson

Max for two classes is .

Example 2 — Easy · Range of Gini

  • Problem: Gini of a pure node, a 50 / 50 node and a 4-class uniform node.
  • Asked: Three values.
  • Concept: Range of Gini.
  • Approach: Direct.
  • Solution: Pure: . 50 / 50: . Uniform 4 classes: .
  • Final answer: .

Key lesson

Max is , not .

Example 3 — Moderate · Gini gain of Wind

  • Problem: Gini gain of Wind on the weather data.
  • Asked: .
  • Concept: Weighted Gini.
  • Approach: Use the Wind partition from C4 Ex. 3: F=(6Y,2N), T=(3Y,3N).
  • Solution: . . Weighted: . Gain .
  • Final answer: .

Key lesson

Same ordering of magnitude as IG (0.048): the two criteria agree on “Wind is weak”.

Example 4 — Hard · CART’s binary grouping of Outlook

  • Problem: CART builds binary splits. For the categorical feature Outlook list the three binary splits ("" vs "") and pick the best by Gini gain.
  • Asked: Best binary split.
  • Concept: Binary CART split of a multi-valued feature.
  • Approach: Counts: Sunny (2Y,3N), Overcast (4Y,0N), Rainy (3Y,2N).
  • Solution:
    • Overcast vs rest: Overcast Gini ; rest (5Y,5N) . Weighted . Gain .
    • Sunny vs rest: Sunny ; rest (7Y,2N) . Weighted . Gain .
    • Rainy vs rest: Rainy ; rest (6Y,3N) . Weighted . Gain .
  • Final answer: “Overcast vs not Overcast” (gain 0.102).

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.
  • Asked: Two rankings.
  • Concept: Entropy vs Gini disagree.
  • Approach: Compute both criteria for both splits.
  • Solution: Parent: , .
    • Split A: child 1 pure (). Child 2: , , , . Weighted → . Weighted → .
    • Split B: child 1 , , , ; child 2 , , , . Weighted → . Weighted → .
    • Comparison: IG: → A. Gini: → B.
  • Final answer: Entropy prefers A; Gini prefers B.
IGGini gainWinner
Split A (tiny pure child)0.1480.077entropy
Split B (two moderately pure children)0.1250.083Gini

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 classes is , not .

Connections: Entropy (C4), CART (C9), random forests (C10); for 2 classes , 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

(The lecture writes the denominator as ; it is the entropy of the partition sizes.) Undefined when (feature has a single value).

Mathematical formulation

is the entropy of the feature’s own value distribution; for equal-size branches it is .

Derivation (why it penalises ID-like features)

For a feature with unique values in rows, (all children pure) but . So as grows.

Key insights

  • Used by C4.5.
  • It can over-correct (favours very unbalanced splits with tiny ).

Worked examples

Example 1 — Very Easy · How fragmented is the split?

  • Problem: of a binary split with sizes 7 and 7; of a 3-way equal split.
  • Asked: Two values.
  • Concept: SplitInfo.
  • Approach: Entropy of proportions.
  • Solution: : . Equal 3-way: .
  • Final answer: and .

Key lesson

More branches ⇒ larger SplitInfo.

Example 2 — Easy · Gain ratio of Outlook

  • Problem: of Outlook (IG ; branch sizes 5, 4, 5).
  • Asked: GR.
  • Concept: Gain ratio.
  • Approach: Compute SplitInfo then divide.
  • Solution: . .
  • Final answer: .

Key lesson

The division shrinks the gain by .

Example 3 — Moderate · Rank all four weather features

  • Problem: Compute GR for all four weather features and rank.
  • Asked: Four GRs.
  • Concept: Gain ratio.
  • Approach: IG and SplitInfo from branch sizes.
  • Solution:
Featurebranch sizesIGSplitInfoGR
Outlook5, 4, 50.24671.57740.156
Humidity7, 70.15181.00000.152
Wind8, 60.04810.98520.049
Temperature4, 6, 40.02921.55670.019
  • Final answer: Outlook > Humidity > Wind > Temperature .

Key lesson

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 → . . . Under IG, Day beats Outlook vs (ratio ). Under GR, Day beats Outlook vs (ratio ).
  • 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 .
    • A: three pure children (weight each); big child : , . Weighted ; . ; .
    • B: child 1 pure (); child 2 , . Weighted ; . ; .
  • Final answer: IG picks A (); GR picks B ().

Key lesson

IG wants the biggest absolute purity gain; GR wants gain per unit of fragmentation.

Common mistakes

  • Dividing by (class entropy) instead of SplitInfo.
  • Using GR when SplitInfo .

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.

 error
  |  \                         validation
  |   \                      /
  |    \          __________/      ← overfit zone: train ↓, validation ↑
  |     \________/
  |      train \________________
  +----------------------------→ tree depth
      underfit   sweet spot   overfit

Formal definitions

  • 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 overfits training data if there exists with but ( = true distribution).
  • Pre-pruning: stop growing early. Post-pruning: grow fully, then cut (C8).

Mathematical formulation

Generalisation gap: . Overfit ⇔ gap grows while training error shrinks.

Derivation: noise makes memorisation costly

Suppose true labels are deterministic given 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 , whereas a tree that learns the true label has error (the unavoidable noise). Since , 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): : (0.30, 0.32); : (0.20, 0.22); : (0.10, 0.15); : (0.05, 0.18); : (0.00, 0.25). Choose and identify under / overfitting.
  • Asked: Best depth.
  • Concept: Validation-based depth selection.
  • Approach: Minimise validation error.
  • Solution: Validation errors ; minimum at . : both errors high → underfit. : train falls, validation rises → overfit.
  • Final answer: .

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 ; threshold . The node has 40 samples (22 Yes, 18 No). What does the tree do, and what is the leaf’s label and training error?
  • Asked: Action, label, error.
  • Concept: Threshold stopping.
  • Approach: Compare IG to ; majority label.
  • Solution: → stop. Leaf label = majority = Yes. Errors of 40 → .
  • Final answer: Leaf “Yes”, training error 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 (large tree) has training error 0 and true error 0.30. (small tree) has training error 0.20 and true error 0.12. Does overfit? Which would you deploy?
  • Asked: Overfit judgement.
  • Concept: Mitchell’s definition.
  • Approach: Test the definition with , .
  • Solution: ✓; ✓. Both conditions hold ⇒ overfits. Deploy .
  • Final answer: Yes, overfits; deploy .

Key lesson

Overfitting is relative: it needs a better-generalising alternative in .

Example 5 — Very Hard · Noisy labels

  • Problem: A survey form is mis-transcribed so labels are flipped with noise . (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 the pruned tree’s?
  • Asked: Two errors and a ratio solve.
  • Concept: Noise and memorisation.
  • Approach: Use vs .
  • Solution: (a) . (b) . (c) .
  • Final answer: , , .

Key lesson

Memorisation costs extra error — largest near .

Common mistakes

  • Judging a tree by training accuracy.
  • Equating “large tree” with “overfit” without a comparison.

Exam traps

  • “Tight” stopping ⇒ underfit; “loose” ⇒ overfit.
  • The definition of overfit uses true distribution error.

Connections: Pruning (C8), cross-validation (C13), 1-NN error (C23).

Mastery checklist

  • List three stopping criteria.
  • State Mitchell’s overfit definition.
  • Derive .

C8. Post-Pruning: Reduced-Error, Cost-Complexity, Error-Based

Intuition

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: error rate of tree on ; ; = with subtree at replaced by a leaf (majority class).

  1. Reduced-Error Pruning (REP, Quinlan 1987). Hold out a pruning (validation) set. Bottom-up, replace node by its majority-class leaf if accuracy on the pruning set does not decrease. Stop when any further pruning would decrease accuracy.
  2. Cost-Complexity Pruning (CCP, Breiman; CART). For each internal node : Prune if (preset ). = error increase per leaf removed.
  3. Error-Based Pruning (EBP; C4.5). Replace the training error by an upper confidence bound: Bottom-up at node , compare of: (i) on ; (ii) on ; (iii) on . Take the minimum: keep, prune to leaf, or replace by its most-travelled child subtree.

Derivation: where EBP’s formula comes from

from samples is approximately normal with mean and standard error (binomial). The one-sided upper bound is mean s.e. A tiny node has a large s.e., so its estimated error is inflated: small nodes are distrusted. For (one-sided), .

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 , the pruning set has 20 samples reaching ; 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 ; with leaf . Not reduced → prune.
  • Final answer: Prune.

Key lesson

Ties prune (simpler wins).

Example 2 — Easy · One CCP decision

  • Problem (CCP): Subtree at has 4 leaves. , . Threshold . Prune?
  • Asked: and decision.
  • Concept: formula.
  • Approach: Leaves removed .
  • Solution: . → prune.
  • Final answer: , prune.

Key lesson

The denominator is leaves removed (3), not 4.

Example 3 — Moderate · Pessimistic error

  • Problem (EBP): A node has , training error . With find .
  • Asked: Upper bound.
  • Concept: EBP formula.
  • Approach: Substitute.
  • Solution: . .
  • Final answer: .

Key lesson

The pessimistic estimate exceeds the raw error.

Example 4 — Hard · Ordering nodes by α

  • Problem (CCP ordering): Tree : , 9 leaves. Candidate nodes: : subtree has 3 leaves, pruning gives error ; : 2 leaves, pruning gives ; : 4 leaves, pruning gives . Compute each and the pruning order; with which are pruned (considered independently)?
  • Asked: ‘s, order, set.
  • Concept: Weakest-link idea.
  • Approach: .
  • Solution: : . : . : . Order (smallest first): . With rule "" and : pruned; (, not strictly less) kept; kept.
  • Final answer: ; only 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 has . has on . (leaf) has on . receives 40 of the 100 samples; its subtree has on those 40. With choose the action.
  • Asked: Keep / prune / replace by maxchild.
  • Concept: EBP comparison.
  • Approach: Compute three .
  • Solution: (i) ; . (ii) leaf: same and → . (iii) ; . Minimum is (iii).
  • Final answer: Replace by its maxchild subtree.

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 .

Common mistakes

  • Using the number of leaves in (not the number removed) in .
  • Pruning using the training set in REP.
  • Treating as a probability estimate rather than an upper bound.

Exam traps

  • REP: “does not reduce accuracy” (ties prune).
  • CCP rule is prune if .
  • EBP compares three values.

Connections: Overfitting (C7), cross-validation (C13), CART / C4.5 (C9).

Mastery checklist

  • Apply each of the three pruning rules.
  • Derive the EBP bound.
  • Order nodes by .

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 scoreInformation gainGain ratioGini index
BranchingMultiway on categoricalMultiwayBinary
Stoppingall one class, or best IG too few samples to split—
Pruningnoneerror-based pruningcost-complexity pruning
Numeric / missingNoYesYes
RegressionNoNoYes

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:

  1. Outlook=Sunny ∧ Humidity=High → No
  2. Outlook=Sunny ∧ Humidity=Normal → Yes
  3. Outlook=Overcast → Yes
  4. Outlook=Rainy ∧ Wind=True → No
  5. Outlook=Rainy ∧ Wind=False → Yes

Worked examples

Example 1 — Very Easy · Match algorithm to score

  • Problem: Which algorithm uses Gini? Gain ratio? Information gain?
  • Asked: Match.
  • Concept: Comparison table.
  • Approach: Recall.
  • Solution: CART–Gini; C4.5–gain ratio; ID3–information gain.
  • Final answer: As stated.

Key lesson

Memorise the triple: ID3 – IG, C4.5 – GR, CART – Gini.

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 .
  • Final answer: No; training accuracy .

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.
  • Asked: Algorithm per scenario.
  • Concept: Capabilities.
  • Approach: Use the table.
  • Solution: (a) numeric + missing support → C4.5. (b) regression + binary → CART. (c) ID3 suffices.
  • Final answer: (a) C4.5, (b) CART, (c) ID3.

Key lesson

Match the algorithm to the data type.

Example 4 — Hard · Root splits: ID3 vs CART

  • 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): , ; weighted ; gain .
  • 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.

Key lesson

Branching factor changes tree shape, not necessarily the feature chosen.

Example 5 — Very Hard · The XOR trap

  • Problem: Eight points with and irrelevant: . 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) → . : rows have → ; rows → . Weighted , . : same, . : both children → ; . All gains are : ID3’s stopping rule (“best IG not greater than zero”) fires → a single leaf, accuracy . Optimal: split then → 4 leaves, accuracy .
        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 is perfect.

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 :

  1. Draw a bootstrap sample of size with replacement from the training set .
  2. Grow a tree on : at each node pick () features at random from all features ; choose the best split among those by a criterion (e.g. Gini); split.
  3. Predict a test sample by majority vote of the trees.

Default . 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 : .
  • Variance of the average of identically distributed trees with pairwise correlation and variance :

Derivation of the variance formula

. ∎ (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 .
  • 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: .
  • Concept: .
  • Approach: Square root.
  • Solution: .
  • 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 for two classes to avoid ties.

Example 3 — Moderate · How much is out-of-bag?

  • Problem: With 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 .
  • Asked: Three quantities.
  • Concept: Bootstrap sampling.
  • Approach: .
  • Solution: . Expected distinct . Limit .
  • Final answer: ; rows; .

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 independent diagnostic trees is correct with probability . Find the probability that a majority vote is correct for .
  • Asked: Three probabilities.
  • Concept: Why ensembles help (independence idealisation).
  • Approach: Binomial tail.
  • Solution: : . : need : . : need : .
  • Final answer: .

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 . Compute the variance of the forest average for (, ), (, ), and (, ). What does it say about feature subsampling?
  • Asked: Three variances.
  • Concept: Variance of correlated averages.
  • Approach: Use the derived formula.
  • Solution: (i) . (ii) : . (iii) .
  • Final answer: .
Var
0.5102.2
0.5∞2.0 (floor)
0.1100.76

Key lesson

Adding trees only shrinks the 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).

Mastery checklist

  • Write the algorithm.
  • Compute OOB fraction.
  • State the variance formula and its implication.