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).
- 01Start at the root with all training data
- 02Find the feature and split point that best reduces impurity
- 03Split the data into two child nodes
- 04Repeat recursively until a stopping criterion (max depth, min samples)
- 05Each leaf predicts the majority class (classification) or mean value (regression)
Impurity measures decide what "best separates" means:
| Measure | Formula | Use |
|---|---|---|
| Gini impurity | 1 − Σ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:
- Bootstrap aggregating (bagging): sample N data points with replacement from the training set
- Random feature subsets: at each split, consider only a random subset of features (typically √p for classification, p/3 for regression)
- 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.
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:
- 01Start with a simple prediction (e.g., the mean of y)
- 02Compute the residuals (errors) of the current ensemble
- 03Fit a small tree to predict the residuals
- 04Add the new tree to the ensemble (scaled by learning rate)
- 05Repeat for T rounds
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:
| Library | Key innovation | Best for |
|---|---|---|
| XGBoost | Regularized objective, sparse-aware splits, column block structure | General tabular, Kaggle |
| LightGBM | Leaf-wise growth, GOSS sampling, exclusive feature bundling | Large datasets, speed |
| CatBoost | Ordered boosting (reduces target leakage), native categorical handling | Data 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.
| Method | What it measures |
|---|---|
| Split-based importance | How much each feature reduces impurity across all splits |
| Permutation importance | How much accuracy drops when a feature's values are shuffled |
| SHAP values | Each 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#
| Criterion | Trees/Ensembles | Neural networks |
|---|---|---|
| Tabular data | Usually better | Need careful tuning |
| Images, text, audio | Not applicable | Dominant |
| Interpretability | High (feature importance, individual trees) | Low (black box) |
| Data efficiency | Work well on small datasets | Hungry for data |
| Feature engineering | Less needed (handle nonlinearity, interactions) | Can learn features, but need architecture design |
| Training speed | Fast (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.