ECE571 / Week 6 · Decision trees and ensembles

Week 6 · Decision trees and ensembles

Decision trees, bagging and random forests

A decision tree classifies by asking one question at a time, choosing each question to make the groups as pure as possible. Single trees overfit and change wildly with the data, so we train hundreds of them on resampled data and let them vote: that's a random forest.

~40 min read 10 practice questions + 2 problems Reading: Géron Ch. 6 and 7 (to "Feature Importance"); Mitchell Ch. 3
The big picture

This lecture has two halves (two slide decks, 6a and 6b). The first half builds a decision tree: a flowchart of yes/no or multiple-choice questions about the features, ending in a class label. Trees are grown greedily: at each node, pick the feature whose split makes the child groups purest, measured by entropy (giving information gain) or Gini impurity, then recurse. Trees are easy to explain, which the professor calls their biggest strength, but they overfit easily and are high-variance: change one training example and you may get a completely different tree. The second half turns that weakness into a strength. Train many trees on bootstrap resamples of the data and let them vote (bagging); averaging cancels much of the variance. Add a random subset of features at each split and you have a random forest, one of the most reliable off-the-shelf classifiers.

After this you can
Section 1

What a decision tree is

Lecture 00:34–06:26, 13:08–17:06, 30:12–31:166a slides 2–4, 9, 22; 6b slide 2Géron Ch. 6, "Training and Visualizing a Decision Tree", "Making Predictions"

A decision tree classifies an example by walking it from the top of the tree to the bottom, answering one question at each step. The professor's everyday example (slide 3): "Work to do?" If yes, stay in. If no, look at the outlook, and so on.

YesNoSunnyOvercastRainyYesNoWork to do?Outlook?Friends busy?Stay inGo to beachGo runningStay inMovies← root← internal nodeshaded boxes areleaves (decisions)
A tree is a nested set of questions; each path from the root to a leaf is one decision rule. Redrawn from 6a slide 3. The root is the first question. Internal nodes each test one attribute. Each branch (edge) is one value of that attribute. Leaves have no children and hold the final decision.

The vocabulary from slide 4, using the PlayTennis example that runs through the deck:

  • An attribute (feature) is a question like Outlook. Its values are the possible answers: Sunny, Overcast, Rain. Each internal node tests one attribute and has one branch per value.
  • A leaf assigns a class (PlayTennis = Yes or No). "The nodes for decisions are always leaf nodes, because we never make another decision based on this one" (05:58).
  • To classify a new day, start at the root, follow the branch that matches its value, and repeat until you reach a leaf.

Trees are rules. Every root-to-leaf path is an AND of conditions, so a tree converts directly into a rule list (slide 22), e.g. "If Outlook = Sunny AND Humidity = High then No". The professor stresses that this is the main selling point: "if, let's say, for your applications the explanation is very important, then the first algorithm you should think about is the decision tree" (16:30). His example is a hospital's COVID triage flowchart: patients and doctors can see exactly why a decision was made. Géron calls this a white-box model, in contrast to black boxes like random forests and neural networks.

When trees fit well (slide 9, from Mitchell Ch. 3): examples are described by attribute–value pairs, the target is discrete (a class), the training data may be noisy or have missing values, and the target concept may need a disjunction (an OR of conditions).

Heads up: lecture 13:34 on "disjunctive hypothesis"

The lecture explains "disjunctive hypothesis may be required" as meaning the child subsets don't overlap. That's not what slide 9 (Mitchell) means. It means the concept you're learning may be an OR of ANDs: "play if (Sunny AND Normal humidity) OR Overcast OR (Rain AND Weak wind)". Each path is an AND; the whole tree is the OR of its Yes-paths. Trees represent such concepts naturally, while a single linear rule cannot. (The subsets are disjoint too, but that's a different fact.)

The second deck (6b slide 2) lists the trade-offs, which drive everything in the second half of the lecture:

ProsCons
Easy to interpret: a bunch of if–else rulesGenerally poor generalization: overfits easily
Handles mixed data (numerical and categorical) with no scalingHigh variance: a small change in the data gives a very different tree
Fast to predict: one comparison per levelUnlimited depth means VC dimension is infinite: a deep enough tree can fit any labeling of distinct points
Quick check: using the tree in the figure, what does a day with no work, Rainy outlook and busy friends lead to? Which nodes are internal?

Work to do? No → Outlook? Rainy → Friends busy? Yes → Stay in. The internal nodes below the root are "Outlook?" and "Friends busy?"; "Work to do?" is the root.

Section 2

Growing a tree greedily

Lecture 06:26–08:16, 17:06–17:366a slides 5, 10; 6b slides 3–6Géron Ch. 6, "The CART Training Algorithm"; Mitchell §3.4

