Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 91/ 160
05. Classical Machine Learning

Bagging & Random Forests

Reduce variance by averaging bootstrapped trees with feature randomness.

IntermediateBootstrap · Feature Randomness3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A random forest builds lots of slightly different decision trees and lets them vote, which gives steadier answers than any single tree.

Think of it like…

Asking a committee of independent experts rather than one: if they each make different random mistakes, the average is far better, but if they all read the same briefing and make the same mistakes, adding more experts barely helps, so you give each one a different slice of the information.

Where you’ve seen it

On a 5,000-row churn dataset a single unpruned tree gets 71% test accuracy, bagging 200 trees reaches 80% and a random forest with max_features='sqrt' reaches 83%. The variance math shows why: for B trees each with variance σ² and pairwise correlation ρ, the averaged variance is ρσ² + (1 − ρ)σ² / B. With σ² = 1 and ρ = 0.5, 100 trees give 0.5 + 0.005 = 0.505, so the correlation floor dominates; reducing ρ to 0.2 with feature subsampling gives 0.2 + 0.008 = 0.208, less than half. A bootstrap leaves out (1 − 1/n)ⁿ ≈ e⁻¹ = 36.8% of rows, so with 1,000 rows each tree's OOB set holds about 368 rows, and each row is OOB for about 0.368 × 300 = 110 of 300 trees, enough to compute an OOB prediction per row and an OOB accuracy of 82.6% without a separate validation set. Permutation importance on the validation set shows support_tickets and tenure_months matter most, while the default impurity importance had wrongly ranked a high-cardinality ID-like column high.

Words you’ll hear

Bootstrap sample
A sample of n rows drawn with replacement; about 63% of unique rows appear.
Out-of-bag (OOB) estimate
Validation using, for each row, only trees that didn't train on it.
max_features
Number of features considered at each split; lower values decorrelate trees.
Permutation importance
Drop in score when a feature's values are shuffled.

Visual diagram

Loading interactive diagram

Theory & deep dive

Why averaging works and why randomness helps

Averaging B identically distributed estimates, each with variance σ² and pairwise correlation ρ, gives variance ρσ² + (1 − ρ)σ² / B. As B grows the second term vanishes but the first term does not: the correlation between trees puts a floor on the variance. Bagging trees trained on different bootstrap samples reduces ρ somewhat, but strong features still dominate every tree's early splits, leaving ρ high (0.5 in the example, floor 0.5). The random forest's key idea is feature subsampling at every split (max_features='sqrt' for classification, about p/3 for regression), which forces trees to use different features and lowers ρ (0.2 in the example, floor 0.2). Bias rises slightly because each split sees fewer features, but the variance reduction usually dominates.

Because averaging attacks variance, forests use deep, unpruned trees (low bias, high variance individually). Bootstrap sampling means each tree trains on a random subset with about 63.2% unique rows, since the chance a given row is never drawn in n draws is (1 − 1/n)ⁿ → e⁻¹ = 36.8%. Those out-of-bag rows allow an unbiased internal estimate: for each row, predict using only the trees where it was OOB (about 110 of 300 trees) and compare with the label. RandomForestClassifier(oob_score=True) reports it, so you can often skip a separate validation set during tuning (though a final test set is still needed). Extra-trees (ExtraTreesClassifier) go further by choosing random thresholds, decorrelating more and training faster.

Variance of the average

σ² = 1, B = 100. Bagging with ρ = 0.5: 0.5 + 0.5/100 = 0.505. Random forest with ρ = 0.2: 0.2 + 0.8/100 = 0.208. Going from 100 to 500 trees at ρ = 0.2 only improves to 0.2 + 0.0016 = 0.2016: more trees help little once the correlation term dominates.

Key takeaway: Averaging cuts only the uncorrelated part of variance, so feature randomness (lower ρ) is what makes forests beat plain bagging.

Tuning, interpretation and limits

Forests have robust defaults. Key hyperparameters: n_estimators (200 to 1,000; more is never harmful beyond cost, with diminishing returns), max_features (√p classification; try values from 0.1p to 0.5p for regression or many noisy features), min_samples_leaf (1 to 5, raise to smooth predictions and shrink the model) and max_depth (usually unrestricted; limit for speed or memory), plus class_weight="balanced_subsample" for imbalanced classes and n_jobs=-1 to train trees in parallel. Tune with cross-validation or OOB scores (RandomizedSearchCV), and calibrate probabilities if you need them (forest votes tend to be under-confident near 0 and 1).

