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 canWhat a decision tree is
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.
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).
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:
| Pros | Cons |
|---|---|
| Easy to interpret: a bunch of if–else rules | Generally poor generalization: overfits easily |
| Handles mixed data (numerical and categorical) with no scaling | High variance: a small change in the data gives a very different tree |
| Fast to predict: one comparison per level | Unlimited 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.
Growing a tree greedily
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:
- Pick the "best" attribute for the current node, the one whose split gives the purest children (the next two sections define "purest").
- Split. Make one child per value of and send each training example down the branch matching its value.
- Recurse on each child with only the examples that reached it.
- 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:
| Algorithm | Split criterion | Splits | Notes |
|---|---|---|---|
| ID3 | information gain (entropy) | one branch per value | categorical features; no pruning |
| C4.5 | gain ratio (gain normalized by how many ways the split divides the data) | multiway; thresholds for numbers | adds continuous features, missing values, post-pruning |
| CART | Gini impurity (default) or entropy | always binary: ? | what scikit-learn (and Géron) use; also does regression |
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.
Measuring impurity: entropy, Gini and error
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
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.
, .
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 ().
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 A | Split B |
|---|---|---|
| Misclassification error | 0.25 | 0.25 (tie) |
| Gini | 0.125 | 0.167 |
| Entropy (information gain) | 0.189 | 0.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.
Information gain: choosing the split
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 .
- Parent [29+, 35−]:
- A1: children [21+, 5−] (H = 0.706) and [8+, 30−] (H = 0.742).
- A2: children [18+, 33−] (H = 0.937) and [11+, 2−] (H = 0.619).
- 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.
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.
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:
Worked example: ID3 on PlayTennis
The classic 14-day dataset (slide 16, originally Mitchell Table 3.2). The task: predict PlayTennis from four attributes.
| Day | Outlook | Temp. | Humidity | Wind | Play |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Weak | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Strong | Yes |
| D11 | Sunny | Mild | Normal | Strong | Yes |
| D12 | Overcast | Mild | High | Strong | Yes |
| D13 | Overcast | Hot | Normal | Weak | Yes |
| D14 | Rain | Mild | High | Strong | No |
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:
| Attribute | Children [yes+, no−] (entropy) | Gain | Gini decrease |
|---|---|---|---|
| Outlook | Sunny [2+, 3−] (0.971) · Overcast [4+, 0−] (0) · Rain [3+, 2−] (0.971) | 0.247 | 0.116 |
| Humidity | High [3+, 4−] (0.985) · Normal [6+, 1−] (0.592) | 0.152 | 0.092 |
| Wind | Weak [6+, 2−] (0.811) · Strong [3+, 3−] (1.000) | 0.048 | 0.031 |
| Temperature | Hot [2+, 2−] (1.000) · Mild [4+, 2−] (0.918) · Cool [3+, 1−] (0.811) | 0.029 | 0.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.
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:
| Attribute | Children | Gain |
|---|---|---|
| Humidity | High [0+, 3−] · Normal [2+, 0−] | 0.971 (both children pure) |
| Temperature | Hot [0+, 2−] · Mild [1+, 1−] · Cool [1+, 0−] | |
| Wind | Weak [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.
As rules (slide 22): R1 Sunny ∧ High → No; R2 Sunny ∧ Normal → Yes; R3 Overcast → Yes; R4 Rain ∧ Strong → No; R5 Rain ∧ Weak → Yes.
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.
Continuous features and missing values
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.
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.
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.
Overfitting, Occam's razor and pruning
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.
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.
"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).
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.
Trees are high-variance
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.
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.
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.
Ensembles and aggregation
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:
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.
Bootstrapping and bagging
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):
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.
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 .
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.
Out-of-bag points and OOB error
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:
| 2 | 5 | 10 | 100 | 1000 | ||
|---|---|---|---|---|---|---|
| 0.250 | 0.328 | 0.349 | 0.366 | 0.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.
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.
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 bags | Their votes | Right? | |
|---|---|---|---|---|
| 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.
Random forests
A random forest is bagging with decision trees, plus extra randomness to make the trees more different from each other (slide 30):
- Bootstrap a dataset for each tree and grow it to full depth (no pruning: we want low bias and accept high variance).
- 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"). - 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.
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.
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 tree | Bagged trees | Random forest | |
|---|---|---|---|
| Average accuracy of one member tree | 0.793 | 0.785 | 0.743 |
| Average correlation between two trees' predictions | — | 0.50 | 0.35 |
| Ensemble test accuracy | 0.793 | 0.8845 | 0.898 |
| OOB accuracy estimate | — | 0.872 | 0.882 |
- 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.
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 / CART | entropy, multiway / gain ratio, thresholds, pruning / Gini, binary splits |
| Stop splitting | pure node, no attributes left, or no examples; leaf = majority label |
| Continuous feature | test ; candidates = midpoints where the sorted labels change |
| Overfitting fixes | pre-prune (max depth, min samples, significance) or post-prune (subtree replacement, reduced-error pruning on validation data) |
| Bias / variance | bias = average prediction − truth; variance = spread across training sets; full tree: low bias, high variance |
| Majority vote | helps only if voters are better than chance and diverse; independent case is a binomial tail |
| Bootstrap | draw 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 forest | bagging + full-depth trees + random of features per split (); lowers |
Practice
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.