Step 3 of 6

Decision trees, random forests & boosting

Tree-based models dominate tabular data. Understand splits, bagging, boosting (XGBoost, LightGBM), and why ensembles beat single models.

16 min read

Ask any data scientist what wins Kaggle competitions on tabular data, and the answer hasn't changed in a decade: gradient-boosted trees. While neural networks dominate text, images, and audio, tree-based ensembles remain the default for structured data - and understanding why teaches you the most important ensemble ideas in ML.

Decision trees - if-then machines#

A decision tree partitions the feature space with a sequence of yes/no questions. At each node, it picks the feature and threshold that best separates the data; at each leaf, it makes a prediction (the majority class, or the mean of training targets).

  1. 01Start at the root with all training data
  2. 02Find the feature and split point that best reduces impurity
  3. 03Split the data into two child nodes
  4. 04Repeat recursively until a stopping criterion (max depth, min samples)
  5. 05Each leaf predicts the majority class (classification) or mean value (regression)

Impurity measures decide what "best separates" means:

MeasureFormulaUse
Gini impurity1 − Σpᵢ²Classification (scikit-learn default)
Entropy−Σpᵢ log pᵢClassification (information gain)
MSE(1/n)Σ(yᵢ − ȳ)²Regression

A single decision tree is easy to interpret but has high variance - small changes in the training data produce very different trees. This is exactly the problem ensembles fix.

Gini impurity
Measures how often a randomly chosen element would be misclassified - 0 means pure (all one class), 0.5 means maximally mixed.
Entropy (information gain)
Measures the uncertainty in a node's class distribution - splits that reduce entropy the most are chosen first.
Ensemble
A model that combines predictions from multiple weaker models to produce a stronger, more reliable result.

Random forests - bagging many trees#

A random forest reduces variance by training many trees on random subsets of the data and averaging their predictions:

  1. Bootstrap aggregating (bagging): sample N data points with replacement from the training set
  2. Random feature subsets: at each split, consider only a random subset of features (typically √p for classification, p/3 for regression)
  3. Aggregate: average predictions (regression) or take a majority vote (classification)

The randomization ensures the trees are decorrelated - they make different errors on different examples, so averaging cancels out individual mistakes.

f^(x)=1B∑b=1Bfb(x)\hat{f}(x) = \frac{1}{B} \sum_{b=1}^{B} f_b(x)

Random forest prediction: the average (or vote) of B independently trained trees, each on a bootstrapped sample with random feature subsets.

Why it works: each tree has low bias (deep trees capture complex patterns) but high variance (sensitive to the exact training sample). Averaging many decorrelated high-variance estimators keeps the low bias while dramatically reducing variance.

Gradient boosting - learning from mistakes#

Where random forests train trees independently in parallel, gradient boosting trains them sequentially, each one correcting the errors of the ensemble so far:

  1. 01Start with a simple prediction (e.g., the mean of y)
  2. 02Compute the residuals (errors) of the current ensemble
  3. 03Fit a small tree to predict the residuals
  4. 04Add the new tree to the ensemble (scaled by learning rate)
  5. 05Repeat for T rounds
F(t)(x)=F(t−1)(x)+η⋅h(t)(x)F^{(t)}(x) = F^{(t-1)}(x) + \eta \cdot h^{(t)}(x)

Boosting: each new tree h(t) fits the gradient of the loss, moving the ensemble toward lower error.

Each tree is shallow (depth 3-8, typically) - individually weak, but their cumulative corrections produce a strong learner. The learning rate η (shrinkage) controls how much each tree contributes; smaller values require more trees but generalize better.

XGBoost, LightGBM, CatBoost#

The three major gradient boosting libraries:

LibraryKey innovationBest for
XGBoostRegularized objective, sparse-aware splits, column block structureGeneral tabular, Kaggle
LightGBMLeaf-wise growth, GOSS sampling, exclusive feature bundlingLarge datasets, speed
CatBoostOrdered boosting (reduces target leakage), native categorical handlingData with many categoricals

All three support GPU training, handle missing values natively, and include built-in feature importance. XGBoost and LightGBM are the workhorses of production tabular ML.

Feature importance#

Trees naturally measure how important each feature is: sum up the impurity reduction each feature provides across all splits and all trees.

MethodWhat it measures
Split-based importanceHow much each feature reduces impurity across all splits
Permutation importanceHow much accuracy drops when a feature's values are shuffled
SHAP valuesEach feature's marginal contribution to each prediction (theoretically grounded)

Permutation importance and SHAP are more reliable than split-based importance - split-based scores are biased toward high-cardinality features (features with many unique values get more opportunities to split).

SHAP values
Shapley Additive Explanations - assigns each feature a fair contribution score for a specific prediction, grounded in cooperative game theory.
Bagging
Bootstrap aggregating - trains models on random subsets of the data (with replacement) and averages them to reduce variance.
Boosting
Trains models sequentially, each one focusing on the mistakes of the previous ensemble - reduces bias.
High-cardinality feature
A feature with many distinct values (e.g. zip codes, user IDs) - requires special encoding and can bias split-based importance.

Trees vs. neural networks#

CriterionTrees/EnsemblesNeural networks
Tabular dataUsually betterNeed careful tuning
Images, text, audioNot applicableDominant
InterpretabilityHigh (feature importance, individual trees)Low (black box)
Data efficiencyWork well on small datasetsHungry for data
Feature engineeringLess needed (handle nonlinearity, interactions)Can learn features, but need architecture design
Training speedFast (minutes)Slow (hours to weeks)

Bagging reduces variance

Random forests average many independent high-variance trees. Each tree is deep and biased toward its bootstrap sample; the average isn't.

Boosting reduces bias

Gradient boosting fits residuals sequentially - each tree corrects the ensemble's remaining errors.

Trees handle messiness

Missing values, mixed feature types, nonlinear relationships, and feature interactions - all handled natively, no preprocessing.

Ensembles of ensembles

Competition-winning models often stack multiple boosting models with different hyperparameters. Stacking is meta-ensembling.

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.