Slides · Trees, ensembles and classical models
Decision trees, random forests and gradient boosting
1 / 31
Trees, forests and boosting
One flexible model with a flaw, and two ways to turn the flaw into strength: average many trees, or add small trees one at a time.
Concept
Why this is worth 80 minutes
- Most business data is a table, and tree ensembles are a strong default for tables.
- Knowing the mechanism tells you which knob to turn: more trees will not fix a forest whose trees agree, and more boosting rounds can hurt.
- A common interview topic (common industry pattern).
Four things you will be able to do:
- Compute a split gain by hand and control a tree’s overfitting.
- Use the variance formula for correlated predictors to explain bagging and forests.
- Explain gradient boosting as stagewise fitting of the negative gradient.
- Use trees well on tabular data: importance, missing values, categoricals, extrapolation.
Math
How a tree picks a split
Gini=1−k∑pk2,Entropy=−k∑pklog2pkgain=I(parent)−c∑nncI(c)- A pure node scores 0; a 50/50 node scores 0.5 (Gini) or 1 bit (entropy).
- Try every feature and threshold; keep the largest gain. Regression trees use the variance of the targets.
- Entropy as the criterion is equivalent to minimising the log loss.
Worked example
Worked example: two splits by hand
| Split | Children | Child Gini | Gini gain | Entropy gain |
|---|---|---|---|---|
| (5+, 5-) | (4+, 1-) and (1+, 4-) | 0.32 and 0.32 | 0.18 | 0.2781 |
| (6+, 4-) | (5+, 0-) and (1+, 4-) | 0 and 0.32 | 0.32 | 0.6100 |
- Parent Gini 0.5 and 0.48. Weighted children: 0.32 and 0.5 x 0.32 = 0.16.
- Both criteria rank these the same way.
- For 0/1 labels the Gini is twice the variance, so squared-error splitting finds the same cut.
Check yourself
Check: a split that does nothing
A node has 90 negative and 10 positive rows. What is its Gini, and would a split into (45 negative, 5 positive) and (45 negative, 5 positive) help?
Answer
Gini is 1−(0.92+0.12)=0.18. Both children have the same mix, so each has Gini 0.18 and the gain is 0.18−0.18=0. A split only helps if it separates the classes, not if it divides the rows evenly.
Concept
Greedy, and what it misses
- Finding an optimal tree is NP-complete, so trees choose the best split now, with no look-ahead.
- On XOR (label 1 when two binary features differ) any single split leaves both children 50/50: gain exactly 0. Two levels of splits are perfect.
- A learner that demands positive gain stops at the root.
- Splits compare one feature with a threshold: boundaries are axis-aligned staircases, and leaves hold constants.
Worked example
Overfitting, measured
Noisy circle, 15% of labels flipped, so no model beats 0.85. Medians over 20 datasets of 200 rows:
| Setting | Train | Validation |
|---|---|---|
max_depth 1 | 0.603 | 0.563 |
max_depth 4 | 0.850 | 0.763 |
max_depth 8 | 0.958 | 0.736 |
| No limit | 1.000 | 0.715 |
min_samples_leaf 10 | 0.843 | 0.778 |
min_samples_leaf 20 | 0.815 | 0.780 |
- Train above the 0.85 ceiling means the tree learned flipped labels.
Compare
Controls on a tree
| Control | What it does | Watch for |
|---|---|---|
max_depth | Caps the number of questions in a row | Too low underfits |
min_samples_leaf | Every leaf keeps a minimum of rows | Starting value 5; tune it |
| Cost-complexity pruning | Minimises impurity + alpha x leaves | Pick ccp_alpha on validation |
- Pick every control on validation data, never on training accuracy.
- A small change in the data can give a completely different tree: that variance is what bagging averages away.
Check yourself
Check: read the gap
A tree scores 0.99 on training and 0.70 on validation. The source has about 5% label noise. What does the training score tell you, and what do you try first?
Answer
With 5% wrong labels nothing can score near 0.99 on fresh data, so the tree has memorised noise. Limit depth or leaf size (or prune) and choose the setting by validation score.
Diagram
Bagging: average deep trees
Math
The variance of an average of correlated trees
Var(B1b∑Tb)=B2Bσ2+B(B−1)ρσ2=ρσ2+B1−ρσ2- More trees shrink the second term only.
- ρσ2 is a floor: independent trees (ρ=0) give σ2/B, identical trees (ρ=1) gain nothing.
- Make the trees less alike to lower the floor.
- Checked exactly (ρ=1/2, B=4: 5/8) and by simulation in the script.
Worked example
Measured on real trees
30 training sets of 200 rows, 100 trees each, variance of the prediction at 40 points:
| Ensemble | σ2 | ρ | Variance at 1, 5, 25, 100 trees | Squared bias |
|---|---|---|---|---|
| Bagging, 6 features | 2.284 | 0.127 | 2.376, 0.678, 0.375, 0.310 | 0.273 |
| Forest, 2 of 6 | 2.891 | 0.056 | 2.861, 0.644, 0.277, 0.189 | 0.467 |
- ρ is implied at 100 trees. For bagging the formula then gives 0.689 and 0.370 at 5 and 25 trees, within about 0.011 of the measurements; the forest at 5 trees is less close (0.708 against 0.644).
- The forest lowered the floor (0.162 against 0.290) but each tree got worse.
Compare
Random forests: what feature subsampling trades
| Bagging | Random forest | |
|---|---|---|
| Features per split | All | A random subset (sqrt for classification by default) |
| Correlation between trees | Higher | Lower |
| Each tree | Stronger | Weaker, more bias |
| Tuning | Few knobs | max_features matters |
- In this example bias plus variance was 0.583 for bagging and 0.656 for the forest: decorrelation did not pay where every feature carries signal.
Concept
Out-of-bag error
- A row is missed by one bootstrap sample with probability (1−1/n)n: 0.3487 at n = 10, 0.3660 at 100, 0.3679 in the limit (1/e).
- Predict each row with only the trees that never saw it: a validation estimate with nothing held out (
oob_score=True). - On the noisy circle: OOB 0.780 against 0.778 on fresh data, but a median per-dataset gap of 0.025.
- If you tune on the OOB score, it is no longer an unbiased estimate.
Check yourself
Check: use the formula
Trees have variance 1 and pairwise correlation 0.5. What is the variance of the average of 10 trees, and the limit as B grows?
Answer
0.5⋅1+0.5⋅1/10=0.55, and the limit is 0.5. Half of the variance is shared, so only decorrelating the trees (or lowering each tree’s variance) helps.
Math
Boosting: fit what is still wrong
Fm(x)=Fm−1(x)+ηhm(x),hm fitted to −∂F∂ℓ(y,F)Fm−1- Squared error: the negative gradient is the residual y−F.
- Log loss with p=σ(F): the derivative is p−y, so the target is y−p (checked numerically: -0.331812 for y = 1, F = 0.7).
- Gradient descent where the parameters are the predictions; the tree makes the steps work on new rows.
- XGBoost adds one tree at a time in the same way, fixing what has been learned.
Source[3] Introduction to Boosted Trees (XGBoost documentation)
Worked example
Worked example: two rounds, exact
x=1..6, y=(1,3,2,6,7,9), stumps, η=1/2. Start at the mean 14/3, MSE 74/9 = 8.22.
| Round | Split | Leaves | Predictions | MSE |
|---|---|---|---|---|
| 1 | After x = 3 | -8/3 and 8/3 | 10/3, 10/3, 10/3, 6, 6, 6 | 26/9 = 2.89 |
| 2 | After x = 4 | -1 and 2 | 17/6 x3, 11/2, 7, 7 | 25/18 = 1.39 |
- A leaf is the mean residual of its rows; the step adds only half of it.
- Round 2 picks a different split because round 1 already moved the errors.
Worked example
Learning rate, rounds and depth
Six-feature linear source, noise variance 1 (floor 1.0), 200 rows, median of 6 datasets:
| Rate | Depth | Best validation MSE | At round | After 800 |
|---|---|---|---|---|
| 1.0 | 1 | 1.709 | about 51 | 1.958 |
| 0.1 | 1 | 1.274 | about 251 | 1.356 |
| 0.01 | 1 | 1.665 | 800 (still falling) | 1.665 |
| 0.1 | 3 | 1.489 | about 73 | 1.566 |
- Rounds are regularisation: stop by early stopping on validation data.
- Smaller rates need more rounds: 0.01 is still falling at the 800-round cap and has not caught up with 0.1.
Check yourself
Check: a rate on its own
A colleague compares learning rate 0.01 and 0.1 after exactly 100 rounds and concludes that 0.01 is worse. What did the comparison miss?
Answer
The two rates need different numbers of rounds. After 100 rounds the small rate has barely started (in the lesson it was still improving at 800). Compare each at its own best round, chosen by early stopping on validation data.
Compare
XGBoost and LightGBM: documented features
| Documented | XGBoost | LightGBM |
|---|---|---|
| Binning | tree_method auto is the same as hist, max_bin 256 | Histogram-based algorithms |
| Growth | grow_policy depthwise by default, lossguide available | Leaf-wise: split the leaf with the largest loss reduction |
| Objective | Second-order expansion, penalty on leaf count and weights | Not covered here |
| Complexity controls | max_depth 6, min_child_weight, gamma | num_leaves, min_data_in_leaf, max_depth |
| Other regularisers | subsample, colsample_bytree, lambda, alpha | feature_fraction, bagging_fraction, lambda_l1, lambda_l2 |
- Leaf-wise growth may over-fit when data is small; keep
num_leavessmall. - Scikit-learn’s
HistGradientBoostingbins into up to 255 bins plus one for missing values. - Sparsity-aware algorithm for sparse data (XGBoost paper abstract). CatBoost was not covered: its documentation was not opened.
Sources[3] Introduction to Boosted Trees (XGBoost documentation)[4] XGBoost Parameters (XGBoost documentation)[5] XGBoost: A Scalable Tree Boosting System[6] Features (LightGBM documentation)[7] Parameters Tuning (LightGBM documentation)[8] HistGradientBoostingClassifier (scikit-learn API reference)
Concept
Do trees really beat neural nets on tables?
- 2022 benchmark of 45 tabular datasets: heterogeneous columns, at least 3,000 rows, training sets truncated to 10,000.
- In 2022 the authors found tree-based models such as XGBoost and random forests remained state of the art on that medium-sized data, even without counting speed.
- Their reasons: MLPs prefer overly smooth functions, are less robust to uninformative features, and tabular data is not rotation invariant.
- Since then (Nature, 2025) the TabPFN authors report a pretrained tabular foundation model beating strong baselines on datasets up to about 10,000 samples. These are their claims, not tested here.
Sources[9] Why do tree-based models still outperform deep learning on tabular data?[10] Accurate predictions on small data with a tabular foundation model
Worked example
Where trees lose, and where they win
Validation MSE, median of 6 datasets of 200 rows:
| Model | Linear signal (floor 1.0) | Steps and sine (floor 0.25) |
|---|---|---|
| Least squares | 1.050 | 2.807 |
| One deep tree | 3.463 | 0.955 |
| Bagged trees | 1.686 | 0.625 |
| Forest, 2 of 6 | 1.639 | 1.128 |
| Boosting | 1.516 | 0.475 |
- A staircase approximating a straight line wastes data.
- Trees cannot extrapolate: trained on y = 2x for x in [0, 10], a tree says 20.0 at x = 15 and a line says 30.0.
Worked example
Feature importance: two measures, two answers
One binary signal and two noise columns. Medians over 20 datasets:
| Column | Impurity share (training) | Validation drop when permuted |
|---|---|---|
| Signal | 0.251 | 0.182 |
| Noise A | 0.371 | 0.001 |
| Noise B | 0.377 | -0.001 |
- Impurity importance favours many-valued features and comes from training statistics.
- With an exact copy of the signal (a new forest), the drop for each copy shrinks (0.134 and 0.092); permuting both gives 0.237, close to their sum. Permute groups together, or keep one feature per cluster.
Sources[11] Permutation feature importance (scikit-learn user guide)[2] Ensembles: Gradient boosting, random forests, bagging, voting, stacking (scikit-learn user guide)
Compare
Missing values and categoricals
| Problem | Poor choice | Better choice |
|---|---|---|
| Missing values carry signal | Mean fill: 0.656 accuracy | Learn a side for missing: 0.693 |
| 50,000-level category | One-hot: 50,000 sparse columns | Native categorical support or cross-fitted target encoding |
| Target encoding | fit(X, y).transform(X) on training data | fit_transform(X, y), which cross-fits |
- No library learns a side? An “is missing” indicator column is a common workaround (judgment).
- Trees need no scaling, because a threshold moves with the feature.
Sources[12] Frequently Asked Questions (XGBoost documentation)[1] Decision Trees (scikit-learn user guide)[13] Preprocessing data: encoding categorical features and the target encoder (scikit-learn user guide)
Check yourself
Check: two correlated features
Two features are near copies of each other. Permuted one at a time on validation data, each shows only a small drop. Can you conclude that neither matters?
Answer
No. When one is shuffled the model still reads the other, so each looks less important than the pair is. Permute the pair together to see their joint importance.
Diagram
A defensible default for a table
Code
Two loops in a few lines
Python
import random
def bootstrap(n, rng):
"""Bagging: n row indices drawn with replacement; about 63.2% are distinct."""
return [rng.randrange(n) for _ in range(n)]
def boost(fit_tree, predict, X, y, lr, rounds):
"""Gradient boosting for squared error."""
f0 = sum(y) / len(y)
F, trees = [f0] * len(y), []
for _ in range(rounds):
tree = fit_tree(X, [t - p for t, p in zip(y, F)]) # fit the residuals
F = [p + lr * predict(tree, x) for p, x in zip(F, X)]
trees.append(tree)
return f0, trees- Bagging draws the data; boosting changes the target. The full script is in the lesson.
Summary
Recap
- A split is the question with the largest impurity drop (Gini gain 0.18 in the worked example); greedy, so XOR is missed; unlimited trees memorise noise, so limit them by validation.
- Averaged trees have variance ρσ2+(1−ρ)σ2/B: more trees remove only the second term, feature subsampling lowers ρ at a cost, and about 36.8% of rows are out of bag.
- Gradient boosting fits the negative gradient of the loss (residual, or y−p); rounds and learning rate trade off and are set by early stopping.
- Trees are a strong default on medium-sized tabular data, not a law: no extrapolation, impurity importance misleads, missing values and categoricals need the right encoding.
References
References & Sources (1 of 3)
Decision Trees (scikit-learn user guide) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/tree.html
Used for Gini (sum of p(1-p)) and entropy criteria, entropy as equivalent to minimising log loss; learning an optimal tree is NP-complete so practical algorithms are greedy; trees overfit and need pruning, a minimum leaf size or a maximum depth, with min_samples_leaf=5 suggested as a starting value; small data changes can give a completely different tree; predictions are piecewise constant and not good at extrapolation; XOR, parity and multiplexer problems are hard to express; cost-complexity pruning minimises R(T) + alpha|T| and removes the weakest link until the effective alpha exceeds ccp_alpha; built-in support for missing values, which the splitter sends all left or all right when evaluating a threshold.
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/ensemble.html
Used for Bootstrap samples drawn with replacement; bagging works best with strong, complex models and boosting with weak ones such as shallow trees; random forest randomness aims to decrease variance, sometimes at the cost of a slight increase in bias; max_features defaults (all features for regression, sqrt for classification); oob_score=True; impurity-based importances are computed from training statistics and favour high-cardinality features; the learning rate interacts with n_estimators, small values favour better test error, learning_rate <= 0.1 with early stopping is recommended; subsample 0.5 is typical and helps only with shrinkage; histogram-based boosting can be orders of magnitude faster than GradientBoosting above tens of thousands of samples (binning makes split points approximate on small data), learns the side for missing values from the potential gain, and has native categorical support (cardinality below max_bins) that is often better than one-hot encoding.
Introduction to Boosted Trees (XGBoost documentation) (opens in a new tab)
XGBoost2026Documentation
https://xgboost.readthedocs.io/en/stable/tutorials/model.html
Used for Additive training that fixes what has been learned and adds one tree at a time; a second-order Taylor expansion of the loss with gradient g_i and second derivative h_i; regularisation gamma T + (1/2) lambda sum w_j^2.
XGBoost Parameters (XGBoost documentation) (opens in a new tab)
XGBoost2026Documentation
https://xgboost.readthedocs.io/en/stable/parameter.html
Used for Defaults: tree_method auto is the same as hist, grow_policy depthwise (lossguide available), eta 0.3, max_depth 6, max_bin 256; parameters min_child_weight, subsample, colsample_bytree, lambda (L2) and alpha (L1).
XGBoost: A Scalable Tree Boosting System (opens in a new tab)
Tianqi Chen, Carlos Guestrin2016arXiv:1603.02754 (KDD 2016)Paper
https://arxiv.org/abs/1603.02754
Used for XGBoost introduces a sparsity-aware algorithm for sparse data and a weighted quantile sketch (abstract page only).
References
References & Sources (2 of 3)
Features (LightGBM documentation) (opens in a new tab)
Microsoft LightGBM2026Documentation
https://lightgbm.readthedocs.io/en/latest/Features.html
Used for Histogram-based algorithms bucket continuous values into bins; leaf-wise (best-first) growth picks the leaf with the largest loss reduction, may over-fit when the data is small, and max_depth can limit depth; categorical features are split by partitioning the categories into two subsets in about O(k log k), and one-hot encoding is described as suboptimal for tree learners.
Parameters Tuning (LightGBM documentation) (opens in a new tab)
Microsoft LightGBM2026Documentation
https://lightgbm.readthedocs.io/en/latest/Parameters-Tuning.html
Used for To deal with over-fitting: small num_leaves (smaller than 2^max_depth), min_data_in_leaf, max_depth, feature_fraction, bagging_fraction with bagging_freq, and lambda_l1, lambda_l2 and min_gain_to_split; small learning_rate with large num_iterations for accuracy.
HistGradientBoostingClassifier (scikit-learn API reference) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostingClassifier.html
Used for HistGradientBoostingClassifier max_bins is the number of bins for non-missing values (default and maximum 255), with one more bin always reserved for missing values.
Why do tree-based models still outperform deep learning on tabular data? (opens in a new tab)
Leo Grinsztajn, Edouard Oyallon, Gael Varoquaux2022arXiv:2207.08815Preprint
https://arxiv.org/abs/2207.08815
Used for A benchmark of 45 tabular datasets (heterogeneous columns, at least 3,000 rows and 4 features, training sets truncated to 10,000 rows) on which tree-based models remain state of the art for medium-sized data; the three explanations (neural networks biased to overly smooth solutions, less robust to uninformative features, rotation invariance not desirable); the stated limits (very small and very large datasets not evaluated, timing not rigorous). Read from the arXiv abstract page and HTML version.
Accurate predictions on small data with a tabular foundation model (opens in a new tab)
Noah Hollmann, Samuel Muller, Lennart Purucker, Arjun Krishnakumar, et al.2025Nature 637(8045), 319-326Paper
https://pubmed.ncbi.nlm.nih.gov/39780007/
Used for TabPFN, a pretrained tabular foundation model, is reported (by its authors, two of whom are affiliated with a company developing such models) to outperform previous methods including gradient-boosted trees on datasets of up to about 10,000 samples. Abstract page only.
References
References & Sources (3 of 3)
Permutation feature importance (scikit-learn user guide) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/permutation_importance.html
Used for Permutation importance shuffles one feature and measures the score drop; it can be computed on held-out data, unlike impurity importance which is strongly biased toward high-cardinality features and can credit non-predictive features when the model overfits; correlated features can both receive lower importance because the model still has access to the other, and the suggestion to cluster correlated features and keep one per cluster.
Frequently Asked Questions (XGBoost documentation) (opens in a new tab)
XGBoost2026Documentation
https://xgboost.readthedocs.io/en/stable/faq.html
Used for In tree algorithms, branch directions for missing values are learned during training.
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/preprocessing.html
Used for TargetEncoder's fit_transform uses cross fitting to prevent target leakage, with encodings shrunk toward the global mean (smooth parameter); fit(X, y).transform(X) does not equal fit_transform(X, y) and is discouraged on training data.
Keys: ← → move, Home End first and last, F full screen.