Decision trees, random forests and gradient boosting

  • Intermediate
  • 1 h 20 min
  • Lesson 1 of 2 in Trees, ensembles and classical models
  • Last verified

Open slides(31 slides)

Before you start

You will be able to

  • Compute the Gini and entropy gain of a split by hand, explain why greedy splitting grows trees that overfit, and choose the controls (depth, leaf size, pruning) by validation error.
  • Use the variance of an average of correlated predictors, rho sigma^2 + (1 - rho) sigma^2 / B, to explain what bagging and feature subsampling fix and what more trees cannot, and use out-of-bag error as a free validation estimate.
  • Explain gradient boosting as stagewise fitting of the negative gradient (residuals for squared error, y - p for log loss), say how learning rate, number of rounds and tree depth interact, and contrast it with bagging.
  • Decide when tree ensembles are the right default for tabular data, and avoid the practical traps: impurity importance, correlated features, missing values, high-cardinality categoricals and extrapolation.

Concept

A decision tree is a list of yes-or-no questions about the features. Each row follows the answers down one branch to a leaf that holds a prediction. It is readable, needs no feature scaling and bends to almost any shape, which is also its flaw. This lesson turns the flaw into strength in two ways: average many trees (bagging, random forests), or add small trees one at a time, each correcting the last (boosting).

The first lesson gave the vocabulary (bias, variance, validation) and the second showed gradient descent on a loss. Here averaging attacks variance, and boosting is gradient descent in the space of predictions.

Single deep treeRandom forestGradient boosting
TreesOne, grown until pureMany, deep, grown independentlyMany, shallow, grown in sequence
Each tree seesAll rowsA bootstrap sample, and a random subset of features per splitThe current errors of the ensemble
Main effectLow bias, high varianceKeeps the bias, cuts the varianceCuts the bias step by step
Main riskMemorises noiseTrees too alike, so a variance floorToo many rounds or too large a step overfits
Tuning effortSmallSmallLarger

The last rows are rules of thumb. The lesson tests them on data you can regenerate.

Diagram: Bagging draws several bootstrap samples, grows one deep tree on each independently and averages their predictions.

Gradient boosting: sequential

Start: a constant

Tree 1 fits the residuals

Tree 2 fits what is left

Tree 3 ...

Sum: constant + learning rate x each tree

Bagging and random forests: parallel

Bootstrap sample 1

Deep tree 1

Bootstrap sample 2

Deep tree 2

Bootstrap sample 3

Deep tree 3

Average or vote

Diagram summary: Bagging draws several bootstrap samples, grows one deep tree on each independently and averages their predictions. Boosting starts from a constant and grows shallow trees one after another, each fitted to the errors that remain, and sums them with a learning-rate weight.

Why It Matters

Tabular data is everywhere in business problems, and tree ensembles are a widely used default for it: they handle mixed feature types and need little preprocessing. Knowing why they work tells you which knob to turn when they do not: more trees will not fix a forest whose trees agree with each other, and more boosting rounds can make a model worse. These models are also a common interview topic (common industry pattern).

Mental Model

Picture a tree as an eager student who memorises the textbook, noise included; a different textbook sample gives a different student with different mistakes. Bagging polls many such students so their quirks cancel. Boosting goes the other way: a deliberately simple student answers first, the next studies only what the first got wrong, and each student’s say is turned down so no one overrules the group.

How a tree picks a split

A tree grows from the root. At each node it tries every feature and threshold and keeps the question that makes the child groups purer. For class proportions pkp_k the standard impurities are

Gini=1−∑kpk2Entropy=−∑kpklog⁡2pk\text{Gini} = 1 - \sum_k p_k^2 \qquad\qquad \text{Entropy} = -\sum_k p_k \log_2 p_k

Scikit-learn writes the Gini as ∑kpk(1−pk)\sum_k p_k(1-p_k), the same number, and notes that using entropy as the criterion is equivalent to minimising the log loss (scikit-learn, Decision trees). A pure node scores 0; a 50/50 node scores the maximum, 0.5 for Gini and 1 bit for entropy. The gain of a split is the parent’s impurity minus the size-weighted impurity of the children. Regression trees use the variance of the targets as the impurity, and each leaf predicts the mean.

Worked example: Gini and entropy by hand

A node holds 10 rows, 5 positive and 5 negative: Gini 1−(0.52+0.52)=0.51 - (0.5^2 + 0.5^2) = 0.5. A question sends 5 rows left (4 positive, 1 negative) and 5 right (1 positive, 4 negative). Each child has Gini 1−(0.82+0.22)=0.321 - (0.8^2 + 0.2^2) = 0.32, so the Gini gain is 0.5 - 0.32 = 0.18. With entropy the parent is 1 bit, each child 0.7219 bits, and the gain 0.2781. A second node of 6 positive and 4 negative rows splits into (5, 0) and (1, 4): the right child has Gini 0.32 and half the rows, so the gain is 0.48−0.16=0.320.48 - 0.16 = 0.32 (entropy gain 0.6100).

For 0/1 labels with a share pp of ones, the Gini is 1−p2−(1−p)2=2p(1−p)1 - p^2 - (1-p)^2 = 2p(1-p), exactly twice the label variance p(1−p)p(1-p). Every split’s weighted impurity scales by the same factor, so squared-error splitting picks the same cut as Gini, and one tree-growing routine serves both.

Greedy, and what it misses

The tree takes the best split now and never looks ahead. Finding the best whole tree is much harder: scikit-learn states that learning an optimal decision tree “is known to be NP-complete under several aspects of optimality”, so practical algorithms are greedy (scikit-learn, Decision trees). Greed fails visibly on XOR, where the label is 1 when two binary features differ. Either feature alone leaves both children 50/50, so the gain is exactly 0 for both (script section 2), yet one split on each feature gives pure leaves. A learner that demands positive gain stops at the root. The guide lists XOR, parity and multiplexer problems among the concepts trees do not express easily.

