Bagging and Random Forests

Averaging many decorrelated trees to cut variance, giving a robust, low-tuning model for tabular data.

Intermediate · about 5 hours · difficulty 2/5

Learn first: Decision Trees

A single tree is high variance: small data changes produce a very different tree. Bagging trains many trees on bootstrap samples and averages them. Random forests add random feature subsets at each split so trees disagree more, which makes the average even better.

Key hyperparameters

  • n_estimators: more trees rarely hurt, just cost time; a few hundred is typical.
  • max_features: features considered per split; the main decorrelation knob.
  • max_depth / min_samples_leaf: usually left fairly deep.
  • n_jobs=-1 to train in parallel.

Useful extras

  • Out-of-bag (OOB) score: each tree ignores about a third of the data, giving a free validation estimate.
  • Extra Trees: even more randomized splits, faster and sometimes better.
  • Permutation importance for trustworthy feature rankings.

When to use

Random forests are an excellent low-effort baseline: hard to badly misconfigure, robust to outliers and irrelevant features. They are usually beaten by well-tuned gradient boosting, and they cannot extrapolate beyond the target range seen in training.

Good enough to move on when you can explain why averaging decorrelated trees reduces variance and use the OOB score to sanity-check a model.

Key concepts

  • Bootstrap aggregation
  • Random feature subsets
  • Out-of-bag evaluation
  • Permutation importance
  • Extra Trees

Mini project

Train a random forest on the Kaggle House Prices dataset, compare OOB score with 5-fold CV score, and compare impurity-based and permutation feature importances.

Check yourself

Why does restricting max_features at each split usually improve a forest even though each tree gets worse?

Free resources