Many trees fit the same training data perfectly (6b slide 3 shows a 3-leaf tree and a 6-leaf tree that both have zero training error). We'd like the smallest tree that fits, but finding it is computationally intractable: Géron notes that finding the optimal tree is NP-complete. So every practical algorithm builds the tree top-down and greedily:

  1. Pick the "best" attribute for the current node, the one whose split gives the purest children (the next two sections define "purest").
  2. Split. Make one child per value of and send each training example down the branch matching its value.
  3. Recurse on each child with only the examples that reached it.
  4. Stop (make a leaf) when all examples at the node have the same label, when no attributes are left (or all remaining examples have identical features), or when no examples reached the node. A leaf predicts the majority label of its examples (for an empty node, the parent's majority).

This template is ID3 (Quinlan, 1986) when "best" means largest information gain. "Most decision tree learning algorithms follow this template, but with different choices of heuristics" (6b slide 5). The professor says ID3 and C4.5 are the ones to remember (41:31). The differences:

AlgorithmSplit criterionSplitsNotes
ID3information gain (entropy)one branch per valuecategorical features; no pruning
C4.5gain ratio (gain normalized by how many ways the split divides the data)multiway; thresholds for numbersadds continuous features, missing values, post-pruning
CARTGini impurity (default) or entropyalways binary: ?what scikit-learn (and Géron) use; also does regression
Why "greedy" matters

Greedy means each split is chosen by looking only one level ahead. It never asks "would a worse split now lead to a much better tree two levels down?" That makes it fast, but there's no guarantee of the best tree (6b slide 7). Section 7 shows one case (XOR) where this short-sightedness bites.

Quick check: a node has 12 examples, all labeled No, but three attributes are still unused. What does ID3 do?

It stops and makes a leaf labeled No. All labels are the same, so no split could make the node purer.

Section 3

Measuring impurity: entropy, Gini and error

Lecture 09:48–13:08, 19:42–20:086a slides 7–8, 12–13Géron Ch. 6, Eq. 6-1 and 6-3, "Gini Impurity or Entropy?"; Mitchell §3.4.1

A node is pure if all its examples have the same class and impure if the classes are mixed. An impurity measure turns that into a number that is 0 for a pure node and largest for a 50/50 mix. Let be the fraction of the node's examples in class (the slides write for node ), with classes.

fraction of the node's examples that belong to class
taken as 0 (a class that's absent contributes nothing)
entropy in bits; 0 for a pure node, maximum when all classes are equally common (1 bit for two classes)
Gini impurity; 0 when pure, maximum (0.5 for two classes)
misclassification error: the fraction a majority-vote leaf gets wrong
0.5100.250.50.751p = fraction of class 1 in the nodeentropyentropy ÷ 2Ginierror
All three measures are 0 for a pure node and peak at a 50/50 mix. Two classes, plotted against , the fraction in class 1 (redrawn exactly from the formulas; compare 6a slide 8). Entropy ÷ 2 (dashed) and Gini are almost the same curve, which is why they usually pick the same splits. Misclassification error is a straight-sided tent.

What entropy means (slides 12–13). Entropy is the average number of bits needed to encode the class of a randomly drawn example using the best possible code. A message with probability gets a code of bits; averaging over classes gives . A pure node needs 0 bits (you already know the answer). A 50/50 node needs 1 bit. "If the distribution is flat, the entropy is maximized" (20:01): the flatter the class distribution, the more uncertain and the higher the entropy, for any number of classes.

Worked example: the PlayTennis root, [9+, 5−]

, .

Heads up: lecture 12:18, "you have to use 2 bits"

The lecture says a 50/50 two-class distribution needs 2 bits. It needs 1 bit: . One bit is exactly a fair coin flip (0 = class 1, 1 = class 2). Two bits would be needed for four equally likely classes ().

Heads up: lecture 11:56, "Gini is a lower bound of entropy"

True as stated, but it's a numerical fact, not the reason to use Gini: for every distribution, because . For two classes Gini even stays below entropy ÷ 2, the dashed curve on slide 8. What matters in practice is that they rank splits almost identically. Géron: "most of the time it does not make a big difference". Gini is slightly faster (no logarithm) and is scikit-learn's default; when they differ, Gini tends to isolate the most frequent class in its own branch and entropy gives slightly more balanced trees.

Why not use misclassification error to grow trees? Slide 8 says it's "less sensitive to changes in the class probabilities" and recommends it only for pruning. Here's a concrete case. A node has [4+, 4−]. Split A gives [3+, 1−] and [1+, 3−]. Split B gives [2+, 4−] and [2+, 0−]. Split B creates a pure node, so it's clearly more useful. But:

Decrease in…Split ASplit B
Misclassification error0.250.25 (tie)
Gini0.1250.167
Entropy (information gain)0.1890.311

Error can't tell them apart because it only counts majority mistakes. Entropy and Gini are curved (strictly concave), so they reward pushing a child toward purity.

Quick check: a node has three classes in proportions 1/2, 1/4, 1/4. Compute its entropy and Gini.

Section 4

Information gain: choosing the split

Lecture 08:16–09:48, 17:36–23:546a slides 6, 11, 14–15; 6b slide 6Géron Ch. 6, Eq. 6-2; Mitchell §3.4.1.2

To score a candidate split, compare the parent's impurity with the size-weighted average impurity of the children. The drop is the information gain (when the impurity is entropy):

,
the parent node's examples and how many there are
the feature (attribute) being tested; it has values
,
the examples sent to child and their count
an impurity measure: entropy (then this is information gain, ID3), or Gini (CART)

ID3 picks the feature with the largest gain. Since is the same for every candidate, that's the same as picking the split with the smallest weighted child impurity, which is how Géron writes CART's cost function (Eq. 6-2): minimize . 6b slide 6 writes the same formula as .

Split on A1[29+, 35−] H = 0.99G[21+, 5−]H = 0.71H[8+, 30−]H = 0.74gain = 0.27 Split on A2[29+, 35−] H = 0.99L[18+, 33−]H = 0.94M[11+, 2−]H = 0.62gain = 0.12
A1 wins: both of its children are much purer than the parent. Slides 11 and 14–15. Bars are drawn to scale; teal is positive, orange is negative. A2 leaves a big, still-mixed child (51 of the 64 examples, H = 0.94), so on average it barely reduces uncertainty.
Worked example (slides 14–15): A1 or A2?
  1. Parent [29+, 35−]:
  2. A1: children [21+, 5−] (H = 0.706) and [8+, 30−] (H = 0.742).
  3. A2: children [18+, 33−] (H = 0.937) and [11+, 2−] (H = 0.619).
  4. Choose A1 (0.27 > 0.12, matching the slide). With Gini instead the gains are 0.172 vs 0.079, the same choice.

The professor's reading of the gain: "if you maximize information gain, then from the same node the decision we make will be much easier" (22:11). The children should be closer to "one class has all the probability", where entropy is 0.

Heads up: slides 11 and 14 relabel A2's branches

Slide 11 labels A1's branches G/H and A2's L/M; slides 14–15 relabel them True/False. Same splits, same counts: nothing changes in the math.

Common mistake: forgetting the weights

The children's impurities are weighted by the fraction of examples each child gets, , not averaged equally. A tiny pure child shouldn't count as much as a huge mixed one. For A2, a plain average would give , badly overstating it.

Quick check: a split sends [6+, 2−] into [3+, 0−] and [3+, 2−]. What is the information gain?

Parent . Children: , . Gain:

Section 5

Worked example: ID3 on PlayTennis

Lecture 23:54–31:166a slides 16–22Mitchell §3.4.2 (the same example)

The classic 14-day dataset (slide 16, originally Mitchell Table 3.2). The task: predict PlayTennis from four attributes.

DayOutlookTemp.HumidityWindPlay
D1SunnyHotHighWeakNo
D2SunnyHotHighStrongNo
D3OvercastHotHighWeakYes
D4RainMildHighWeakYes
D5RainCoolNormalWeakYes
D6RainCoolNormalStrongNo
D7OvercastCoolNormalWeakYes
D8SunnyMildHighWeakNo
D9SunnyCoolNormalWeakYes
D10RainMildNormalStrongYes
D11SunnyMildNormalStrongYes
D12OvercastMildHighStrongYes
D13OvercastHotNormalWeakYes
D14RainMildHighStrongNo
Heads up: slide 16, D9's temperature

Slide 16 lists D9's temperature as "Cold". In Mitchell's original table it's Cool, and the slide's own result Gain(S, Temperature) = 0.029 (slide 19) only comes out with Cool. If "Cold" were a fourth value, the gain would be 0.064. The table above uses Cool. (Outlook still wins either way.)

Step 1: the root. The whole set is [9+, 5−] with . Score all four attributes:

AttributeChildren [yes+, no−] (entropy)GainGini decrease
OutlookSunny [2+, 3−] (0.971) · Overcast [4+, 0−] (0) · Rain [3+, 2−] (0.971)0.2470.116
HumidityHigh [3+, 4−] (0.985) · Normal [6+, 1−] (0.592)0.1520.092
WindWeak [6+, 2−] (0.811) · Strong [3+, 3−] (1.000)0.0480.031
TemperatureHot [2+, 2−] (1.000) · Mild [4+, 2−] (0.918) · Cool [3+, 1−] (0.811)0.0290.019

For example,

Outlook wins under both criteria. (Slide 17 prints 0.151 for Humidity because it uses rounded entropies; the exact value is 0.152.) Overcast is already pure [4+, 0−], so it becomes a Yes leaf.

Heads up: typos on slides 18 and 20

Slide 18 writes the Rain term as ; it should be (the slide's answer 0.247 uses the right value). Slide 20 writes the Sunny entropy as 0.970 (it's 0.971) and has a stray "=" in the Wind line, which should read:

Step 2: the Sunny branch, = {D1, D2, D8, D9, D11} = [2+, 3−], . Outlook is used up, so score the other three on just these five days:

AttributeChildrenGain
HumidityHigh [0+, 3−] · Normal [2+, 0−]0.971 (both children pure)
TemperatureHot [0+, 2−] · Mild [1+, 1−] · Cool [1+, 0−]
WindWeak [1+, 2−] · Strong [1+, 1−]

Step 3: the Rain branch (not shown on the slides), {D4, D5, D6, D10, D14} = [3+, 2−]: Wind gives Weak [3+, 0−] and Strong [0+, 2−], gain 0.971 − 0 = 0.971, since both children are pure. (Temperature and Humidity each give only 0.020.) The leaves are now all pure, so ID3 stops.

SunnyOvercastRainHighNormalStrongWeakOutlookHumidityWindNoD1, D2, D8YesD9, D11YesD3, D7, D12, D13NoD6, D14YesD4, D5, D10[9+, 5−] at the root · every leaf is pure
The finished ID3 tree uses only 3 of the 4 attributes and classifies all 14 days correctly. Slide 21. Temperature never appears: it was never the most informative question at any node. Green leaves predict Yes, red predict No; the days that reach each leaf are listed under it.

As rules (slide 22): R1 Sunny ∧ High → No; R2 Sunny ∧ Normal → Yes; R3 Overcast → Yes; R4 Rain ∧ Strong → No; R5 Rain ∧ Weak → Yes.

Cross-check with the textbook: gain favors many-valued attributes

Add the Day column (D1…D14) as an attribute. Every child holds one day, so every child is pure and , the maximum possible. ID3 would split on the date, a useless tree that memorizes the training set. Mitchell (§3.7.3) and C4.5 fix this with the gain ratio, which divides the gain by the entropy of the split proportions themselves, penalizing splits into many small pieces. CART avoids it differently: every split is binary.

Quick check: classify a new day: Rain, Hot, High humidity, Weak wind.

Outlook = Rain → Wind = Weak → Yes (rule R5). Temperature and humidity are never looked at.

Section 6

Continuous features and missing values

Lecture 40:02–41:266a slides 3, 6, 29–30Géron Ch. 6, "The CART Training Algorithm", "Instability"; Mitchell §3.7.2, §3.7.4

Continuous features are handled by thresholding: turn temperature into the yes/no question "temperature > ?" (slide 29). Which ? Sort the examples by the feature and only consider thresholds halfway between neighbors whose labels differ (Mitchell shows the best threshold is always at such a boundary). Then score each candidate by information gain like any other attribute.

1416182022242628t = 18.5gain 0.459t = 25.5gain 0.191YesNotemperature (°C)
Only label changes are candidate thresholds, and 18.5 °C wins. Slide 29's data. Labels change between 18 and 19 and between 24 and 27, so only and need checking.
Worked example: slide 29's threshold

Parent: [3 Yes, 3 No], .

: left {15, 18} = [0 Yes, 2 No] (H = 0), right {19, 22, 24, 27} = [3 Yes, 1 No] (H = 0.811). Gain .

: left [3 Yes, 2 No] (H = 0.971), right [0 Yes, 1 No]. Gain .

So the tree asks "temperature > 18.5?". The slide's "> 20.0" only illustrates the form of the question: as a split it would put 19 °C (a Yes) with the No days and score just 0.082.

The picture for two continuous features. Each split "" is a line perpendicular to one axis, so a tree carves the plane into axis-aligned rectangles, one per leaf. This is what CART does (always binary, one feature and one threshold per node), and the threshold search above happens at every node for every feature.

x₁ →x₂ yesnoyesnoyesnoyesnox₁ ≤ 6.25x₁ ≤ 3.25x₂ ≤ 6.25x₂ ≤ 4.755 leaves = 5 rectangles
A tree is a recursive partition: each leaf is a rectangle, and each split cuts one rectangle in two along an axis. 20 points, grown with scikit-learn (entropy, no depth limit). The root cuts at ; the left half is cut at , and so on. Shading shows each region's predicted class.
Cross-check with the textbook: trees love axis-parallel boundaries

Géron ("Instability") points out that because every cut is perpendicular to an axis, a diagonal boundary needs a staircase of many small cuts. Rotate a cleanly separable dataset by 45° and the tree becomes needlessly complicated and generalizes worse. Trees also need no feature scaling: a threshold doesn't care about units.

Missing values (slide 30). If an example lacks the value of attribute at a node that tests , the options are: fill in the most common value of among the examples at that node; or the most common value among examples with the same label; or, as in C4.5, split the example into fractions sent down every branch in proportion to how common each value is (e.g. 0.6 of it down High, 0.4 down Normal), and classify new examples the same way. The professor's summary: "You need to make an estimation… it's not accurate, but it's probably better than nothing" (40:28).

Quick check: sorted values 1, 2, 4, 7, 8 with labels A, A, B, B, A. Which thresholds are candidates?

Labels change between 2 and 4 and between 7 and 8, so the candidates are 3 and 7.5.

Section 7

Overfitting, Occam's razor and pruning

Lecture 31:16–40:026a slides 23–28; 6b slides 4, 7Géron Ch. 6, "Regularization Hyperparameters"; Mitchell §3.6, §3.7.1

Occam's razor (slide 23): "If two theories explain the facts equally well, the simpler one is preferred." The argument for it: there are far fewer short hypotheses than long ones, so a short tree that fits the data is unlikely to do so by coincidence, while a long one easily can. The professor ties this to week 5: among the many separating lines, the SVM picks the one with smallest , a "smaller" model, and that's the idea behind regularization in general. "When you have some models that can work equally well, then you should pick the model with minimal size" (34:19). (Slide 23 also notes the counterargument: there are many ways to define "small", so "simple" isn't uniquely defined.)

Overfitting is "one of the biggest problems with decision trees" (slide 24). A tree can keep splitting until every leaf is pure, fitting the training set perfectly including its noise. 6b slide 4 phrases the cure as regularization: minimize training error subject to "size of tree ≤ C". Solving that exactly is intractable, so in practice we use the heuristics below.

0.70.80.91.0051015202530tree size (number of leaves)best: 4 leavestrainingtest
Training accuracy keeps rising as the tree grows; test accuracy peaks early and then falls. Our own run of the experiment on slide 24 (noisy two-moons data, 150 training points, 4000 test points, scikit-learn trees capped at leaves). The fully grown tree (28 leaves) is perfect on training data but scores 0.762 on test data, versus 0.849 for 4 leaves.

Two ways to keep a tree small (slides 25–26):

  • Pre-pruning (stop early): don't split a node when the split isn't statistically significant or the node is too small. The professor's example: a node with 100 positives and 1 negative is good enough as a leaf (35:56). In scikit-learn this is max_depth, min_samples_split, min_samples_leaf, max_leaf_nodes.
  • Post-pruning (grow, then cut back): grow the full tree, then replace subtrees by leaves when that doesn't hurt. Subtree replacement (slide 27) swaps an entire subtree for a single leaf predicting the majority class of the examples that reached it. Reduced-error pruning (Mitchell) prunes a node whenever doing so does not lower accuracy on a separate validation set.
ABC45123before: full tree AB645after: subtree → leaf 6
Subtree replacement: the whole subtree under C collapses into one leaf. Redrawn from 6a slide 27. Leaf 6 predicts the majority label of every training example that used to reach leaves 1, 2 and 3.
Why pre-pruning can stop too early (slide 26)

"Sometimes features individually do not contribute much to a decision, but combined, they may have a significant impact." Example: XOR. Points (0,0) and (1,1) are −, (0,1) and (1,0) are +. Splitting on gives [1+, 1−] and [1+, 1−]: gain exactly 0, and the same for . A pre-pruning rule like "stop if the gain is tiny" quits at the root, yet two levels of splits classify everything perfectly. Post-pruning sees the full tree first, so it doesn't have this blind spot.

Picking the best tree (slide 25): measure accuracy on a separate validation set (or by cross-validation, as in week 2) for different sizes and keep the best; or minimize size(tree) + misclassifications(tree), which charges for size like a regularization term (this is Mitchell's minimum description length idea).

Heads up: lecture 39:08, reading slide 28

Slide 28 (Mitchell Fig. 3.7) adds a dotted curve: test accuracy while pruning. Pruning shrinks the tree, so that curve is read from right to left: starting from the big tree on the right, accuracy climbs as nodes are removed. It shows pruning works, recovering most of the test accuracy lost to overfitting. The lecture describes the curve as still overfitting with tree size and concludes that the best fix is more data. More data does help too, but that isn't what the plot shows.

Quick check: in the figure above, which tree would 5-fold cross-validation most likely pick, and why not the 28-leaf tree?

One near the test-accuracy peak, around 4–8 leaves. The 28-leaf tree has the best training accuracy (1.0), but cross-validation scores each size on held-out folds, where the big tree's memorized noise hurts it.

Section 8

Trees are high-variance

Lecture 42:50–44:08, 51:16–56:446b slides 2, 7–10, 17Géron Ch. 6, "Instability"

The professor skips the review slides at the start of deck 6b and goes straight to this point: "Remember, decision trees have high variance" (43:44). High variance means a small change in the training data gives a very different learned model. Slides 8–9 change a single label in a 16-row commuting table (Metro → Drive) and the learned tree changes completely: a different root attribute and a different shape.

x₁ →x₂ x₁ →x₂
Flip one label and the tree is rebuilt from the root down. Left: the tree from Section 6. Right: the same 20 points, but the circled point at (1, 3.5) is relabeled from square to circle. The new root splits on instead of , and the upper-left region is cut differently. One point out of 20 changed one region's shape and the whole tree's structure.

Why so unstable? Each split is a hard, greedy choice. If two attributes have nearly equal gain, a tiny change can swap which one wins, and everything below that node is then grown on different subsets of data. Errors at the top cascade down.

Bias and variance, done carefully. At 52:04 the professor switches to Wikipedia's dartboard figure. Imagine retraining the model on many different training sets drawn from the same source, and look at its prediction for one test point each time:

  • Bias is how far the average prediction is from the truth: a systematic error that more data of the same kind doesn't fix. Simple models (a depth-1 "stump", a line) have high bias.
  • Variance is how much the predictions spread from one training set to another. Flexible models (fully grown trees) have high variance.
Low bias, low var Low bias, high var High bias, low var High bias, high var
Bias is where the cloud is centered; variance is how spread out it is. Each teal dot is the prediction of a model trained on a different training set; the orange center is the truth. A fully grown tree is the second panel: right on average, but scattered.
Heads up: lecture 52:32–56:17

The spoken explanation of the dartboards is muddled. It describes bias as "what type of data each model can recognize" and high bias as models that all "have very good, similar performance". Use the definitions above: bias = average prediction minus truth, variance = spread across training sets. For squared error, expected test error = bias² + variance + irreducible noise (this was week 2's decomposition).

6b slide 17 puts the two extremes side by side: a fully grown tree is low-bias and high-variance; a decision stump (one split) is high-bias and low-variance. The next sections exploit the first: a high-variance, low-bias model is exactly what averaging can fix.

Quick check: you retrain a depth-1 stump on 100 different samples of the data and it always picks the same split. High or low variance? Could it still have high error?

Low variance (it barely changes). Yes, its error can still be high, if one split can't represent the true boundary: that's high bias.

Section 9

Ensembles and aggregation

Lecture 44:08–51:166b slides 11–17Géron Ch. 7, "Voting Classifiers"

An ensemble combines several trained models into one. If none of them is good enough on its own, maybe their combination is. Each is a weak learner: "a little bit better than the random classifier, for example 60 or 55 percent" (45:55). The goal is a strong learner from many weak ones. Ways to combine (slide 13):

the prediction of model ; for classification, or
if more models say , else : a majority vote (with ±1 labels, averaging and voting are the same thing, as the slide's blue box says)
in weighted aggregation, each model's vote is multiplied by (the professor: "we do not take a negative" weight); boosting (not covered in this course) learns these weights

Stacking (mentioned, not covered): feed the predictions as a feature vector into another model, e.g. a linear classifier, trained to combine them. Slide 15 shows two pictures of aggregation: averaging many separating lines gives a stable middle line, and combining several axis-aligned stumps gives a staircase boundary that no single stump could draw.

When does voting help? Only when the models are diverse and each is better than chance (slide 16). "If all classifiers have a large overlap with each other, then averaging doesn't make any difference" (49:58). The ideal case is independent errors, where majority voting is spectacularly effective:

0.50.60.70.80.91.0151101151201number of voters M (odd)each 60% → 99.8%each 55% → 92.3%each 51% → 61.2%
Many independent weak voters make a strong one. Probability that a majority of independent classifiers is right, if each is right with probability (a binomial tail). With 201 voters, 60% each becomes 99.8% together. Real models trained on the same data are not independent, so real gains are smaller.
Worked example: 5 independent voters at 60%

The majority is right if at least 3 of 5 are right:

With 25 voters it's 0.846, the "80% from 55–60% learners" the lecture describes. Géron's version: 1,000 independent classifiers that are each right 51% of the time give a correct majority about 73% of the time (he says "close to 75%", which counts a 500–500 tie as a win).

So the question becomes how to get diverse models from one dataset. Two families (slide 16): bagging (this lecture; random forests are the main example) and boosting (AdaBoost; the professor says it's not covered in this course and suggests a tutorial if you're interested).

Quick check: three classifiers each 70% accurate, but they always make their mistakes on exactly the same examples. Majority-vote accuracy?

70%. When they're wrong they're all wrong together, so the vote is wrong too. Diversity, not just accuracy, is what makes voting work.

Section 10

Bootstrapping and bagging

Lecture 56:44–1:01:206b slides 18–23Géron Ch. 7, "Bagging and Pasting"

Slide 19 recalls the week-2 picture: fit a line to 2 points of a sine curve, repeat on many datasets, and each fit is wild, but their average is stable. Averaging reduces variance. The catch: "We only have one dataset in practice!"

Bootstrapping fakes many datasets from one. From , draw points uniformly at random with replacement. Some points are drawn twice or more and others not at all, so each bootstrap set is a slightly different version of . "Several keywords: uniformly, with replacement. These are the two keywords" (58:46).

Bagging (bootstrap aggregating, Breiman 1996): make bootstrap sets, train one model on each, and aggregate by majority vote (classification) or average (regression):

DN pointsbag 1traing1bag 2traing2bag MtraingMsample N withreplacementvoteor averageG(x)
Bagging = bootstrap + train + aggregate. 6b slides 21–22. Every model uses the same algorithm (usually a fully grown tree); diversity comes only from the different resamples. The models can be trained in parallel.

Why it works (slide 23). If are independent, each with variance , their average has variance . Bagging averages many low-bias, high-variance models: averaging keeps the bias about the same and divides the variance. Low bias plus low variance is a strong learner.

Cross-check: slide 23's assumes independence

Bagged trees are trained on overlapping resamples of the same data, so they're positively correlated. If each tree's prediction has variance and any two have correlation , the average has variance

Adding trees only shrinks the second term. The first, , is a floor that no number of trees can get below. That's exactly why random forests try to lower (Section 12). Slide 23 is the special case .

00.250.50.75111020304050number of trees Mρ = 0ρ = 0.3ρ = 0.6variance ÷ σ²
Correlation sets a floor on how much averaging can help. Variance of the average of trees relative to one tree, from the formula above. With , even infinitely many trees keep 60% of a single tree's variance; with , 30%.
Heads up: lecture 57:36, bootstrapping vs. cross-validation

The lecture says bootstrapping was introduced with cross-validation in week 2 and describes it as splitting off training and testing parts. Those are different procedures. Cross-validation partitions the data without replacement: each point is in exactly one fold. A bootstrap sample draws points with replacement: duplicates are normal, and the left-out points are random. Géron's term for sampling without replacement is pasting; bagging specifically means with replacement.

Quick check: a tree's prediction has variance 0.2. You bag 50 trees with pairwise correlation 0.5. What is the variance of the bagged prediction, and what's the limit as M → ∞?

The limit is : adding more trees can't go below it.

Section 11

Out-of-bag points and OOB error

Lecture 1:01:20–1:01:546b slides 24–27Géron Ch. 7, "Out-of-Bag Evaluation"

Slide 24 poses an exercise: when you draw points with replacement from , what's the probability that a particular point is never drawn? Each draw misses it with probability , and the draws are independent:

25101001000
0.2500.3280.3490.3660.368

So each bootstrap set contains only about 63% of the distinct original points, and the other ~37% are out of bag (OOB) for that model. Note they're a different 37% for each model.

Heads up: algebra slip on slide 25

Slide 25 rewrites as . The correct form is

(, not ). The slide's version would go to 0, not : for it gives 0.0006 instead of 0.349. The slide's final answer is right (0.368 to three places).

The OOB error (slides 26–27). A point that never saw is a free validation point for . For each training point , let be the vote of only the models for which was out of bag. Then

majority vote (classification) or average (regression) of the models whose bootstrap set did not contain
err
0/1 error for classification, squared error for regression

It estimates the ensemble's test error with no separate validation set and no extra training: the lecture calls it "basically doing cross-validation" (1:01:26). The difference is that cross-validation retrains on fixed folds, while OOB reuses the randomness bagging already created.

1−2−3−4+5−6+7+8+x =y =bag 1oob1ooboob1222t = 5.5bag 22oob21ooboob21t = 3.5bag 31131ooboob2oobt = 3.5bag 4ooboob1231oob1t = 5.5bag 5ooboob1oob2122t = 5.5cell = times drawn · green = out of bag
Every bag leaves out about a third of the points, and those are its free test points. A real bootstrap run: 8 points on a line, 5 bags of 8 draws each. Numbers count how often each point was drawn; green cells are out of bag. Each bag trains a stump "predict + if "; its best threshold is listed on the right.
Worked example: OOB error for the run above

Data: with labels − − − + − + + + (points 4 and 5 are the "noisy" overlap). Each stump picks the threshold with the fewest errors on its own bag (counting duplicates): bags 1, 4, 5 choose ; bags 2, 3 choose .

Point (label)OOB for bagsTheir votesRight?
1 (−)1, 4, 5− − −−✓
2 (−)2, 4, 5− − −−✓
3 (−)1−−✓
4 (+)1, 5− −−✗
5 (−)2, 3+ ++✗
6 (+)2, 3+ ++✓
7 (+)4++✓
8 (+)3++✓

. Compare the training error of the full ensemble (all 5 stumps vote: three say , so predicts + only for ): only point 4 is wrong, 1/8. The OOB estimate is more honest because no point is judged by a model that trained on it.

Each bag here leaves out exactly 3 of the 8 points (37.5%), close to the expected for .

In scikit-learn: BaggingClassifier(..., oob_score=True) or RandomForestClassifier(oob_score=True), then read oob_score_ (an accuracy, i.e. ).

Quick check: with N = 1000 and M = 3 bags, what's the probability a given point is in all three bags (so it gets no OOB prediction at all)?

In one bag: . In all three: . With bags this drops to , so in practice every point gets OOB votes.

Section 12

Random forests

Lecture 1:01:54–1:04:526b slides 28–30Géron Ch. 7, "Random Forests", "Extra-Trees", "Feature Importance"

A random forest is bagging with decision trees, plus extra randomness to make the trees more different from each other (slide 30):

  1. Bootstrap a dataset for each tree and grow it to full depth (no pruning: we want low bias and accept high variance).
  2. Random feature subsets: at every split, consider only a random subset of of the features and pick the best split among those. A common default for classification is (scikit-learn's max_features="sqrt").
  3. Aggregate: majority vote for classification, average for regression.

Slide 30 mentions one more option from Breiman's paper: randomly project the features (use random linear combinations) for each tree.

Cross-check: "random forest = bagging + decision tree" (lecture 1:02:00)

The lecture summarizes the method as "nothing but bootstrapping plus decision trees". That's bagged trees. What makes it a random forest is step 2, the random feature subset at each split (it's on slide 30 and in Géron). Without it, every tree tends to split on the same strong features near the root, so the trees stay highly correlated, and the floor from Section 10 stays high.

Worked example: how feature subsets decorrelate trees

Say features and one feature is much stronger than the rest. Bagged trees almost all put it at the root. A random forest with only sees it at a given split with probability , so about 75% of root splits must use something else. The trees become more varied (lower ), each one individually a bit worse (higher bias), and the average better.

Here's that trade-off measured. Same data for all three: 1,000 training and 2,000 test points, 30 features (8 informative), 300 trees per ensemble, scikit-learn defaults ( for the forest):

One full treeBagged treesRandom forest
Average accuracy of one member tree0.7930.7850.743
Average correlation between two trees' predictions—0.500.35
Ensemble test accuracy0.7930.88450.898
OOB accuracy estimate—0.8720.882
0.700.750.800.850.90131030100300number of trees M (log scale)one full tree: 79.3%random forest 89.8%bagging 88.45%
Weaker trees, better forest. Test accuracy of the vote of the first trees. A random forest's individual trees are worse (it starts lower at ), but because they're less correlated, the forest overtakes bagging after about 15 trees. Both beat one fully grown tree by 9 to 10 points. Accuracy levels off: more trees never cause overfitting, they just stop helping.
  • Extra-Trees (Géron): also pick the threshold at random instead of searching for the best one. Even more diversity, and faster to train.
  • Feature importance (Géron): average how much each feature reduces impurity across all the forest's splits, weighted by how many samples reach each split. A cheap way to see which features matter.
  • The professor's practical note: "the concept is simple, but while you're doing implementation… what's the depth" and similar details matter, so use the library (sklearn.ensemble.RandomForestClassifier) rather than writing your own (1:03:04).
  • The price: a forest of 300 trees is no longer a readable set of rules. You trade the white box for accuracy.
Quick check: why grow random-forest trees to full depth instead of pruning them?

Averaging attacks variance, not bias. Full-depth trees have low bias and high variance, which is exactly what averaging fixes. Pruning would lower each tree's variance but raise its bias, and averaging can't remove bias.

Section 13

Cheat sheet

Entropy; 0 pure, 1 bit at 50/50 (2 classes), max
Gini; 0 pure, 0.5 at 50/50, max ; scikit-learn default
Misclassification; fine for pruning, too insensitive for growing
Information gain: weighted by child size; pick the max
ID3 / C4.5 / CARTentropy, multiway / gain ratio, thresholds, pruning / Gini, binary splits
Stop splittingpure node, no attributes left, or no examples; leaf = majority label
Continuous featuretest ; candidates = midpoints where the sorted labels change
Overfitting fixespre-prune (max depth, min samples, significance) or post-prune (subtree replacement, reduced-error pruning on validation data)
Bias / variancebias = average prediction − truth; variance = spread across training sets; full tree: low bias, high variance
Majority votehelps only if voters are better than chance and diverse; independent case is a binomial tail
Bootstrapdraw of uniformly with replacement;
Bagging bootstrap sets → models → vote/average; reduces variance, keeps bias
Variance of average; only if independent
OOB error, = models that never saw
Random forestbagging + full-depth trees + random of features per split (); lowers
Section 14

Practice

Score: 0 / 0

Q1What is the entropy of a node with [3+, 1−]?

Q2A node has three classes in equal proportions. Its Gini impurity is:

Q3A split sends a [6+, 2−] node into [3+, 0−] and [3+, 2−]. The information gain is:

Q4You add a unique "Day ID" column to the PlayTennis data and run plain ID3. What happens at the root?

Q5A continuous feature has sorted values 2, 5, 6, 9, 12 with labels No, No, Yes, Yes, No. Which thresholds does the tree need to test?

Q6Why can pre-pruning ("stop when the best gain is below a threshold") stop too early?

Q7You bootstrap 10 points from a dataset of 10. Probability that a particular point is never drawn?

Q8Each tree's prediction has variance 1 and any two trees have correlation 0.5. Variance of the average of 100 trees?

Q9What does a random forest add on top of bagged decision trees?

Q10Bagging helps the most when the base model is:

Problem 1: The table below (6b slide 3) has three ±1 features and a label. (a) Run ID3: compute the gain of each feature at the root, choose, and finish the tree. (b) Slide 3 also shows a 6-leaf tree with at the root that fits the data perfectly. Why does ID3 not build that one, and which tree does Occam's razor prefer? x₁ x₂ x₃ → y: (+,+,+)→+, (+,+,−)→+, (+,−,+)→+, (+,−,−)→+, (−,+,+)→+, (−,+,−)→+, (−,−,+)→−, (−,−,−)→−

(a) Root: [6+, 2−], .

: → [4+, 0−] (H = 0), → [2+, 2−] (H = 1). Gain .

: same counts by symmetry, gain 0.311.

: → [3+, 1−], → [3+, 1−], both H = 0.811. Gain .

and tie; take . Its branch is pure: leaf +. Its branch has [2+, 2−]: there splits into [2+, 0−] and [0+, 2−] (gain 1), while gives [1+, 1−] twice (gain 0). Choose . Final tree: → +; else → +; else −. That's , with 3 leaves, the small tree on slide 3.

(b) has zero gain (it's irrelevant to the label), so greedy ID3 never puts it at the root. Both trees have zero training error; Occam's razor prefers the 3-leaf tree, which also captures the true rule. The 6-leaf tree splits on a feature that carries no information and would generalize no better.

Checked in Python: gains 0.311, 0.311, 0.000 at the root; 1.0 vs 0.0 in the branch.

Problem 2: Bagging with 4 trees on 5 points. Labels . Membership (Y = point is in that bag) and each tree's predictions on all five points are below. (a) Compute the OOB error. (b) Why must point 3 be left out of it? (c) With , what's the probability a given point lands in all 4 bags? in bag 1: Y N Y N Y · bag 2: N Y Y Y N · bag 3: Y Y Y N Y · bag 4: Y N Y N Y g₁: + − − − + · g₂: + + − − + · g₃: + + − + + · g₄: + − + − +

(a) For each point, vote only with the trees whose bag did not contain it:

  • Point 1: OOB for tree 2 only → . Label + → right.
  • Point 2: OOB for trees 1, 4 → −, − → −. Label + → wrong.
  • Point 3: in every bag → no OOB trees.
  • Point 4: OOB for trees 1, 3, 4 → −, +, − → −. Label − → right.
  • Point 5: OOB for tree 2 only → +. Label + → right.

over the four points that have OOB votes.

(b) Every tree trained on point 3, so any prediction for it is a training-set prediction, not a validation one. Including it would make the estimate optimistic. (Tree 4's "+" on point 3 is a training mistake, which OOB rightly ignores.)

(c) One bag contains the point with probability . All four bags: . So about one point in five has no OOB vote when ; with dozens of trees this becomes negligible.

A common mistake is to use all four trees for every point. That's the training error of the ensemble, not the OOB error.