🌏 中文版
Video status: Videos included. This article is written from the official MOOC handout 210_handout.pdf and transcripts of this lecture's four official videos, with formulas following the handout. The transcripts are machine transcripts made for this article (Whisper), not official captions, and no human has proofread them. The videos are taught in Mandarin; the slides are in English. Each section opens with its official video and the approximate time ranges. Page numbers refer to the number at the lower right of each slide (0/22 to 22/22), and wherever the text says "in the lecture" it is paraphrasing what is said in the video.
This is Techniques Lecture 10 in Reading NTU Hsuan-Tien Lin Machine Learning Foundations & Techniques. The Roadmap on page 1 of the handout divides Techniques into three ways of handling features, and this lecture belongs to the second, Combining Predictive Features: Aggregation Models. The previous lecture, Techniques Lecture 9: Decision Trees, takes up a single line on that page: recursive branching (purification) for conditional aggregation of constant hypotheses. This lecture puts that tree inside the bagging of Techniques Lecture 7: Blending and Bagging and gets the random forest (RF from here on).
The prerequisites are bootstrap and bagging from Techniques Lecture 7, C&RT from Techniques Lecture 9 (decision-stump branching, Gini impurity, fully-grown trees), and and model selection from Foundations Lecture 15: Validation. After reading, you should be able to write down the RF algorithm and its two kinds of random branching; derive roughly how much data bootstrap leaves undrawn; take a table of which example was used by which tree and compute and the permutation-test feature importance by hand; and say how the number of trees should be decided.
The four sections answer these questions in order:
- How bagging and decision trees fit together, and how else each tree can be made more different.
- What the data that bootstrap did not draw can be used for.
- How to tell which features matter.
- What the boundary looks like in practice, and how many trees are enough.
Applying bagging to decision trees, then making the trees more different
(Video 00:19–01:29 reviews the previous lecture, 01:29–05:44 covers bagging plus decision trees, 05:44–09:10 random subspace, 09:10–12:16 random combination, and Fun Time follows.)
What each of the two algorithms is like
Page 2 of the handout sets two algorithms from earlier lectures side by side. On the left is bagging:
- For , request size- data by bootstrapping with (draw one example at a time, with replacement).
- Hand to the base algorithm and obtain .
- Return , that is, let every have one vote (classification) or simply average them (regression).
On the right is the decision tree : if the termination criteria are met, return the base hypothesis at the leaf; otherwise learn a branching criterion , use it to split into parts , recursively build a sub-tree on each part, and return
Under each box is a one-line remark. Bagging reduces variance by voting/averaging; the decision tree has large variance, especially if fully-grown. Variance here means what it meant in Techniques Lecture 7: how much the hypothesis the algorithm returns changes when the data set is swapped for a slightly different one.
In the lecture, Lin explains why decision trees are especially unstable. A tree is carved out one cut at a time, and a small change in the data changes where a cut can go; after each cut every piece holds even less data, so later cuts are even more easily swayed by a handful of examples. A fully-grown tree, cut until nothing more can be cut, shows the problem most clearly.
One algorithm pushes variation down and the other varies a lot on its own, so the handout asks: putting them together? It also notes that this is aggregation of aggregation: a decision tree is already an aggregation that combines the constants at its leaves by conditions, and now a layer of bagging goes around it. In the lecture, Lin compares this way of mixing two things into one to the "pissing beef balls" from a Stephen Chow movie.
The basic random forest
Page 3 gives the definition:
The algorithm just replaces step 2 of bagging with a decision tree:
- For , request size- data by bootstrapping.
- Obtain a tree by .
- Return .
In the lecture, Lin also explains where the name comes from: random refers to the randomness of bootstrap within bagging, and forest is there because every hypothesis under bagging is a tree, and many trees together look like a forest.
The handout lists three benefits, and the lecture adds a short explanation to each:
- highly parallel/efficient to learn. Each round learns one tree independently, with no ordering dependence between trees, so the work can be split across different machines. The decision tree is itself an efficient algorithm, and the two layers together run fast on today's computing architectures.
- inherit pros of C&RT. The previous lecture said C&RT handles multiclass classification, categorical features, and missing values naturally, and RF inherits all of these directly.
- eliminate cons of fully-grown tree. A fully-grown tree is too sensitive to the data and overfits easily; the voting in bagging eases this problem.
Why use fully-grown trees here instead of pruning first? An addition in this article: Techniques Lecture 7 splits the average performance of an algorithm into two parts, the performance of the "consensus" (bias) and how far each strays from the consensus (variance), and bagging approximates the consensus by voting, so it works on the second part. The previous lecture used pruning to hold down the variance of a fully-grown tree; RF leaves that job to the vote, so each tree can be left to grow all the way.
One more layer of randomness: each branch looks at only some of the features
The key to uniform aggregation is having that differ from one another. Page 4 first recalls what bagging does: randomness on the data side, randomly sampling examples from . It then proposes another possibility: randomness on the feature side, randomly sampling features from the features of .
If the sampled feature indices are , this amounts to a feature transform
The transformed space is a random subspace of the original . The lecture's example has 100 features, with only 10 of them randomly chosen each time to build a tree; this round picks these 10 and the next round picks those 10, and the two trees clearly classify by very different criteria.
The handout points out two more things:
- Often , so this is in fact more efficient when is large. In the lecture, Lin explains that deciding where to cut used to mean going through all the cuts in 100 dimensions, and now only 10 have to be examined.
- The technique is not limited to decision trees: it can be generally applied on other models. In the lecture, Lin says it also works to apply it to SVM or AdaBoost and then aggregate.
The last line is a design specific to RF: original RF re-sample new subspace for each in C&RT. The random subspace is not sampled once per tree; a new set of features is drawn every time a branch has to be found. In the lecture, Lin says this is the original author's suggestion, and that sampling at every branch makes the trees look more different. So the definition of RF is updated to
Random combination: letting a branch cut along a slanted line
Page 5 rewrites "sample features" in matrix form: , where has rows, each sampled randomly from the natural basis (the unit vectors with a single component equal to 1 and the rest 0). As an example (made up for this article, not from the slides), with and features 2 and 4 sampled:
Written this way, the next step comes naturally. The question asked in the lecture is: why must the projection directions be these fixed coordinate-axis directions? The handout's answer is to let each row of be something other than the natural basis, so that the new features are random combinations of the original ones:
The handout calls these more powerful features for diversity. The same page has three more points:
- Often only a low-dimensional projection is considered: has only non-zero components. The lecture's example is that out of 100 features, this time 3 are picked and combined into one weighted score that gets cut, and next time another 5 are picked; the tree does not combine all 100 every time.
- Random subspace is its special case: and is a vector in the natural basis.
- original RF consider random low-dimensional projections for each in C&RT: the original RF generates such random projections afresh at every branch, and C&RT then finds the best decision stump among these new features.
Continuing the example above (made up for this article), replace with two rows that each have non-zero components:
The first new feature is . A cut on it, say , is a slanted line in the original space, where C&RT could previously make only vertical or horizontal cuts.
The page ends by writing RF as
and adds: randomness everywhere! In the lecture, Lin says it is no wonder the method is called random forest: besides the randomness of bagging, there is also randomness in every branching step of C&RT.
The three layers of definition side by side:
| Version | Data for each tree | Features considered at each branch |
|---|---|---|
| Basic (page 3) | examples by bootstrap | All original features |
| random-subspace (page 4) | Same | randomly sampled original features, re-sampled at every branch |
| random-combination (page 5) | Same | random combinations, each using original features, re-sampled at every branch |
Fun Time: which hypothesis a random-combination branch is equivalent to
Question (page 6): Within RF that contains random-combination C&RT trees, which of the following hypothesis is equivalent to each branching function within the tree?
- a constant
- a decision stump
- a perceptron
- none of the other choices
Answer: 3. The handout's solution: in each , the input vector is first projected by a random vector and then thresholded to make a binary decision, which is exactly what a perceptron does. As a formula, the decision stump on the new feature is
Take as and as the remaining weights, and it is the of Foundations Lecture 2: Perceptrons and PLA. In the example above, the branch corresponds to . Lin's summary in the lecture is that with projection, the cuts are no longer only vertical and horizontal; they can be slanted too.
Choice 1 is wrong because a constant does not split the data into two sides. Choice 2 holds only in a special case: in the random-subspace version with , the branch is a decision stump on an original feature; a general random combination uses more than one feature and is not a stump in the original space. One addition in this article: the direction of this perceptron is generated randomly, and the data decide only which of the candidate directions is chosen and the threshold , which is unlike PLA learning the whole from data.
The data bootstrap did not draw can be used for validation
(Video 00:00–01:26 is the OOB table, 01:26–04:24 counts how many examples are OOB, 04:24–10:25 compares with validation and defines the OOB error, 10:25–11:54 uses it for model selection, and Fun Time follows.)
One table: which example was used by which tree
Page 7 goes back to the bagging procedure and lays it out as a table: each row is one example and each column is one . If was drawn into , that cell says ; if it was not drawn, the cell gets a star. The table on the slide looks like this:
The handout's definition: a in the -th column means the example was not used for obtaining , and such examples are called the out-of-bag (OOB) examples of . Take column 1: training used example 1 and example , and examples 2 and 3 are its OOB examples.
Roughly how many OOB examples each tree has
Page 8 first states the question precisely: an example is OOB for exactly when it is not sampled after drawings. The handout computes only the case , and the derivation has three steps.
Step 1: the probability of being missed in a single draw. Each bootstrap draw picks one of the examples uniformly, so the probability of drawing is and the probability of missing it is .
Step 2: missed in all draws. Every draw is made with replacement, so the draws are independent and the probabilities simply multiply:
Step 3: the approximation for large . The handout rewrites it into a recognizable form:
The first equality puts everything over a common denominator, the second flips the fraction into the denominator, and the third is . In the lecture, Lin says these first steps are only simple rearrangements meant to pull out a more familiar term; the final approximation uses the limit from calculus. This article fills in the last step: let , and the denominator is
so the whole expression tends to . The handout's conclusion is
This article computed the actual values for a few in Python to see how quickly the approximation becomes accurate:
| Average number of OOB examples per tree | ||
|---|---|---|
| 2 | 0.2500 | 0.50 |
| 5 | 0.3277 | 1.64 |
| 10 | 0.3487 | 3.49 |
| 100 | 0.3660 | 36.6 |
| 1126 | 0.3677 | 414.0 |
At the value is already near 0.35, and from on it differs from only in the third decimal place. In the lecture, Lin roughly estimates the fraction aloud as about one third and says that out of 100 examples about 30 or so are OOB; by it is 36.8 examples, a little more than one third.
The handout treats only . The lecture mentions in passing that the result differs somewhat when the number of draws is not . An addition in this article, the general case: replace the exponent in step 2 with ,
The fewer the draws, the higher the OOB fraction. The demonstration figures on pages 17 to 19 of the handout use , and the fraction in that case is left to Self-check question 1.
OOB examples are like validation data
Page 9 puts the OOB table next to the validation of Foundations Lecture 15: Validation. Validation splits the data into and , trains with only, and then measures it with . The lecture restates why this can be trusted: the validation data were not used to obtain , and had they been used, they could no longer serve for validation.
The OOB table has the same structure. used only the examples marked in the table and has never seen the starred ones. The handout puts it as like : 'enough' random examples unused during training. The lecture fills in what "enough" means: ordinary validation might hold out only one fifth or one tenth of the data, while here each tree leaves about one third of the data unused.
The handout then asks two questions.
Use to validate ? The handout answers: easy, but rarely needed. The procedure is direct: compute the error rate of on its OOB examples. The reason it is rarely needed is given in the lecture: bagging and RF are aggregation, and the goal is to obtain , not to find out whether an individual is good.
Use to validate ? No single example can be used to test directly, because some trees in have certainly seen it. In the lecture, Lin says the only point that matters here is keeping the starred data uncontaminated, and the way to do it is to look at one example at a time: for , which trees can it serve as validation data for? Exactly the with a star in its row. Put those trees together into a smaller forest, written , and is data that has never seen. The lecture explains the minus sign: this forest is a bit smaller than the full . The in validation means the same thing, a hypothesis trained with less data.
The handout's example is the last row. The table on page 9 draws the row of with only having used it (this differs from the table on page 7 in the cell) and stars everywhere else, so
In the lecture, Lin stresses that cannot be included, because was used to learn . Do this for every example and average the errors, and the result is the OOB error:
In the lecture, Lin says this is a little like the leave-one-out cross validation of Foundations Lecture 15: every example takes a turn as validation data, its performance is checked, and the average is taken at the end. The handout calls the self-validation of bagging/RF. As Lin puts it in the lecture, the moment is finished, the bootstrap procedure has already told you roughly how well it performs, and no separate validation run is needed.
This article adds two details that come up in implementation. First, if an example is drawn by every tree, its is empty and cannot be evaluated. The probability that an example is drawn by a given tree is about , and the probability that all trees draw it is about : 0.101 for and 0.0001 for , negligible once there are many trees. Second, each example's has only about trees, fewer than the full , so estimates the performance of a smaller forest.
Numerical example: eight examples, five trees, the OOB error by hand
The following example is made up for this article and is not from the slides; every number was recomputed separately in plain Python. The setting reuses the credit card approval from Foundations: eight applicants, where is annual income (in units of 10,000 NTD), is the last digit of the application's serial number (unrelated to approval, included for the feature importance computed later), and means the card is approved.
| (annual income) | (last digit of serial number) | ||
|---|---|---|---|
| 1 | 28 | 6 | |
| 2 | 35 | 1 | |
| 3 | 41 | 8 | |
| 4 | 50 | 3 | |
| 5 | 62 | 5 | |
| 6 | 68 | 9 | |
| 7 | 77 | 2 | |
| 8 | 90 | 7 |
Use the basic RF: , , and each tree is a fully-grown C&RT (Gini impurity, thresholds at the midpoint of two adjacent values). The five bootstrap data sets were drawn with random numbers and then fixed. To keep the example computable by hand, this article picked a sampling outcome in which every tree needs only one cut and every example has at least one tree that has not seen it.
Step 1: sample, and find each tree's OOB examples.
| (example numbers in the order drawn) | OOB examples of | |
|---|---|---|
| 1 | 7, 3, 1, 5, 7, 5, 8, 8 | 2, 4, 6 |
| 2 | 5, 6, 2, 5, 3, 4, 5, 4 | 1, 7, 8 |
| 3 | 7, 8, 4, 3, 4, 3, 4, 4 | 1, 2, 5, 6 |
| 4 | 8, 8, 5, 1, 1, 2, 3, 4 | 6, 7 |
| 5 | 5, 8, 6, 7, 4, 5, 6, 4 | 1, 2, 3 |
The five trees have 3, 3, 4, 2, and 3 OOB examples, an average of 3.0. The formula gives an expected value of examples, and the approximation gives 2.94.
Step 2: run C&RT for each tree. Take . contains examples 1 and 3 (once each, ) and examples 5, 7, and 8 (twice each, ). Among all combinations of feature and threshold, C&RT picks the one that minimizes . The candidate thresholds on and their results:
| Branch | Left (below the threshold) | Right | Weighted impurity |
|---|---|---|---|
| against 34.5 | 1 example, all | 7 examples, 1 negative and 6 positive | |
| against 51.5 | 2 examples, all | 6 examples, all | |
| against 69.5 | 4 examples, 2 negative and 2 positive | 4 examples, all | |
| against 83.5 | 6 examples, 2 negative and 4 positive | 2 examples, all |
Here Gini is computed as ; for instance, 1 negative and 6 positive gives . The four candidate thresholds on (3.5, 5.5, 6.5, 7.5) come out as , , , and , none of them 0. So the first cut of is " against 51.5". After it both sides are already pure, the termination criteria are met, and this fully-grown tree has a single level:
51.5 is the midpoint between the largest negative example in (example 3, 41) and the smallest positive example (example 5, 62). The other four trees likewise make just one cut, always on (in every tree, no candidate on gives pure sides):
| Largest negative example in the bag | Smallest positive example in the bag | Threshold of | |
|---|---|---|---|
| 1 | example 3, 41 | example 5, 62 | 51.5 |
| 2 | example 4, 50 | example 5, 62 | 56 |
| 3 | example 4, 50 | example 7, 77 | 63.5 |
| 4 | example 4, 50 | example 5, 62 | 56 |
| 5 | example 4, 50 | example 5, 62 | 56 |
From one original data set, the five trees end up with three different thresholds. did not draw examples 5 and 6, so the smallest positive example it sees is 77 and its threshold gets pushed to 63.5. This is the variance the handout talks about: change the data and the tree changes.
Step 3: draw the OOB table and compute for each example. "in" means the example is in (in the bag), and means OOB.
| Trees in and their predictions | Wrong? | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 28 | in | in | : | ||||||
| 2 | 35 | in | in | : | ||||||
| 3 | 41 | in | in | in | in | : | ||||
| 4 | 50 | in | in | in | in | : | ||||
| 5 | 62 | in | in | in | in | : | wrong | |||
| 6 | 68 | in | in | : | ||||||
| 7 | 77 | in | in | in | : | |||||
| 8 | 90 | in | in | in | in | : |
Take example 5: only has not seen it, so . The threshold of is 63.5 and , so it predicts , which disagrees with . One of the eight examples is wrong:
Step 4: compare with . Look at example 5 with , the vote of all five trees: the thresholds of are all below 62 and they vote ; only votes . Four to one, and gets it right. On the other seven examples the five trees agree, and they are all correct. So .
What this result means. because the four trees that saw example 5 will of course classify it correctly, and that number says nothing about what happens when new data arrive. asks only the trees that have not seen the example, and it exposes something cannot show: for people whose annual income falls between 50 and 77, whether a tree drew the nearby examples affects its threshold, and the prediction can go wrong. A new applicant is exactly data that no tree has seen, and that is the situation simulates. With only eight examples the estimate is of course crude (a single example is 0.125); the point is the procedure.
Selecting a model with the OOB error
Page 10 puts the model selection procedure of Foundations Lecture 15 next to the RF version:
| Previously: by best | RF: by best | |
|---|---|---|
| Score of each candidate | ||
| Which one is chosen | ||
| What is finally delivered |
On the left every candidate is trained twice: first on so that can be computed, and once is chosen, again on the full . On the right every candidate is trained directly on the full , comes along for free, and the chosen is already the finished product. The handout writes this as two points: use for self-validation of RF parameters such as , and no re-training needed. The lecture names a few more selectable parameters than the handout: , the number of dimensions used in a random projection, as well as other parameters or heuristics of the decision tree itself.
The last line of this page is often accurate in practice. In the lecture, Lin says that in RF practice, measuring the performance of with the OOB error is usually quite accurate. This is an empirical statement, and the handout gives no theoretical guarantee.
Fun Time: 1126 examples and the probability of not being sampled
Question (page 11): For a data set with , what is the probability that is not sampled after bootstrapping samples from the data set?
- 0.113
- 0.368
- 0.632
- 0.887
Answer: 2. The handout's solution: the value of with is about 0.367716, which is close to . This article checked it in Python: , and the two differ by 0.00016. In the lecture, Lin says that whether you estimate it or actually compute the probability, the answer is near 0.368.
The 0.632 of choice 3 is , the probability that the example is drawn at least once; reading the event the question asks about backwards leads to it. Choices 1 and 4 also add up to 1, but neither 0.113 nor 0.887 matches a quantity in the derivation. The question asks about example 1126, and the answer is the same for every other example, because each one has an equal chance of being drawn.
Which features matter: the permutation test plus OOB
(Video 00:00–04:49 gives the motivation and the pros and cons of feature selection, 04:49–05:45 the selection built into decision trees, 05:45–09:07 ranking by importance and linear models, 09:07–13:23 the permutation test, 13:23–18:35 what the original RF does, and Fun Time follows.)
What feature selection is trying to solve
Page 12 defines the problem: for the input , we want to remove two kinds of features.
- redundant: the handout's example is keeping one of "age" and "full birthday". The lecture uses a medical record: a form sometimes asks for your age and sometimes for your birthday, and filling in both duplicates information, since age can be computed from the birthday.
- irrelevant: the handout's example is insurance type for cancer prediction. In the lecture, Lin says whether a patient has cancer is a matter of the body's condition and should have nothing to do with which insurance the patient holds, yet the record form has that column all the same.
After removing them, we only learn a subset-transform with , and then predict with . The numbers used in the lecture are selecting 300 dimensions out of 10,000, with a reminder that this goes in the opposite direction from earlier feature transforms: those went to higher dimensions, and this one goes lower.
The handout lists three advantages and three disadvantages, and the lecture points out that the two sides correspond one to one:
| Advantage | Corresponding disadvantage |
|---|---|
| efficiency: simpler hypothesis and shorter prediction time | computation: 'combinatorial' optimization in training |
| generalization: 'feature noise' removed | overfit: the 'combinatorial' selection may itself overfit |
| interpretability: the features that remain can be interpreted | mis-interpretability: the interpretation may be wrong |
The lecture first explains the left column with the 300-out-of-10,000 example: after selection, training and prediction both run on only 300 dimensions; if the selection is good, it amounts to excluding the noise in the other 9,700 dimensions, which makes overfitting less likely; and the 300 remaining dimensions can go on to further analysis, for example when a medical application wants to know which items relate to what is being predicted. It then goes through the right column item by item. Efficiency comes after the selection, but which 300 of the 10,000 to choose is a combinatorial problem, and the effort may all be spent in the selection stage. A correct selection excludes noise, but with that many combinations it is quite possible to pick a set of features that looks good and is in fact not that good. As for interpretation, if the selection process has already overfit, the interpretation is wrong; and even if it has not, the interpretation may show only correlation, not causation.
The last sentence on this page is decision tree: a rare model with built-in feature selection. The lecture's explanation: a decision tree has to pick a feature to cut on every time, and that picking is selection; an SVM, by contrast, puts all the features into the computation. AdaBoost with decision stumps has the same property, choosing one feature to cut on in every round.
First trade the combinatorial problem for a ranking problem
The idea on page 13: if it is possible to calculate a score for each feature, , then we can simply select the features with the top importance. The lecture states outright what this approach gives up: it ignores interactions between features and looks only at the importance of each feature on its own. What it buys is not having to face the combinatorial explosion.
A linear model makes this easy. The score of a linear model is
The handout's intuitive estimate is with some 'good' , and a good is one learned from data. The lecture's explanation: when is large, feature carries a lot of weight in the score; when is small, it hardly affects the score. The lecture also mentions that once the features are picked this way, the second stage can be followed by a linear or a non-linear model, because feature selection and the later learning are two separate steps. The lecture adds one more premise that the handout does not write down: the value ranges of the features must not differ too much, or the comparison means nothing. This article adds an example: change the same income feature from units of 10,000 NTD to units of 1 NTD, and shrinks by a factor of 10,000, but the importance of the feature has not changed.
The handout then writes: non-linear models? often much harder. The reason given in the lecture is that in a non-linear model the effects of the features are tangled together, and it is hard to isolate one number that measures the importance of a single feature. RF is a non-linear model, but its internal mechanism makes this relatively easy, and that is the content of the next two pages.
The permutation test: shuffle one feature and see how far performance drops
The idea on page 14 is called a random test: if feature is needed, then replacing with random values degrades performance. As Lin puts it in the lecture, the feature matters a lot to you, you stuff some garbage into it, and of course performance gets worse; compare the performance before and after the stuffing, and the gap tells you how important the feature is.
Which random values should be stuffed in? The handout compares two kinds:
- uniform, Gaussian, ... The handout's note is changed. The lecture explains: the original data may not be Gaussian in this feature at all, and if Gaussian random numbers are forced in, the measured performance gap mixes two causes, one being that the distribution was changed and the other being the effect of the noise that we actually want to measure.
- bootstrap, permutation. The handout's note is approximately remained. Both take values only from the feature's existing values .
Permutation means randomly rearranging these values. The lecture's analogy is shuffling cards: shuffle 52 cards and put them back into 52 positions, and they are still the same cards. Seen as a whole, the distribution of the feature has not changed; but for each example the value is now scrambled, and the lecture's example is patient A's value going to patient B and patient B's going to patient C. The gap measured this way reflects just one thing: the correspondence between this feature and the other features, and between this feature and , has been broken.
The permutation test is therefore defined as
where is with the -th feature replaced by the permuted . The handout stresses that this is a general statistical tool for arbitrary non-linear models like RF, not something exclusive to RF.
What the original RF does: no re-training, only a trick at validation time
Page 15 deals with the remaining question: how the two performance terms are measured.
By definition, means re-training a model on the permuted data and then validating it. The handout says this needs re-training and validation in general. With features, that is rounds of re-training.
Validation first. The handout asks: 'escaping' validation? The answer is the OOB just learned: RF needs no separate validation data, and performance can use directly. The term for the original data is then .
Then re-training. By the logic so far, the other term should be , with a forest re-trained on . As Lin puts it in the lecture: I am lazy and do not want to re-train, so let us take a shortcut and replace with . The two differ in where the sits:
- : the permuted data are used in training, which yields a different forest.
- : the forest stays as it is, and the permutation happens only when the OOB error is computed.
The handout writes this as
and explains that comes from replacing each request of by a permuted OOB value. The lecture unpacks that sentence: computing the OOB error requires , is a decision tree, and on reaching some node it may need the value of , which is replaced at that moment. Replaced with whose value? The original author's suggestion is not to take it from all the data, but only from the examples that are OOB for . The reason given in the lecture is that the swapped-in value is then still something has not seen, the training process is not touched at all, and the measurement is more accurate.
The conclusion of this page is RF feature selection via permutation + OOB: often efficient and promising in practice. The lecture is more specific: RF feature selection works well in practice, and many people facing a non-linear problem first use RF for a preliminary feature selection.
This article adds a caution for reading the formula. Page 14 of the handout writes performance, where larger is better, and an important feature makes positive. Page 15 substitutes for performance directly, but is an error, where smaller is better; when an important feature is permuted the error rises, and computed literally from the formula is negative. Both the handout and the lecture substitute for performance as is; what is being compared is how far apart the two quantities are before and after the permutation, and the sign is not adjusted separately. When reading, look at the size of the gap: how much the error rose, that is, , and the more it rose, the more important the feature.
Numerical example (continued): the importance of the two features
Now continue with the example of eight examples and five trees, still made up for this article. The baseline is .
First (the last digit of the serial number). All five trees cut only on , and no node ever uses the value of . Whatever is replaced with, every stays the same, so
Then (annual income). The permutation should be random. To keep it computable by hand, one fixed arrangement is used here: the OOB examples of each tree are arranged in a circle by number, and each example takes the of the next one.
| Threshold | OOB examples | The swapped in | |
|---|---|---|---|
| 1 | 51.5 | 2, 4, 6 | example 2 gets 50, example 4 gets 68, example 6 gets 35 |
| 2 | 56 | 1, 7, 8 | example 1 gets 77, example 7 gets 90, example 8 gets 28 |
| 3 | 63.5 | 1, 2, 5, 6 | example 1 gets 35, example 2 gets 62, example 5 gets 68, example 6 gets 28 |
| 4 | 56 | 6, 7 | example 6 gets 77, example 7 gets 68 |
| 5 | 56 | 1, 2, 3 | example 1 gets 35, example 2 gets 41, example 3 gets 28 |
The same example gets different values in different trees, because each tree permutes within its own OOB examples. Recompute for each example:
| The each OOB tree sees, and its prediction | Vote | Wrong? | ||
|---|---|---|---|---|
| 1 | : 77, ; : 35, ; : 35, | |||
| 2 | : 50, ; : 62, ; : 41, | |||
| 3 | : 28, | |||
| 4 | : 68, | wrong | ||
| 5 | : 68, | |||
| 6 | : 35, ; : 28, ; : 77, | wrong | ||
| 7 | : 90, ; : 68, | |||
| 8 | : 28, | wrong |
Three are wrong, so . By the handout's formula,
which is to say the error rose by 0.25. Example 5 was wrong before and is right this time, because it happened to get 68, a value that also belongs to a positive example; not every example gets worse after a permutation.
What this result means. Permuting raises the OOB error from 0.125 to 0.375, while permuting has no effect at all, so the ranking is above , which matches how the data were designed. No tree was re-trained anywhere in the process; only the predictions were rerun.
The result of one single permutation carries an element of luck. This article used a program to enumerate every possible arrangement in this example (each of the five trees permutes its own OOB examples, combinations in total, with a tied vote counted as half an error): is 0 at its lowest and at its highest, and averages . On average the error still rises (0.125 to 0.292), but 2.8% of the arrangements happen to bring the error down to 0. With only eight examples, the number from one permutation should not be taken too seriously; the fluctuation becomes small only with a lot of data and a lot of trees.
Fun Time: the importance of a constant feature
Question (page 16): For RF, if the 1126-th feature within the data set is a constant 5566, what would be?
- 0
- 1
- 1126
- 5566
Answer: 1. The handout's solution: when a feature is a constant, permutation does not change its value; then and are the same, and thus . In the lecture, Lin says that however you randomly rearrange, that feature always comes out as 5566, the same as before, so the OOB performance is exactly the same too.
Choices 2, 3, and 4 are numbers that appear in the question or are put together from it; importance is the difference of two errors and will not equal the index of a feature or its value. An addition in this article: the 0 in this question has a second source. A constant feature cannot split the data into two sides at whatever threshold, so C&RT never branches on it and no tree ever uses its value; this is the same reason the importance of is 0 in the example above. The thing to watch out for in the other direction is that an importance of 0 means only that this forest did not rely on the feature, and does not guarantee that the feature is entirely unrelated to .
What it looks like in practice, and how many trees
(Video 00:01–05:28 is the simple data set, 05:28–06:26 the complicated data set, 06:26–07:44 the data set with added noise, 07:44–11:10 discusses how many trees, 11:10–11:37 is Fun Time, and the summary follows.)
The slides in this section are almost all figures. All three data sets are binary classification in the two-dimensional plane, with circles as one class and crosses as the other, a blue and red background showing which class the model predicts, and a black line for the boundary. The figures on all three pages are labeled : the bootstrap for each tree draws only half the data size. Page 17 additionally states that the trees are C&RT with random combination; pages 18 and 19 do not repeat the label, and the boundaries of the single trees in those figures are slanted lines as well.
The simple data set: more trees, smoother boundary
Page 17 has three panels, and the slides step from 1 up to 1000 one frame at a time.
| Panel | What it draws | What you see |
|---|---|---|
| Left (fixed) | No bagging: one random-combination C&RT trained on all the data | The boundary is pieced together from several slanted segments and cuts the plane into irregular polygons |
| Middle | The -th tree . Large circles and crosses are examples drawn by bootstrap; small dots are the ones not drawn | Every tree has a different boundary, often just one or two slanted lines, and some of the undrawn points are misclassified |
| Right | voted by the first trees | Changes with , see below |
How the right panel changes, as described in the lecture:
- : there is only one tree, the boundary of is identical to that of the tree in the middle, and some points are misclassified.
- : the boundary twists and turns. In the lecture, Lin says it looks a bit like an amoeba; you can tell it is the result of many different trees voting, and it is already far more complex than each single tree alone.
- From on: the boundary keeps getting smoother, though it is still not very regular.
- : the slide's remark is 'smooth' and large-margin-like boundary with many trees.
The lecture compares the right panel at with the single tree on the left and points out two things. First, the forest's boundary runs roughly through the middle between the circles and the crosses, whereas the single tree's boundary has a stretch pressed right up against one of the crosses. A boundary far from the points on both sides is the large margin of Techniques Lecture 1: Linear SVM. Second, the forest's boundary is much smoother. Lin's comment in the lecture is that it is interesting for a bunch of messy trees to have such a property when combined, much as the opinions of a crowd of internet forum users can add up to something quite good. The handout's wording is large-margin-like: it has that look, but nothing says RF is optimizing the margin.
The complicated data set and the data set with added noise
Page 18 switches to a data set with many points whose true boundary is a curve, keeps only the middle and right panels, and steps through 1, 6, 11, 16, 21. A single tree's boundary is crooked and has sharp corners; with 21 trees combined, the right panel already shows a relatively smooth non-linear boundary that hugs the border between the two classes. The slide's remark is 'easy yet robust' nonlinear model. In the lecture, Lin says this non-linear boundary was obtained in a very simple way, with only twenty or so decision trees, and that it is far more stable than the single trees on the left.
Page 19 uses the same data set, which the lecture explains has 10% noise added, and again goes from 1 to 21. This time the single trees are affected heavily: a fully-grown tree must cut until every example is classified correctly, so it fences off small patches of red inside the blue region for a few mislabeled crosses, and vice versa. In the lecture, Lin says these parts look like overfitting the noise. With 21 trees combined, the main boundary still comes out, and most of those small patches are gone, with only a few left. The slide's remark is noise corrected by voting.
This article adds why voting removes these patches. For a mislabeled example, only the trees that drew it fence off a patch for it; with , each tree has about a 60% chance of not drawing it (Self-check question 1), and those trees predict at that location according to the surrounding majority. In the vote, the trees that fence off a patch for the noise are the minority.
How many trees are enough
The first line of page 20 is almost every theory: the more, the 'better', under the premise assuming good . The lecture explains that the theory of RF is not covered in detail in this lecture, but most of that theory assumes that infinitely many trees give a relatively stable and relatively good result, and that finitely many trees only approximate it. So the practical question is how many trees count as a close enough approximation.
The handout then gives an experience from NTU itself, under the heading Our NTU Experience:
- The competition: KDD Cup 2013 Track 1, predicting author-paper relation (in the lecture, Lin describes it as predicting whether a given author wrote a given paper). The slide adds a note next to it: yes, NTU is world champion again! :-).
- The observation: of thousands of trees fell in depending on seed; of the top 20 teams in the same competition fell in .
- The decision: take 12000 trees with seed 1.
The lecture adds three things the slide does not say. First, that year, for certain reasons, the OOB error was not used and the validation error was computed directly, which is why the slide writes . Second, what the two intervals mean when set side by side: with a well-chosen random seed the score is close to the top three, and with a poorly chosen one it drops to around 20th place. Same method, same data, and the only difference is the random numbers. Third, the final approach was to add as many trees as could be computed, with seed 1; in the lecture, Lin says not to ask why 1, it just seemed a relatively stable choice at the time.
From this the handout writes down the cons of RF: may need lots of trees if the whole random process too unstable, and it recommends: should double-check stability of to ensure enough trees. As Lin puts it in the lecture, RF is a randomized algorithm, and if the random process has not yet reached a stable state, or your problem is sensitive to tiny changes (the gaps between ranks in that competition were very small), the result goes up and down with the random numbers. In practice you check whether is stable: if performance still changes with one tree more or one tree fewer, there are not enough trees, so add more.
An addition in this article: why adding trees makes the result settle down
The reasoning in this part is not in the handout. It is here to explain why the result changes with the seed when there are not enough trees.
Once the data are fixed, every tree uses its own independent random numbers (its own bootstrap, its own random projections). So at each point , the predictions of trees are independent draws. Suppose one tree predicts circle at this point with probability . When , the of infinitely many trees answers circle at this point. The probability that the vote of trees differs from is the binomial probability that circle does not get a majority in draws (the table takes odd to avoid ties):
| 0.60 | 0.400 | 0.317 | 0.154 | 0.021 | below 0.0001 |
| 0.55 | 0.450 | 0.407 | 0.306 | 0.156 | 0.001 |
| 0.51 | 0.490 | 0.481 | 0.460 | 0.420 | 0.263 |
For example, with and : the probability that circle gets 0, 1, or 2 votes is .
The table shows two things. For points far from the boundary ( far from 0.5), a few dozen trees are stable enough. For points near the boundary ( close to 0.5), even a thousand trees still have a one-in-four chance of differing from , and a different seed may flip the answer. In the figures for the simple data set, the boundary twisting at and becoming smooth only by , and the KDD Cup score still moving with the seed at thousands of trees, can both be understood from this angle: what wobbles is the points near the boundary. This is also why no single is right for every problem.
Fun Time: which one is not the best use of RF
Question (page 21): Which of the following is not the best use of Random Forest?
- train each tree with bootstrapped data
- use to validate the performance
- conduct feature selection with permutation test
- fix the number of trees, , to the lucky number 1126
Answer: 4. The handout's solution: a good value of can depend on the nature of the data and the stability of the whole random process. In the lecture, Lin says the number of trees needed differs as the data differ and as the stability of the process differs.
Choices 1, 2, and 3 are each the centerpiece of one of the lecture's first three topics: bootstrap is part of the definition of RF, is the self-validation that comes with it, and the permutation test is the feature-importance computation the handout introduces. The problem with choice 4 is not that 1126 is too large or too small, but that it is fixed without checking; by the handout's advice, you should see whether has become stable.
The summary on page 22 reduces each of the four sections to one line: bag of trees on randomly projected subspaces; self-validation with OOB examples; permutation test for feature importance; 'smooth' boundary with many trees. The preview of the next lecture is boosted decision trees beyond classification: combining decision trees with boosting of the AdaBoost kind, and extending to problems other than classification.
Self-check
1. In the demonstration figures, the bootstrap for each tree draws only examples. When is large, roughly what is the probability that an example is OOB for a given tree? Is it higher or lower than with ?
Answer: . It is higher than the 0.368 of , because with fewer draws there is a better chance of escaping. Computed directly with , .
2. , . What is the probability that example 1 is OOB for a given tree? How many OOB examples does a tree have on average? How far is that from ?
Answer: . The average number of OOB examples is . overestimates by about 20 percent; is the approximation for large , and is not large enough.
3. Four examples, three trees. The table lists each tree's prediction on each example, and parentheses mean the example is in that tree's bootstrap data (not OOB). Compute and .
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 |
Answer: predicts , wrong. consists of , both predicting , right. predicts , wrong. consists of , both predicting , right. . uses the vote of all three trees: the tallies for the four examples are two positive and one negative, three positive, two negative and one positive, and three negative, all correct, so . The predictions in parentheses are all correct (the tree has seen that example), and those are the votes relies on.
4. In a permutation test, why not simply replace feature with Gaussian random numbers? And when the original RF computes , why are the swapped-in values taken only from that tree's OOB examples?
Criteria: for the first part, say that Gaussian random numbers change the distribution of the feature, so the measured performance gap mixes in the effect of the changed distribution, whereas permutation only rearranges the existing values and leaves the distribution roughly unchanged. For the second part, say that with OOB values the swapped-in data are still something did not see in training, so the validation is not contaminated by data used in training.
5. At some branch the sampled projection vector is and the threshold is 2.5. Which kind of hypothesis is this branch? Which of the handout's three RF versions does it fall under? What if ?
Answer: , so the branch is , a decision stump on the original feature , which is the random-subspace special case with and in the natural basis. With the branch is , which uses two features (), is a slanted line in the – plane, and is equivalent to a perceptron with .
Exercises and corresponding reading
The corresponding week in two semesters. The Fall 2024 course page puts decision trees, random forests, and gradient boosted decision trees in the same week (W12, 11/18), taught together with AdaBoost, and the slides for this lecture are 210u. The Fall 2026 course page also puts them in W12 (11/25); that week's slides could not yet be opened as of 2026-09-30, so this article uses only the MOOC handout.
Textbook and further reading. The course pages do not map this lecture to a chapter of Learning from Data. Among the further reading listed on the course page, the one directly related to this lecture is Breiman, Random Forests (Machine Learning, 2001), the original random forest paper; the "original RF" that keeps appearing in the handout and the "original author" mentioned in the lecture refer to it.
Homework. Fall 2024 HW7 (released 2024-12-02, due 12-16, no official solutions) has no problem specifically on random forests and no related programming problem. The closest is Q1: bootstrapping with , it asks how many draws it takes for the probability of at least one repeated example to exceed 70%. It is the same kind of computation as this lecture's OOB derivation: both write "each draw is independent" as a product. The guide to the whole assignment is in Techniques Homework and Final Project.
Hands-on. To verify for yourself the statement that is usually accurate, run scikit-learn's RandomForestClassifier with oob_score=True on the madelon data used in the HW7 programming problems, and compare oob_score_ with the result on the test set. Three things to know when matching it up: oob_score_ reports accuracy, so subtract it from 1 to get this lecture's ; max_features controls how many features each branch considers, which corresponds to the handout's random subspace (), and scikit-learn does not do random combination; feature_importances_ is computed from the decrease in impurity, not this lecture's permutation test, and the permutation version is sklearn.inspection.permutation_importance, which permutes on the data you give it, not on OOB. Then try several values of random_state and several of n_estimators, and watch how the seed-to-seed wobble of the OOB result shrinks as the number of trees grows; that is the double-check of stability the handout asks for.
How another course on this site treats the same topic. Harvard CS181 HW4: Decision Trees, Random Forests, and Mixture of Experts.
Next lecture. Techniques Lecture 11: Gradient Boosted Decision Trees replaces this lecture's bagging with boosting: the trees no longer grow independently, and each one tries to fix the mistakes the earlier trees left behind.
Course video sources
Original videos: Random Forest Algorithm, Out-Of-Bag Estimate, Feature Selection, Random Forest in Action
Checked: 2026-10-13. The video IDs, titles, and lengths were taken from the official playlist on that day; the videos have no caption track on YouTube, and what this article reports from the lecture comes from transcripts made for it.
Update Log
- 2026-10-13: The series now has one article per lecture; this lecture is a newly split-out article, written from the handout and the video transcripts.
References
- Techniques Lecture 10 handout, 210_handout.pdf: the main source for this article. The definitions and derivations in the four sections, the four Fun Time questions, the demonstration figures on pages 17 to 19, and the KDD Cup experience on page 20 all come from this handout.
- Machine Learning Techniques YouTube playlist: the IDs and titles of the four videos; what the text reports as said "in the lecture" is paraphrased from machine transcripts of these four videos.
- Hsuan-Tien Lin > MOOCs: the official entry for handouts and recordings.
- Machine Learning, Fall 2024 course page: the corresponding week, the 210u slides, and the further reading list.
- Machine Learning, Fall 2026 course page: the corresponding week.
- Fall 2024 Homework 7 (hw7.pdf): the content of Q1, and the basis for saying this assignment has no problem specific to random forests.
- Breiman, Random Forests: further reading listed on the course page, and the source of what the handout calls original RF.
- Learning from Data textbook website: the course's assigned textbook; this lecture has no corresponding chapter.
- Reading NTU Hsuan-Tien Lin Machine Learning Foundations & Techniques: Course Overview: where this lecture sits in the whole course and the reading routes.
Loading...