Two more properties follow. Each question compares one feature with a threshold, so boundaries are axis-aligned staircases. A leaf stores a constant, so predictions are piecewise constant and, in scikit-learn’s words, trees “are not good at extrapolation”.

Overfitting and the controls on a tree

Left alone, a tree splits until every leaf is pure, which for noisy labels means one leaf per quirk. The scikit-learn guide names the remedies: pruning, a minimum number of samples at a leaf, and a maximum depth (scikit-learn, Decision trees). It also says small changes in the data can give “a completely different tree”, so a single deep tree has high variance, the opening bagging uses below.

To see it, take a circle of radius about 0.71 in a square, label rows inside as 1, then flip 15% of the labels at random. No model can beat 85% accuracy on fresh data from this source. With 200 training rows, the medians over 20 datasets were:

SettingTrain accuracyValidation accuracy
max_depth 10.6030.563
max_depth 20.7020.640
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

Shallow trees underfit. As depth grows, training accuracy climbs while validation accuracy peaks near depth 4 and then falls. The unlimited tree scores 1.000 on training data, above the 0.85 ceiling, so it has learned the flipped labels. Requiring 10 to 20 rows per leaf did better than any depth tried. Pick the control on a validation set.

Cost-complexity pruning grows the full tree, then cuts back. It minimises R(T)+α ∣T∣R(T) + \alpha\,|T|, the tree’s impurity plus a price α\alpha per leaf, and removes the weakest branches until the effective α\alpha passes your ccp_alpha (scikit-learn, Decision trees). It is the ridge trade from the first lesson again: fit versus size.

Bagging and the variance formula

Averaging many noisy but unbiased guesses beats one guess. Bagging (bootstrap aggregating) builds each tree on a bootstrap sample, nn rows drawn with replacement, then averages the predictions or votes (scikit-learn, Ensembles). The scikit-learn guide says bagging works best with strong, complex models such as fully grown trees, and boosting with weak ones such as shallow trees.

How much does averaging help? Let BB trees each have prediction variance σ2\sigma^2 at some input (over the randomness of the training set and the tree), with pairwise correlation ρ\rho. The variance of the average has BB variance terms and B(B−1)B(B-1) covariance terms, each ρσ2\rho\sigma^2:

Var⁡(1B∑b=1BTb)=Bσ2+B(B−1)ρσ2B2=ρ σ2+1−ρB σ2\operatorname{Var}\Big(\frac1B\sum_{b=1}^{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

The second term shrinks as trees are added. The first, ρσ2\rho\sigma^2, does not depend on BB: it is a floor. Independent trees (ρ=0\rho=0) give σ2/B\sigma^2/B; identical trees (ρ=1\rho=1) gain nothing. Trees grown on overlapping bootstrap samples sit in between, so more trees cannot push you below the floor; making the trees less alike can. This is derived here from the definition of variance and not quoted from a source; the script checks it exactly with fractions (ρ=1/2\rho=1/2, B=4B=4: both sides are 5/8) and on real trees below. Averaging leaves bias unchanged, so the trees should be deep and low-bias, the opposite of what boosting wants.

Random forests and out-of-bag error

A random forest adds a second source of randomness: each split considers only a random subset of the features. Scikit-learn gives the aim as decreasing the variance of the forest, “sometimes at the cost of a slight increase in bias”, with defaults of all features for regression and the square root of the feature count for classification (scikit-learn, Ensembles). Fewer candidates make the trees less alike, which lowers ρ\rho, but each tree gets worse. The script measures both: 30 training sets of 200 rows (six features, a linear signal, noise variance 1), 100 trees on each, predictions at 40 fixed points.

EnsembleOne-tree variance σ2\sigma^2Implied ρ\rhoVariance with 1, 5, 25, 100 treesSquared bias
Bagging, all 6 features2.2840.1272.376, 0.678, 0.375, 0.3100.273
Forest, 2 of 6 features2.8910.0562.861, 0.644, 0.277, 0.1890.467

ρ\rho is implied by solving the formula at 100 trees, so that column matches by construction; the others are the check (for bagging the formula gives 0.689 and 0.370 at 5 and 25 trees against 0.678 and 0.375 measured). Past a few dozen trees the floor dominates (ρσ2=0.290\rho\sigma^2 = 0.290 for bagging). Subsampling lowered it to 0.162 but raised each tree’s variance and the squared bias, so bias plus variance was 0.583 for bagging and 0.656 for the forest. In this example decorrelation did not pay, because every feature carries signal: features per split is a hyperparameter to tune.

Out-of-bag (OOB) error. A row is never drawn in nn draws with probability (1−1/n)n(1-1/n)^n: 0.3487 for n=10n=10, 0.3660 for 100, 0.3677 for 1,000, tending to 1/e=0.36791/e = 0.3679. So each bootstrap sample misses about 36.8% of the rows. Predict each row using only the trees that never saw it and you have a validation score with nothing held out (oob_score=True in scikit-learn). On the noisy circle, a 100-tree forest had median OOB accuracy 0.780 against 0.778 on 2,000 fresh rows, with a median per-dataset gap of 0.025: right on average, noisy for any one 200-row set.

Boosting: fitting the residuals

Bagging reduces variance. Boosting targets bias: the ensemble starts from a constant and improves it in steps. After m−1m-1 rounds the model is Fm−1(x)F_{m-1}(x). Round mm looks at where it is still wrong and adds a small tree hmh_m that corrects that:

Fm(x)=Fm−1(x)+η hm(x),hm fitted to −∂ℓ(y,F)∂F∣F=Fm−1(x)F_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=F_{m-1}(x)}

where η\eta is the learning rate (shrinkage). The tree is fitted to the negative gradient of the loss with respect to the current prediction, which is why the method is called gradient boosting: it is gradient descent, but the “parameter” being moved is the prediction at each training row, and the tree turns the per-row steps into a function that also works on new rows. For squared error ℓ=12(y−F)2\ell = \tfrac12(y-F)^2 the negative gradient is the residual y−Fy - F. For the log loss of the previous lesson, with p=σ(F)p = \sigma(F), the derivative with respect to the raw score is p−yp - y, so the negative gradient is y−py - p; the script checks by finite differences that the derivative is −0.331812-0.331812 for y=1y=1 and 0.6681880.668188 for y=0y=0 at F=0.7F=0.7, matching p−yp-y. Boosting is therefore not tied to squared error; any differentiable loss gives a recipe.

Worked example: two rounds by hand

Take x=1,…,6x = 1,\dots,6 and y=(1,3,2,6,7,9)y = (1, 3, 2, 6, 7, 9), squared error, depth-1 trees (stumps) and η=1/2\eta = 1/2. The starting constant is the mean, 14/314/3, with mean squared error 74/9=8.2274/9 = 8.22.

RoundResidualsBest stumpLeaf valuesPredictions after the stepMSE
1-11/3, -5/3, -8/3, 4/3, 7/3, 13/3Split after x=3x=3-8/3 and 8/310/3, 10/3, 10/3, 6, 6, 626/9 = 2.89
2-7/3, -1/3, -4/3, 0, 1, 3Split after x=4x=4-1 and 217/6, 17/6, 17/6, 11/2, 7, 725/18 = 1.39

A leaf’s value is the mean of the residuals that land in it, and the step adds only half of it. Each round changes the prediction a little, and the second round chooses a different split because the first one already moved the error. Many small corrections can follow a curve that no single stump can.

Learning rate, rounds and depth

Three knobs interact. Scikit-learn says the learning rate “strongly interacts with” the number of estimators: smaller values need more trees, and “empirical evidence suggests that small values of learning_rate favor better test error”. It cites a recommendation of a constant at most 0.1 with enough trees for early stopping to decide when to stop (scikit-learn, Ensembles). Depth sets how many features can interact within one tree.

The script boosts the six-feature linear source (noise variance 1, so validation error cannot go below 1.0) with 200 training rows. Medians over 6 datasets:

Learning rateDepthBest validation MSEAt roundAfter 800 rounds
1.011.709about 511.958
0.111.274about 2511.356
0.0111.665800 (still falling)1.665
0.131.489about 731.566

The big step bottoms out early at a worse value, and the tiny step is still improving when the 800-round cap stops it (given enough rounds it can catch up, but within the cap it is worse than 0.1). At the middle rate validation error bottoms out and creeps up as the model fits noise, so the number of rounds is a regularisation setting, chosen by early stopping on held-out data and not by training loss, which only falls. Row subsampling (a typical subsample is 0.5) gives stochastic gradient boosting, which the guide says helps with shrinkage and does poorly without. Depth-3 trees did worse than stumps in this experiment, where the signal is additive.

XGBoost and LightGBM: what is documented

These are documented defaults and parameters, not a ranking. XGBoost’s tree_method default auto is the same as hist, so it bins too (max_bin 256); its default grow_policy is depthwise, with lossguide available; eta defaults to 0.3 and max_depth to 6. Its objective uses a second-order expansion with the penalty γT+12λ∑jwj2\gamma T + \tfrac12\lambda\sum_j w_j^2, and its regularisers include min_child_weight, subsample, colsample_bytree, lambda (L2) and alpha (L1) (XGBoost, Parameters; Introduction to boosted trees). LightGBM grows leaf-wise, which “may cause over-fitting when #data is small” (Features), so its tuning guide advises a small num_leaves (below 2max_depth2^{\text{max\_depth}}), min_data_in_leaf, max_depth, feature_fraction, bagging_fraction and lambda_l1/lambda_l2 (Parameters Tuning). Scikit-learn’s HistGradientBoosting bins into up to 255 bins plus one for missing values (API reference). CatBoost’s documentation was not opened, so it is not covered.

When trees win on tabular data

The main evidence for “trees beat neural nets on tables” is a 2022 benchmark of 45 tabular datasets by Grinsztajn, Oyallon and Varoquaux: heterogeneous columns, at least 3,000 rows, training sets truncated to 10,000. In 2022 they found tree-based models such as XGBoost and random forests remained state of the art on that medium-sized data, even without counting speed (arXiv:2207.08815). They attribute it to neural networks (MLPs) preferring overly smooth functions, being less robust to uninformative features, and ignoring that a column such as “age” has its own meaning. Very small and very large datasets were not evaluated. For small data the picture has since moved: Hollmann et al. (Nature, 2025) report that TabPFN, a pretrained tabular foundation model, beats strong baselines including gradient-boosted trees on datasets of up to about 10,000 samples (abstract). Those are the authors’ claims (two are affiliated with a company building such models), and this lesson did not test them. Treat “trees win” as a strong default to check, not a settled result.

Trees also lose in places. Validation MSE in the script, median of 6 datasets of 200 rows with little tuning:

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 6 features1.6391.128
Boosting (rounds chosen on 50 held-out rows)1.5160.475

A staircase approximating a line wastes data, so least squares wins the linear source and loses the irregular one. Trust the ordering, not the decimals.

Extrapolation. Trained on y=2xy=2x for xx from 0 to 10, a tree predicts 20.0 at x=15x=15 and a line 30.0, because a leaf is a constant from the nearest training region. For a trending target, detrend it, add a linear component or change model.

A defensible default, offered as judgment and not as a law: a regularised linear baseline, then gradient-boosted trees, and a shallow tree or scorecard when every decision must be explained.

Diagram: Start with a linear baseline on tabular data.

yes

no

Tabular data, a few thousand rows or more

Baseline: regularised linear or logistic model

Needs full transparency?

Shallow tree or scorecard,
explain with care

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 on tabular data. 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.

Feature importance and its traps

The default answer to “which features matter?” misleads. Impurity importance (feature_importances_) credits each feature with the impurity decrease of the splits that use it. Scikit-learn warns that it comes from training statistics, so it may not show what matters on held-out data, and that it favours high-cardinality features (Ensembles; Permutation importance). Permutation importance shuffles one column of a held-out set and measures the drop in score.

The script builds 300 rows with a binary feature that predicts the label 75% of the time, plus two continuous columns of pure noise. A 50-tree forest scores 1.000 on training and 0.690 on validation. Medians over 20 datasets:

ColumnShare of impurity importance (training)Validation accuracy drop when permuted
Binary signal0.2510.182
Noise A0.3710.001
Noise B0.377-0.001

Impurity importance gave about 75% of the credit to columns with no signal, because a tree that must fit every row finds some split on a continuous noise value. The second trap is correlated features: permute one of two near-copies and the model can still use the other, so both look less important than they are. After adding an exact copy of the signal (a new forest), the drop was 0.134 for the original and 0.092 for the copy; permuting both together gave 0.237, close to their sum (0.226). Scikit-learn suggests clustering correlated features and keeping one per cluster. Neither method is causal: they describe the fitted model, not the world.

Missing values and categorical features

Trees compare a feature with a threshold, so they need no scaling. Missing values and categories need thought.

Missing values. Scikit-learn’s trees try sending all missing values left and all right at each candidate threshold, and keep the better split (Decision trees). Histogram boosting learns the side “based on the potential gain” (Ensembles), and XGBoost’s FAQ says branch directions for missing values “are learned during training” (FAQ). This beats mean filling when missingness carries information. In the script, 40% of positive rows and 5% of negative rows have the value missing: a one-split model that learns a side reached validation accuracy 0.693, and with mean filling 0.656, because a filled-in mean sits among real values and hides the signal. Where a library does not learn a direction, an “is missing” indicator column is a common workaround (judgment, not from a source above).

Categorical features. One-hot encoding a 50,000-level category makes 50,000 sparse columns. Better: native categorical support (scikit-learn’s histogram boosting says it is often better than one-hot, with cardinality below max_bins; LightGBM partitions the categories into two subsets and calls one-hot “suboptimal for tree learners”) or target encoding. Target encoding replaces a category by its target mean, shrunk toward the global mean, and leaks the label if computed naively. Scikit-learn’s TargetEncoder cross-fits, encoding each training fold with statistics from the other folds, and warns that fit(X, y).transform(X) differs from fit_transform(X, y) and should not be used on training data (Preprocessing).

Code

This standard-library script produced every number in the lesson (Python 3.14.6). It builds a regression tree, a forest and a boosting loop from scratch, with Fraction for the exact parts and fixed seeds for the random ones. It takes about a minute; another Python version may draw different random numbers, moving decimals but not orderings.

Python

import math
import random
import statistics
from fractions import Fraction as Fr


# ---------- A small CART regression tree, a forest and a boosting loop (squared error) ----------
def best_split(X, y, idx, feats, min_leaf):
    """Greedy search: the (feature, threshold) that most lowers the sum of squared errors."""
    n = len(idx)
    tot, tot2 = sum(y[i] for i in idx), sum(y[i] ** 2 for i in idx)
    parent, best = tot2 - tot * tot / n, None
    for f in feats:
        order = sorted(idx, key=lambda i: X[i][f])
        s = s2 = 0.0
        for k in range(1, n):
            v = y[order[k - 1]]
            s, s2 = s + v, s2 + v * v
            a, b = X[order[k - 1]][f], X[order[k]][f]
            if k < min_leaf or n - k < min_leaf or a == b:
                continue
            gain = parent - ((s2 - s * s / k) + ((tot2 - s2) - (tot - s) ** 2 / (n - k)))
            if best is None or gain > best[0] + 1e-12:
                best = (gain, f, (a + b) / 2)
    return best


def grow(X, y, idx, depth, max_depth, min_leaf, max_features, rng, imp=None):
    mean = sum(y[i] for i in idx) / len(idx)
    if depth == max_depth or len(idx) < 2 * min_leaf or all(y[i] == y[idx[0]] for i in idx):
        return mean
    d = len(X[0])
    feats = range(d) if max_features >= d else rng.sample(range(d), max_features)
    best = best_split(X, y, idx, feats, min_leaf)
    if best is None or best[0] <= 1e-12:
        return mean
    gain, f, thr = best
    if imp is not None:
        imp[f] += gain
    left = [i for i in idx if X[i][f] <= thr]
    right = [i for i in idx if X[i][f] > thr]
    return (f, thr, grow(X, y, left, depth + 1, max_depth, min_leaf, max_features, rng, imp),
            grow(X, y, right, depth + 1, max_depth, min_leaf, max_features, rng, imp))


def predict(tree, x):
    while isinstance(tree, tuple):
        tree = tree[2] if x[tree[0]] <= tree[1] else tree[3]
    return tree


def fit_tree(X, y, max_depth=10**9, min_leaf=1, max_features=10**9, rng=None, imp=None):
    return grow(X, y, list(range(len(X))), 0, max_depth, min_leaf, max_features, rng or random.Random(0), imp)


def fit_forest(X, y, B, max_features, rng, imp=None):
    """B trees on bootstrap samples; returns the trees and each tree's out-of-bag row indices."""
    n, trees, oobs = len(X), [], []
    for _ in range(B):
        boot = [rng.randrange(n) for _ in range(n)]
        seen = set(boot)
        trees.append(grow(X, y, boot, 0, 10**9, 1, max_features, rng, imp))
        oobs.append([i for i in range(n) if i not in seen])
    return trees, oobs


def forest_mean(trees, x):
    return statistics.fmean(predict(t, x) for t in trees)


def boost(X, y, Xv, yv, lr, rounds, depth):
    """Gradient boosting for squared error: each tree fits the residuals. Returns validation MSE per round."""
    F0 = statistics.fmean(y)
    F, Fv = [F0] * len(X), [F0] * len(Xv)
    curve = [mse(Fv, yv)]
    for _ in range(rounds):
        tree = fit_tree(X, [t - p for t, p in zip(y, F)], max_depth=depth)
        F = [p + lr * predict(tree, x) for p, x in zip(F, X)]
        Fv = [p + lr * predict(tree, x) for p, x in zip(Fv, Xv)]
        curve.append(mse(Fv, yv))
    return curve


def mse(pred, y):
    return statistics.fmean((a - b) ** 2 for a, b in zip(pred, y))


def gini(counts):
    n = sum(counts)
    return 1 - sum(Fr(c, n) ** 2 for c in counts)


def entropy(counts):
    n = sum(counts)
    return -sum((c / n) * math.log2(c / n) for c in counts if c)


def med(values):
    return round(statistics.median(values), 3)


D = 6


def f_lin(x):
    return 2 * x[0] + 2 * x[1] + x[2] + x[3] + x[4] + x[5]


def f_irr(x):
    return 3 * (x[0] > 0.3) + 2 * math.sin(6 * x[1]) + x[2] * (x[3] > 0)


def make(seed, n, fn, noise):
    r = random.Random(seed)
    X = [[r.uniform(-1, 1) for _ in range(D)] for _ in range(n)]
    return X, [fn(x) + r.gauss(0, noise) for x in X]


def circle(seed, n, flip=0.15):
    r = random.Random(seed)
    X = [[r.uniform(-1, 1), r.uniform(-1, 1)] for _ in range(n)]
    y = [int(a * a + b * b < 0.5) for a, b in X]
    return X, [1 - t if r.random() < flip else t for t in y]


def acc(model, X, y):
    return statistics.fmean((predict(model, x) >= 0.5) == t for x, t in zip(X, y))


# 1. Splits by hand: Gini and entropy gain
for name, parent, kids in (("5/5 -> (4,1),(1,4)", (5, 5), ((4, 1), (1, 4))),
                           ("6/4 -> (5,0),(1,4)", (6, 4), ((5, 0), (1, 4)))):
    n = sum(parent)
    g = gini(parent) - sum(Fr(sum(k), n) * gini(k) for k in kids)
    e = entropy(parent) - sum(sum(k) / n * entropy(k) for k in kids)
    print("1.", name, "gini parent", gini(parent), "child ginis", [str(gini(k)) for k in kids],
          "gini gain", g, "entropy gain %.4f" % e)

# 2. Greedy is myopic: on XOR no first split helps, yet two splits are perfect
pts = [(a, b, int(a != b)) for a in (0, 1) for b in (0, 1) for _ in range(5)]
for f in (0, 1):
    kids = [[p[2] for p in pts if p[f] == v] for v in (0, 1)]
    gain = gini((10, 10)) - Fr(1, 2) * sum(gini((len(k) - sum(k), sum(k))) for k in kids)
    print("2. XOR split on feature", f, "gain", gain)
for v in (0, 1):                                  # split on feature 0 anyway, then on feature 1
    side = [p for p in pts if p[0] == v]
    kids = [[p[2] for p in side if p[1] == w] for w in (0, 1)]
    print("   child gini", gini((len(side) - sum(p[2] for p in side), sum(p[2] for p in side))),
          "-> grandchildren", [str(gini((len(k) - sum(k), sum(k)))) for k in kids])

# 3. Depth and leaf size on a noisy circle (15% of labels flipped: best possible accuracy 0.85)
print("3. median train and validation accuracy over 20 seeds")
for label, kw in (("depth 1", dict(max_depth=1)), ("depth 2", dict(max_depth=2)), ("depth 4", dict(max_depth=4)),
                  ("depth 8", dict(max_depth=8)), ("no limit", {}), ("leaf >= 10", dict(min_leaf=10)),
                  ("leaf >= 20", dict(min_leaf=20))):
    tr, va = [], []
    for s in range(20):
        X, y = circle(s, 200)
        Xv, yv = circle(1000 + s, 2000)
        m = fit_tree(X, y, **kw)
        tr.append(acc(m, X, y))
        va.append(acc(m, Xv, yv))
    print("  ", label, med(tr), med(va))

# 4. The variance formula, exactly: rho sigma^2 + (1 - rho) sigma^2 / B
for rho, B in ((Fr(1, 2), 4), (Fr(3, 10), 10)):
    total = sum(1 if i == j else rho for i in range(B) for j in range(B))     # 1' Sigma 1, unit variances
    print("4. rho", rho, "B", B, "variance of the mean", total / B ** 2, "formula", rho + (1 - rho) / B)

# 5. Real trees: variance over 30 training sets, bagging versus a random forest
R, B = 30, 100
Xt, _ = make(999, 40, f_lin, 0)
truth = [f_lin(x) for x in Xt]
print("5. 30 training sets of 200 rows; variance of the prediction at 40 fixed points (noise variance 1)")
for name, mf in (("bagging (all 6 features)", 6), ("random forest (2 of 6)", 2)):
    P = []                                   # P[s][b][j]: tree b of training set s at test point j
    for s in range(R):
        X, y = make(s, 200, f_lin, 1.0)
        trees, _ = fit_forest(X, y, B, mf, random.Random(10000 + s))
        P.append([[predict(t, x) for x in Xt] for t in trees])
    J = range(len(Xt))
    ens = lambda s, j, k: statistics.fmean(P[s][b][j] for b in range(k))
    sigma2 = statistics.fmean(statistics.pvariance([P[s][b][j] for s in range(R)]) for b in range(B) for j in J)
    row = {k: statistics.fmean(statistics.pvariance([ens(s, j, k) for s in range(R)]) for j in J) for k in (1, 5, 25, 100)}
    rho = (row[100] - sigma2 / B) / (sigma2 * (1 - 1 / B))
    bias2 = statistics.fmean((statistics.fmean(ens(s, j, B) for s in range(R)) - truth[j]) ** 2 for j in J)
    print("   %s: one-tree variance %.3f, implied rho %.3f, squared bias %.3f" % (name, sigma2, rho, bias2))
    print("     trees -> variance:", {k: round(v, 3) for k, v in row.items()},
          "| formula:", {k: round(rho * sigma2 + (1 - rho) * sigma2 / k, 3) for k in row},
          "| floor rho*sigma2 = %.3f" % (rho * sigma2))

# 6. Out-of-bag: about 36.8% of rows are left out of each bootstrap, and they give a free estimate
print("6a. expected out-of-bag fraction", {n: round((1 - 1 / n) ** n, 4) for n in (10, 100, 1000)}, "limit 1/e = %.4f" % math.exp(-1))
oob_acc, val_acc = [], []
for s in range(20):
    X, y = circle(s, 200)
    Xv, yv = circle(1000 + s, 2000)
    trees, oobs = fit_forest(X, y, 100, 1, random.Random(s))
    votes = [[] for _ in X]
    for t, oob in zip(trees, oobs):
        for i in oob:
            votes[i].append(predict(t, X[i]))
    oob_acc.append(statistics.fmean((statistics.fmean(v) >= 0.5) == t for v, t in zip(votes, y) if v))
    val_acc.append(statistics.fmean((forest_mean(trees, x) >= 0.5) == t for x, t in zip(Xv, yv)))
print("6b. 100-tree forest, 20 datasets: median OOB accuracy %.3f, validation %.3f, median gap %.3f"
      % (statistics.median(oob_acc), statistics.median(val_acc), statistics.median(abs(a - b) for a, b in zip(oob_acc, val_acc))))

# 7. Gradient boosting by hand (squared error), exact; then the log-loss gradient by finite differences
xs, ys, eta = [1, 2, 3, 4, 5, 6], [Fr(v) for v in (1, 3, 2, 6, 7, 9)], Fr(1, 2)
F = [sum(ys) / 6] * 6
print("7a. F0 =", F[0], "mse", sum((t - p) ** 2 for t, p in zip(ys, F)) / 6)
for rnd in (1, 2):
    res = [t - p for t, p in zip(ys, F)]
    best = None
    for k in range(1, 6):                      # stump: split after the k-th point, leaves are the residual means
        lm, rm = sum(res[:k]) / k, sum(res[k:]) / (6 - k)
        sse = sum((v - lm) ** 2 for v in res[:k]) + sum((v - rm) ** 2 for v in res[k:])
        if best is None or sse < best[0]:
            best = (sse, k, lm, rm)
    _, k, lm, rm = best
    F = [p + eta * (lm if i < k else rm) for i, p in enumerate(F)]
    print("   round %d: residuals %s, split after x=%d, leaves %s and %s, new F %s, mse %s"
          % (rnd, [str(v) for v in res], xs[k - 1], lm, rm, [str(v) for v in F],
             sum((t - p) ** 2 for t, p in zip(ys, F)) / 6))
sigmoid = lambda z: 1 / (1 + math.exp(-z))
for y1 in (1, 0):
    loss = lambda z: -(y1 * math.log(sigmoid(z)) + (1 - y1) * math.log(1 - sigmoid(z)))
    print("7b. y=%d: numerical d(loss)/dF at F=0.7: %.6f, p - y = %.6f"
          % (y1, (loss(0.7 + 1e-6) - loss(0.7 - 1e-6)) / 2e-6, sigmoid(0.7) - y1))

# 8. Learning rate, rounds and depth (validation MSE; noise floor 1.0), median of 6 datasets
print("8. best validation MSE, the round it happens at, and MSE after 800 rounds")
for lr, depth in ((1.0, 1), (0.1, 1), (0.01, 1), (0.1, 3)):
    curves = []
    for s in range(6):
        X, y = make(s, 200, f_lin, 1.0)
        Xv, yv = make(500 + s, 1000, f_lin, 1.0)
        curves.append(boost(X, y, Xv, yv, lr, 800, depth))
    print("   lr %-4s depth %d: best %.3f at round %s, after 800 rounds %.3f"
          % (lr, depth, statistics.median(min(c) for c in curves), statistics.median(c.index(min(c)) for c in curves),
             statistics.median(c[-1] for c in curves)))


# 9. Which model, on which data? Validation MSE, median of 6 datasets of 200 rows
def ols(X, y):
    A = [[1.0] + x for x in X]
    k = len(A[0])
    M = [[sum(r[i] * r[j] for r in A) for j in range(k)] + [sum(r[i] * t for r, t in zip(A, y))] for i in range(k)]
    for c in range(k):
        p = max(range(c, k), key=lambda i: abs(M[i][c]))
        M[c], M[p] = M[p], M[c]
        for i in range(k):
            if i != c:
                m = M[i][c] / M[c][c]
                M[i] = [a - m * b for a, b in zip(M[i], M[c])]
    return [M[i][k] / M[i][i] for i in range(k)]


for label, fn, noise in (("linear truth, noise 1.0 (floor 1.0)", f_lin, 1.0),
                         ("steps and a sine, noise 0.5 (floor 0.25)", f_irr, 0.5)):
    out = {}
    for s in range(6):
        X, y = make(s, 200, fn, noise)
        Xv, yv = make(500 + s, 1000, fn, noise)
        w = ols(X, y)
        out.setdefault("linear", []).append(mse([w[0] + sum(a * b for a, b in zip(w[1:], x)) for x in Xv], yv))
        out.setdefault("one deep tree", []).append(mse([predict(fit_tree(X, y), x) for x in Xv], yv))
        for name, mf in (("bagged trees", 6), ("forest, 2 of 6", 2)):
            trees, _ = fit_forest(X, y, 50, mf, random.Random(s))
            out.setdefault(name, []).append(mse([forest_mean(trees, x) for x in Xv], yv))
        c = boost(X[:150], y[:150], X[150:], y[150:], 0.1, 300, 3)     # pick the rounds on the last 50 rows
        out.setdefault("boosting", []).append(boost(X, y, Xv, yv, 0.1, max(c.index(min(c)), 1), 3)[-1])
    print("9.", label, {k: med(v) for k, v in out.items()})

# 10. Trees cannot extrapolate
X = [[i / 10] for i in range(101)]
w = ols(X, [2 * v[0] for v in X])
print("10. trained on x in [0, 10] with y = 2x; at x = 15 the tree says", predict(fit_tree(X, [2 * v[0] for v in X]), [15]),
      "and the line says", round(w[0] + w[1] * 15, 3))


# 11. Importance: impurity (training) versus permutation (validation), and a correlated copy
def signal_data(seed, n):
    r = random.Random(seed)
    X, y = [], []
    for _ in range(n):
        s = r.random() < 0.5
        y.append(int(s if r.random() < 0.75 else not s))
        X.append([1.0 if s else 0.0, r.random(), r.random()])     # a binary signal and two noise columns
    return X, y


def forest_acc(trees, X, y):
    return statistics.fmean((forest_mean(trees, x) >= 0.5) == t for x, t in zip(X, y))


def shuffled(X, cols, rng):
    perm = list(range(len(X)))
    rng.shuffle(perm)
    out = [x[:] for x in X]
    for k, p in enumerate(perm):
        for j in cols:
            out[k][j] = X[p][j]
    return out


shares, drops, tr_acc, va_acc, alone, copy_a, copy_b, both = [], [], [], [], [], [], [], []
for s in range(20):
    X, y = signal_data(s, 300)
    Xv, yv = signal_data(100 + s, 1000)
    rng, imp = random.Random(s), [0.0] * 3
    trees, _ = fit_forest(X, y, 50, 2, random.Random(s), imp)
    shares.append([v / sum(imp) for v in imp])
    base = forest_acc(trees, Xv, yv)
    drops.append([base - forest_acc(trees, shuffled(Xv, [j], rng), yv) for j in range(3)])
    tr_acc.append(forest_acc(trees, X, y))
    va_acc.append(base)
    X4, Xv4 = [x + [x[0]] for x in X], [x + [x[0]] for x in Xv]         # add an exact copy of the signal
    trees4, _ = fit_forest(X4, y, 50, 2, random.Random(s))
    base4 = forest_acc(trees4, Xv4, yv)
    copy_a.append(base4 - forest_acc(trees4, shuffled(Xv4, [0], rng), yv))
    copy_b.append(base4 - forest_acc(trees4, shuffled(Xv4, [3], rng), yv))
    both.append(base4 - forest_acc(trees4, shuffled(Xv4, [0, 3], rng), yv))
    alone.append(drops[-1][0])
col = lambda rows: [med(r[j] for r in rows) for j in range(3)]
print("11a. columns: binary signal, noise, noise. Impurity importance share (training):", col(shares))
print("     permutation drop on validation:", col(drops), "| forest train accuracy %.3f, validation %.3f"
      % (statistics.median(tr_acc), statistics.median(va_acc)))
print("11b. permuting the signal: alone %.3f; with a copy, the original %.3f and the copy %.3f; both together %.3f"
      % tuple(statistics.median(v) for v in (alone, copy_a, copy_b, both)))


# 12. Missing values: let the split choose a side, or fill in the mean
def gaps(seed, n):
    r = random.Random(seed)
    X, y = [], []
    for _ in range(n):
        label = int(r.random() < 0.5)
        X.append(None if r.random() < (0.4 if label else 0.05) else r.gauss(0.5 * label, 1))   # missingness is a signal
        y.append(label)
    return X, y


def one_split(X, y, Xv, yv, learn_side):
    """Best one-question model on X; returns validation accuracy. Missing goes left or right, or is mean-filled."""
    mean = statistics.fmean(x for x in X if x is not None)
    prep = (lambda v: v) if learn_side else (lambda v: mean if v is None else v)
    rule = lambda x, thr, left_if_missing, lc: lc if (left_if_missing if x is None else x <= thr) else 1 - lc
    cuts = sorted({x for x in X if x is not None})[::5]
    options = [(t, m, lc) for t in cuts for m in ((True, False) if learn_side else (True,)) for lc in (0, 1)]
    best = max(options, key=lambda o: sum(rule(prep(x), *o) == t for x, t in zip(X, y)))
    return statistics.fmean(rule(prep(x), *best) == t for x, t in zip(Xv, yv))


learned, filled = [], []
for s in range(20):
    X, y = gaps(s, 500)
    Xv, yv = gaps(100 + s, 5000)
    learned.append(one_split(X, y, Xv, yv, True))
    filled.append(one_split(X, y, Xv, yv, False))
print("12. one-split model, validation accuracy: side learned for missing %.3f, mean-filled %.3f"
      % (statistics.median(learned), statistics.median(filled)))

What to look for: section 1 (gains 9/50 and 8/25), section 2 (zero gain on XOR), section 3 (training accuracy above the 0.85 ceiling), section 5 (the floor and the bias price of subsampling), section 8 (small rates need more rounds), section 11 (impurity versus permutation importance). Scikit-learn’s DecisionTreeClassifier, RandomForestClassifier(oob_score=True), HistGradientBoostingClassifier and permutation_importance are the production versions; their numbers will differ.

Real-World Application

On a churn, fraud or pricing table: split by time or group so validation resembles production, fit a regularised linear baseline, then a boosted model with early stopping on the validation fold, and read the train-validation gap before tuning further. Use permutation importance on validation data, fit target encoding inside each fold, and check behaviour outside the training range. Store the number of rounds with the model.

Interview Perspective

Expect “compute the gain of this split”, “random forest versus gradient boosting”, “why does feature subsampling help”, “walk me through gradient boosting”, “how do you stop a boosted model overfitting”, “why not trust impurity importance” and “why do trees beat neural networks on tabular data”. A strong answer gives the mechanism with a formula or a small number, then a limit: the variance floor, the bias cost of subsampling, or the 10,000-row scope of the benchmark. A weak answer says “boosting is more accurate” and stops.

Provenance: Common industry pattern. These are standard questions for ML roles, not a verified list for any named company.

Practice Questions

  • Basic: A node has 6 positive and 4 negative rows. Split it into (5, 0) and (1, 4) and compute the Gini gain.
  • Intermediate: Your random forest with 500 trees has the same validation error as one with 100. What does the variance formula say, and what could you change instead?
  • Advanced: Why does the negative gradient of the log loss with respect to the raw score equal y−py - p, and what does that mean for a gradient-boosted classifier fitting regression trees?
  • Product-Company (Generated practice): A boosted model reaches AUC 0.91 on validation but 0.84 a month after launch, and the top “important” feature is a customer ID. List what you check, in order.

Activity

Run the script once. Change section 3 to try min_leaf 5 and 40 and say where validation accuracy peaks. In section 5 change the forest to 3 of 6 features and predict, before running, whether ρ\rho and the squared bias rise or fall. In section 8 try learning rate 0.05 and predict whether its best round comes before or after the rate-0.1 run.

Homework

Implement the pieces of a decision tree in pure Python: Gini impurity, the gain of a split, the best threshold for one feature, and a depth-limited tree you can train and predict with. The code is in homework/; run the tests until they pass.

Quick Revision

  • Gini 1−∑pk21-\sum p_k^2, entropy −∑pklog⁡2pk-\sum p_k\log_2 p_k; (5,5) into (4,1) and (1,4) has Gini gain 0.18. Greedy misses XOR. Unlimited trees memorise noise: limit them by validation.
  • Averaged predictors: ρσ2+(1−ρ)σ2/B\rho\sigma^2 + (1-\rho)\sigma^2/B. More trees shrink only the second term. About 36.8% of rows are out of bag.
  • Gradient boosting fits the negative gradient (the residual, or y−py-p for log loss); rounds and learning rate trade off, set by early stopping.
  • Trees are a strong default for medium-sized tabular data, not a law; they cannot extrapolate. Use permutation importance on validation data.

Check yourself

  • Walk-through: Without notes, derive the variance of an average of BB equally correlated predictors, and say which term more trees remove.
  • Variation: A forest and a boosted model have equal validation error, but the forest has 400 trees of depth 20 and the boosted model 300 trees of depth 3. Which is easier to tune and why, and which would you expect to need early stopping?
  • Common misconception: “More trees in a random forest always improve it”, and “boosting and bagging both just average trees”.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Further reading

Research papers

Hands-on

More for this module: Trees, ensembles and classical models resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Trees, ensembles and classical models.

Check yourself14 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 14 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveCompute the Gini and entropy gain of a split by hand, explain why greedy splitting grows trees that overfit, and choose the controls (depth, leaf size, pruning) by validation error.

  1. Question 1 of 14A node holds 8 rows, 4 positive and 4 negative. Split A sends them to (3 positive, 1 negative) and (1 positive, 3 negative). Split B sends them to (4 positive, 2 negative) and (0 positive, 2 negative). Which split has the larger Gini gain?

    Choose one answer.

  2. Question 2 of 14Which statements about how trees choose splits are true? Select all that apply.

    Choose all that apply.

  3. Question 3 of 14You grow a full tree and then apply cost-complexity pruning, raising ccp_alpha from 0 through a series of larger values. What do you expect, and how do you pick the value to keep?

    Choose one answer.

ObjectiveUse the variance of an average of correlated predictors, rho sigma^2 + (1 - rho) sigma^2 / B, to explain what bagging and feature subsampling fix and what more trees cannot, and use out-of-bag error as a free validation estimate.

  1. Question 4 of 14A bag of B = 50 trees has per-tree prediction variance 4 and pairwise correlation 0.25. What is the variance of the averaged prediction, and roughly what happens if you raise B to 5,000?

    Choose one answer.

  2. Question 5 of 14A random forest of 100 trees has the same validation error as one of 1,000 trees, and the error is well above what the team needs. The data has several useful features. Which change could lower the error floor the formula describes?

    Choose one answer.

  3. Question 6 of 14Which statements about out-of-bag (OOB) error in a bagged forest are true? Select all that apply.

    Choose all that apply.

ObjectiveExplain gradient boosting as stagewise fitting of the negative gradient (residuals for squared error, y - p for log loss), say how learning rate, number of rounds and tree depth interact, and contrast it with bagging.

  1. Question 7 of 14Squared-error gradient boosting on three rows with targets y = (2, 4, 9). The starting constant is the mean, 5. The first stump puts rows 1 and 2 in one leaf and row 3 in the other, and the learning rate is 0.5. What are the predictions after round 1?

    Choose one answer.

  2. Question 8 of 14A gradient-boosted binary classifier uses log loss on a raw score F, with probability p = sigmoid(F). For a row with y = 1 and current score F = -1.0, what target does the next regression tree receive for this row?

    Choose one answer.

  3. Question 9 of 14In a boosting run with learning rate 0.3 and depth-4 trees, training loss falls on every round of 2,000. Validation loss reaches its minimum at round 140 and rises afterwards. What is the best response?

    Choose one answer.

  4. Question 10 of 14Which statements correctly contrast bagging (random forests) with gradient boosting? Select all that apply.

    Choose all that apply.

ObjectiveDecide when tree ensembles are the right default for tabular data, and avoid the practical traps: impurity importance, correlated features, missing values, high-cardinality categoricals and extrapolation.

  1. Question 11 of 14A forest's impurity-based feature importance ranks customer_id, a unique identifier per row, as the second most important feature. Permutation importance on a held-out validation set puts it near zero. How do you read this?

    Choose one answer.

  2. Question 12 of 14Which statements about missing values and categorical features in tree models are true? Select all that apply.

    Choose all that apply.

  3. Question 13 of 14A boosted-tree model for weekly sales is trained on 2020 to 2023, where sales rose steadily. In 2024 it predicts a flat line near the 2023 level while actual sales keep rising. What explains this, and what is a sensible fix?

    Choose one answer.

  4. Question 14 of 14A table has 200 rows and six numeric features whose relationship to the target is linear plus noise. On validation, least squares scores MSE 1.05, boosted trees 1.52 and a random forest 1.64, with a noise floor of 1.0. A colleague says trees always win on tabular data. What is the best response?

    Choose one answer.