For interpretation, the default impurity-based importance (mean decrease in impurity) is biased toward continuous or high-cardinality features and computed on training data; prefer permutation importance on held-out data (sklearn.inspection.permutation_importance) and SHAP for local explanations. Limits: large models (hundreds of deep trees take memory and are slower to serve), no extrapolation beyond the training range (a regression forest predicts within the range of seen targets), piecewise-constant predictions, difficulty with very sparse high-dimensional data such as raw text and slightly weaker accuracy than well-tuned gradient boosting on many tabular benchmarks. Forests remain an excellent first model, a strong baseline for feature work and a reliable choice when you need robustness with little tuning.

Importance pitfalls

A random numeric ID column with 5,000 unique values ranks 4th by impurity importance because it offers many split points, but shuffling it on the validation set changes accuracy by 0.0 points, exposing it as noise; support_tickets loses 4.1 points when shuffled.

Key takeaway: Tune max_features and leaf size, use OOB or CV for validation and permutation importance for trustworthy rankings.

How it works, step by step

Step 1 of 4
Analyst

1. Start with defaults

Fit a random forest with 300 trees, sqrt features and unpruned depth; no scaling is needed.

n_estimators=300 · max_features='sqrt'
Key numbers at this step
Parallel
n_jobs=-1

When to use it & trade-offs

What it is

Bagging (bootstrap aggregating) trains many models on different bootstrap samples (rows drawn with replacement) and averages (regression) or votes (classification) their predictions, which reduces variance without much extra bias. A random forest is bagging applied to deep decision trees with one extra twist: at each split only a random subset of features (max_features, typically √p for classification) is considered, which decorrelates the trees so that averaging helps more. Each tree sees about 63% of the unique rows, leaving the other ~37% out-of-bag (OOB), which gives a free validation estimate. Forests need little tuning, handle mixed data and are a strong default for tabular problems.

Why it matters: A single deep tree has low bias but high variance: retrain on slightly different data and the tree changes. Averaging many such trees keeps the low bias and shrinks the variance, which is why a forest usually beats any individual tree and is robust to noise and outliers. Understanding why feature randomness matters (correlation between trees limits how much averaging can help) is a favourite interview topic and explains how forests, extra-trees and boosting differ.

When to reach for it

  • Strong default for tabular classification and regression
  • Quick feature-importance screening
  • Noisy data with outliers

When to avoid or be careful

  • Interpreting impurity importance of high-cardinality features
  • Expecting extrapolation outside the training range
  • Serving huge forests where latency is tight without pruning

Ensembles of trees

Bagging of trees
Best for: Reducing variance of unstable learners

Strengths: Simple; parallel; OOB estimate.

Watch out: Trees remain correlated.

Random forest
Best for: Strong, low-tuning tabular baselines

Strengths: Decorrelated trees; robust to noise and outliers.

Watch out: Large models; no extrapolation.

Gradient boosting
Best for: Maximum accuracy with tuning

Strengths: Reduces bias; often top accuracy.

Watch out: More tuning; sensitive to noise and overfitting.

Interview signals & numbers to know

When this topic comes up

  • “Single tree is unstable”
  • Out-of-bag error
  • max_features and tree correlation
  • Permutation importance
  • Bootstrap aggregating

Benchmarks & rules of thumb

63.2% / 36.8% -
in-bag and out-of-bag shares of rows per tree
ρσ² + (1 − ρ)σ²/B -
variance of an average of B correlated trees
√p -
default features per split for classification

Common mistakes & follow-ups

Common interview mistakes

  • Using more trees to fix a correlation problem.
  • Reading default importances as causal or reliable.
  • Forgetting class weights on imbalanced data.

Likely interviewer follow-ups

  • Why does a random forest decorrelate trees?
  • What is the OOB score and why is it useful?
  • When would you prefer gradient boosting over a random forest?
Interview tip: State the variance formula and note that correlation sets the floor. It explains why feature subsampling, not just more trees, drives the gains.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Bagging & Random Forests with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Decision Trees (CART, Gini, Entropy)
Next topic
Boosting Intuition (AdaBoost & Gradient Boosting)