Intermediate: machine learning · k-NN, decision trees and ensembles · topic 35 of 62 · 30 min
Random forests and bagging
Explanation
The wisdom of crowds
Ask one person to guess the weight of a pumpkin at a village fair and they may be far off. Ask 500 people and average their guesses, and the result is often surprisingly close, because individual errors point in different directions and cancel. A random forest applies this to trees: many slightly different, imperfect trees vote together.
Bagging: bootstrap aggregating
A bootstrap sample is drawn from the training data with replacement: pick a random row, put it back, pick again, until you have as many rows as the original. Some rows appear twice or more, and about 37% do not appear at all. Train one tree on each bootstrap sample, then aggregate: majority vote for classification, average for regression. This is bagging, and it mainly reduces variance (overfitting).
import random
rng = random.Random(0)
rows = list(range(10))
sample = [rng.choice(rows) for _ in rows]
print(sorted(sample))
print(len(set(sample)), "distinct rows out of 10")The extra randomness: feature subsets
If one feature is very strong, every bagged tree would split on it first and the trees would look alike, so their errors would not cancel. A random forest also picks a random subset of features at each split (often √(number of features) for classification). This makes the trees more different from each other, which makes the vote stronger.
Out-of-bag (OOB) error
Each tree never saw its out-of-bag rows, so they can be used to test it. Combining these gives the OOB score, a free estimate of test performance without a separate validation set. In scikit-learn, pass oob_score=True.
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=300, max_features="sqrt", oob_score=True, n_jobs=-1, random_state=0)
forest.fit(X_train, y_train)
print(round(forest.oob_score_, 3))
print(sorted(zip(forest.feature_importances_, X_train.columns), reverse=True)[:5])Feature importance, with a warning
Forests report how much each feature reduced impurity across all trees. This is handy for a first look, but it favours features with many possible split points (like ids or continuous numbers) and can split credit between correlated features. Permutation importance (topic 5) is usually more trustworthy.
Strengths and weaknesses
- Strengths: accurate out of the box, hard to badly overfit by adding trees, little tuning, handles mixed feature types.
- Weaknesses: slower and larger than one tree, harder to explain than a single tree, cannot extrapolate (it averages trees).
Common mistakes
- Thinking more trees cause overfitting. More trees mostly just cost time; the score levels off.
- Treating impurity-based importance as causal. It shows what the model used, not what causes the outcome.
- Including an id column. The forest may find accidental patterns in it.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Random forests and bagging · 1/6
A random forest is a crowd of decision trees that vote together.
Prefer a video by a teacher? Find free videos on “random forest explained bagging bootstrap out of bag” on YouTube ↗
In real life: Predicting which shipments will be delayed
A logistics company predicts delayed parcels using features like origin hub, destination pin-code zone, weight, day of week and weather alerts. A random forest with a few hundred trees beat both a single tree and logistic regression, needed almost no tuning, and its OOB score matched the later test score closely. The operations team uses its daily risk scores to re-route parcels before delays happen.
Practice (0/2 done)
Write forest_vote(tree_preds) where tree_preds is a list of lists: tree_preds[t][i] is tree t's predicted label for example i. Return one label per example: the majority vote across trees. On a tie, return the smallest label (sorted order). Assume at least one tree.
Write bootstrap(n, seed) that returns a bootstrap sample of the indices 0..n−1: a list of n indices, each chosen with rng.randrange(n), where rng = random.Random(seed). Also write oob(n, sample) that returns the sorted list of indices that are NOT in the sample (out-of-bag).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Gradient boostingk-NN, decision trees and ensembles · same module
- Backtracking: subsets and permutationsData Structures and Algorithms (DSA) for interviews · Recursion and backtracking
- Knapsack problemsData Structures and Algorithms (DSA) for interviews · Dynamic programming
- Bag of words, TF-IDF and text classificationNLP, embeddings and large language models
- Cross-validation and tuning hyperparametersEvaluating models
- Train, validation and test setsEvaluating models
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is a bootstrap sample?
Answer: Rows drawn at random WITH replacement, as many as the original
Sampling with replacement means repeats and left-out rows.
Why do random forests choose random feature subsets at each split?
Answer: To make the trees different from each other so their errors cancel
Diverse trees give a stronger combined vote.
What is the out-of-bag score?
Answer: A test-like score computed on rows each tree did not see
It is a built-in validation estimate.
Bagging mainly reduces…
Answer: Variance (overfitting)
Averaging many high-variance trees smooths their noise.
Adding more trees to a random forest usually…
Answer: Improves or levels off the score, at the cost of more time
Beyond a point, extra trees mostly cost compute.
Do decision trees need feature scaling?Related
Answer: No; splits compare one feature at a time with a threshold
A threshold question works the same whatever the units.
From Decision trees
Features are salary in rupees and age in years, unscaled. What goes wrong in k-NN?Related
Answer: Distance is dominated by salary, so age is almost ignored
Large-valued features swamp the distance. Scale first.
From k-nearest neighbours
In subsets with duplicates, why is the skip test i > start and not i > 0?Related
Answer: i > 0 would also skip the second 2 when going deeper, losing subsets such as [2, 2]
Only repeats at the SAME level are duplicates. Deeper levels start at start = i + 1 and may use the equal value once.
How does boosting differ from a random forest?Related
Answer: Boosting builds trees in sequence, each correcting earlier errors; forests build independent trees and average
Sequential correction versus parallel averaging.
From Gradient boosting
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “k-NN, decision trees and ensembles” before its exam: Gradient boosting, Choosing and explaining a model.
- Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.