Slides · Trees, ensembles and classical models

Decision trees, random forests and gradient boosting

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:

  1. Compute a split gain by hand and control a tree’s overfitting.
  2. Use the variance formula for correlated predictors to explain bagging and forests.
  3. Explain gradient boosting as stagewise fitting of the negative gradient.
  4. Use trees well on tabular data: importance, missing values, categoricals, extrapolation.

Math

How a tree picks a split

Gini=1−∑kpk2,Entropy=−∑kpklog⁡2pk\text{Gini}=1-\sum_k p_k^2,\qquad \text{Entropy}=-\sum_k p_k\log_2 p_kgain=I(parent)−∑cncn I(c)\text{gain}=I(\text{parent})-\sum_{c}\frac{n_c}{n}\,I(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.

Source1 Decision Trees (scikit-learn user guide)

Worked example

Worked example: two splits by hand

SplitChildrenChild GiniGini gainEntropy gain
(5+, 5-)(4+, 1-) and (1+, 4-)0.32 and 0.320.180.2781
(6+, 4-)(5+, 0-) and (1+, 4-)0 and 0.320.320.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.181-(0.9^2+0.1^2)=0.18. Both children have the same mix, so each has Gini 0.18 and the gain is 0.18−0.18=00.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.

Source1 Decision Trees (scikit-learn user guide)

Worked example

Overfitting, measured

Noisy circle, 15% of labels flipped, so no model beats 0.85. Medians over 20 datasets of 200 rows:

SettingTrainValidation
max_depth 10.6030.563
max_depth 40.8500.763
max_depth 80.9580.736
No limit1.0000.715
min_samples_leaf 100.8430.778
min_samples_leaf 200.8150.780
  • Train above the 0.85 ceiling means the tree learned flipped labels.

Source1 Decision Trees (scikit-learn user guide)

Compare

Controls on a tree

ControlWhat it doesWatch for
max_depthCaps the number of questions in a rowToo low underfits
min_samples_leafEvery leaf keeps a minimum of rowsStarting value 5; tune it
Cost-complexity pruningMinimises impurity + alpha x leavesPick 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.

Source1 Decision Trees (scikit-learn user guide)

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

Diagram: Each tree is grown on its own bootstrap sample (rows drawn with replacement), independently of the others.

Bootstrap sample 1

Deep tree 1

Bootstrap sample 2

Deep tree 2

Bootstrap sample 3

Deep tree 3

Average or vote

Diagram summary: Each tree is grown on its own bootstrap sample (rows drawn with replacement), independently of the others. Their predictions are averaged for regression or voted for classification. Bagging works best with strong, complex trees.

Source2 Ensembles: Gradient boosting, random forests, bagging, voting, stacking (scikit-learn user guide)

Math

The variance of an average of correlated trees

Var⁡(1B∑bTb)=Bσ2+B(B−1)ρσ2B2=ρσ2+1−ρBσ2\operatorname{Var}\Big(\tfrac1B\sum_b T_b\Big)=\frac{B\sigma^2+B(B-1)\rho\sigma^2}{B^2}=\rho\sigma^2+\frac{1-\rho}{B}\sigma^2
  • More trees shrink the second term only.
  • ρσ2\rho\sigma^2 is a floor: independent trees (ρ=0\rho=0) give σ2/B\sigma^2/B, identical trees (ρ=1\rho=1) gain nothing.
  • Make the trees less alike to lower the floor.
  • Checked exactly (ρ=1/2\rho=1/2, B=4B=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\sigma^2ρ\rhoVariance at 1, 5, 25, 100 treesSquared bias
Bagging, 6 features2.2840.1272.376, 0.678, 0.375, 0.3100.273
Forest, 2 of 62.8910.0562.861, 0.644, 0.277, 0.1890.467
  • ρ\rho 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

BaggingRandom forest
Features per splitAllA random subset (sqrt for classification by default)
Correlation between treesHigherLower
Each treeStrongerWeaker, more bias
TuningFew knobsmax_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.

Source2 Ensembles: Gradient boosting, random forests, bagging, voting, stacking (scikit-learn user guide)

Concept

Out-of-bag error

  • A row is missed by one bootstrap sample with probability (1−1/n)n(1-1/n)^n: 0.3487 at n = 10, 0.3660 at 100, 0.3679 in the limit (1/e1/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.

Source2 Ensembles: Gradient boosting, random forests, bagging, voting, stacking (scikit-learn user guide)

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.550.5\cdot1+0.5\cdot1/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 −∂ℓ(y,F)∂F∣Fm−1F_m(x)=F_{m-1}(x)+\eta\,h_m(x),\qquad h_m\ \text{fitted to}\ -\frac{\partial\ell(y,F)}{\partial F}\Big|_{F_{m-1}}
  • Squared error: the negative gradient is the residual y−Fy-F.
  • Log loss with p=σ(F)p=\sigma(F): the derivative is p−yp-y, so the target is y−py-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.

Source3 Introduction to Boosted Trees (XGBoost documentation)

Worked example

Worked example: two rounds, exact

x=1..6x=1..6, y=(1,3,2,6,7,9)y=(1,3,2,6,7,9), stumps, η=1/2\eta=1/2. Start at the mean 14/3, MSE 74/9 = 8.22.

RoundSplitLeavesPredictionsMSE
1After x = 3-8/3 and 8/310/3, 10/3, 10/3, 6, 6, 626/9 = 2.89
2After x = 4-1 and 217/6 x3, 11/2, 7, 725/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:

RateDepthBest validation MSEAt roundAfter 800
1.011.709about 511.958
0.111.274about 2511.356
0.0111.665800 (still falling)1.665
0.131.489about 731.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.

Source2 Ensembles: Gradient boosting, random forests, bagging, voting, stacking (scikit-learn user guide)

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

DocumentedXGBoostLightGBM
Binningtree_method auto is the same as hist, max_bin 256Histogram-based algorithms
Growthgrow_policy depthwise by default, lossguide availableLeaf-wise: split the leaf with the largest loss reduction
ObjectiveSecond-order expansion, penalty on leaf count and weightsNot covered here
Complexity controlsmax_depth 6, min_child_weight, gammanum_leaves, min_data_in_leaf, max_depth
Other regulariserssubsample, colsample_bytree, lambda, alphafeature_fraction, bagging_fraction, lambda_l1, lambda_l2
  • Leaf-wise growth may over-fit when data is small; keep num_leaves small.
  • Scikit-learn’s HistGradientBoosting bins 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.

Sources3 Introduction to Boosted Trees (XGBoost documentation)4 XGBoost Parameters (XGBoost documentation)5 XGBoost: A Scalable Tree Boosting System6 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.

Sources9 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:

ModelLinear signal (floor 1.0)Steps and sine (floor 0.25)
Least squares1.0502.807
One deep tree3.4630.955
Bagged trees1.6860.625
Forest, 2 of 61.6391.128
Boosting1.5160.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:

ColumnImpurity share (training)Validation drop when permuted
Signal0.2510.182
Noise A0.3710.001
Noise B0.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.

Sources11 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

ProblemPoor choiceBetter choice
Missing values carry signalMean fill: 0.656 accuracyLearn a side for missing: 0.693
50,000-level categoryOne-hot: 50,000 sparse columnsNative categorical support or cross-fitted target encoding
Target encodingfit(X, y).transform(X) on training datafit_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.

Sources12 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

Diagram: Start with a linear baseline.

yes

no

Tabular data, a few thousand rows or more

Baseline: regularised linear or logistic model

Needs full transparency?

Shallow tree or scorecard

Gradient-boosted trees, early stopping on validation

Compare with the baseline and a forest on the same folds, tune each fairly

Diagram summary: Start with a linear baseline. If every decision must be transparent, use a shallow tree or scorecard. Otherwise fit gradient-boosted trees with early stopping, then compare them with the baseline and a random forest on the same folds with equal tuning effort. This is judgment, not a law.

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\rho\sigma^2+(1-\rho)\sigma^2/B: more trees remove only the second term, feature subsampling lowers ρ\rho 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−py-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)

  1. Decision Trees (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    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.

  2. Ensembles: Gradient boosting, random forests, bagging, voting, stacking (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    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.

  3. Introduction to Boosted Trees (XGBoost documentation) (opens in a new tab)

    XGBoost2026Documentation

    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.

  4. XGBoost Parameters (XGBoost documentation) (opens in a new tab)

    XGBoost2026Documentation

    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).

  5. XGBoost: A Scalable Tree Boosting System (opens in a new tab)

    Tianqi Chen, Carlos Guestrin2016arXiv:1603.02754 (KDD 2016)Paper

    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)

  1. Features (LightGBM documentation) (opens in a new tab)

    Microsoft LightGBM2026Documentation

    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.

  2. Parameters Tuning (LightGBM documentation) (opens in a new tab)

    Microsoft LightGBM2026Documentation

    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.

  3. HistGradientBoostingClassifier (scikit-learn API reference) (opens in a new tab)

    scikit-learn2026Documentation

    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.

  4. 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

    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.

  5. 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

    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)

  1. Permutation feature importance (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    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.

  2. Frequently Asked Questions (XGBoost documentation) (opens in a new tab)

    XGBoost2026Documentation

    Used for In tree algorithms, branch directions for missing values are learned during training.

  3. Preprocessing data: encoding categorical features and the target encoder (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    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.