Lecture 4

Decision trees and ensembles

Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027

The engineer's rule

A maintenance engineer: "if the vibration exceeds a limit, inspect the bearing".

Severity charts such as ISO 10816 are tables of such limits.

Today

Can a model learn rules of this kind from data, and which limits would it choose?

The bearings again

The training bearings of lecture 3, vibration against temperature. Healthy bearings cluster at low vibration; faulty ones spread to high vibration and temperature. The straight boundary of logistic regression runs diagonally and separates most of them.
Two features, 1000 training and 1000 test bearings, 10% of them faulty. Lecture 3 drew one straight boundary: 94.7% test accuracy.

Today in three choices

Model

a tree

nested yes or no questions on single features

Loss

local impurity

judged one split at a time

Optimiser

greedy splitting

no global loss, no gradient: the frame breaks

The plan

  1. Trees as partitions of the feature space
  2. Growing and pruning a tree
  3. Ensembles: forests and boosting

Exercise 2 implements the Gini impurity and the split search, then trains trees and forests.

Block 1

Trees as partitions

One split

Is the vibration at most 2.97 mm/s?

  • Yes: 925 bearings, 41 faulty
  • No: 75 bearings, 59 faulty

The limit was learned from the 1000 training bearings of lecture 3.

The bearing scatter plot divided by one vertical line at 2.97 mm/s into a predicted healthy region on the left and a predicted faulty region on the right.

Split again

A tree diagram. The root asks whether the vibration is at most 2.97. Its yes branch asks whether the temperature is at most 67.9, its no branch whether the vibration is at most 3.56. The four leaves hold 879 healthy and 27 faulty, 5 and 14, 15 and 15, and 1 and 44 bearings. The bearings below 8 mm/s, divided into four rectangular regions by a vertical line at 2.97, a horizontal segment at 67.9 degrees to its left, and a vertical line at 3.56 to its right.

Tree vocabulary

The tree of depth two: the root asks about the vibration at 2.97, its two children ask about the temperature at 67.9 and the vibration at 3.56, and four leaves hold the counts of healthy and faulty bearings.
  • Root: the first question, on all the bearings
  • Node: any box of the tree. An internal node asks a question; its two answers are the branches
  • Leaf: a node that asks nothing and predicts
  • Depth: the most questions on a path from the root to a leaf
  • A tree of depth 1 is a stump

A tree is a set of rules

if vibration ≤ 2.97:
    if temperature ≤ 67.9: healthy
    else: faulty
else:
    if vibration ≤ 3.56: healthy
    else: faulty

One rule per leaf, readable by the engineer who has to act on it.

The third leaf is a tie, 15 to 15. scikit-learn breaks ties towards the first class, healthy.

Predicting a new bearing

The tree of depth two, as on the previous slides.

A new bearing: 2.5 mm/s, 70 °C.

  1. Vibration ≤ 2.97? Yes: go left.
  2. Temperature ≤ 67.9? No: go right.
  3. Leaf: 5 healthy, 14 faulty. Predict faulty.

One path from the root to a leaf, one question per node. Features not asked on this path, and the other branches, are never looked at.

Reading a fitted tree

scikit-learn

tree = DecisionTreeClassifier(
    max_depth=2)
tree.fit(X_train, y_train)
names = ["vibration",
         "temperature"]
print(export_text(tree,
      feature_names=names))

Output

|--- vibration <= 2.97
|   |--- temperature <= 67.93
|   |   |--- class: 0
|   |--- temperature >  67.93
|   |   |--- class: 1
|--- vibration >  2.97
|   |--- vibration <= 3.56
|   |   |--- class: 0
|   |--- vibration >  3.56
|   |   |--- class: 1

The rules of the previous slides, printed by sklearn.tree.export_text. Class 0 is healthy, class 1 faulty. plot_tree draws the same tree as a diagram.

Leaves predict

A leaf predicts its majority class.

Its share of faulty bearings reads as a probability: 14 of 19 gives \(p = 0.74\).

The tied leaf gives \(p = 0.50\), the threshold of lecture 3.

The probability of a tree changes in steps, one value per leaf, while the sigmoid of lecture 3 changes smoothly.

Boxes, not lines

Two panels of the bearing data. Left, the logistic model of lecture 3 with one oblique straight boundary. Right, a tree of depth 3 whose boundary consists of horizontal and vertical segments.
Every split is a threshold on one feature, so every boundary segment is parallel to an axis.

Where a tree beats a line

Two panels of toy data in which a bearing is faulty above 6 mm/s or above 80 degrees. Left, the straight boundary of logistic regression cuts diagonally through both arms of the faulty corner. Right, a tree of depth 2 draws the corner with one vertical and one horizontal segment.
Toy data: faulty above 6 mm/s or above 80 °C, with 5% of the labels flipped. Two questions draw the corner, 95% on the test set; logistic regression reaches 78%.

Depth grows the boxes

Four panels of the bearing data with tree boundaries at depths 1, 2 and 4 and for the fully grown tree. The boundary becomes more fragmented with depth, and the fully grown tree draws small boxes around single bearings.
Fully grown: 71 leaves, 100% training accuracy, 90.5% test accuracy. Always healthy scores 90.0%.

Pure leaves, certain answers

Every leaf of the fully grown tree is pure.

So every bearing gets \(p = 0\) or \(p = 1\), never anything between.

A bearing in the overlap is called faulty with full confidence, or healthy with full confidence.

A ROC curve needs scores to rank. With two values there is one threshold to move, and the test AUC of the fully grown tree is 0.81, against 0.90 for logistic regression.

No scaling needed

A split compares one feature with a threshold.

Only the order of the values matters.

Standardising a feature moves its thresholds with it, and the tree stays the same.

The same holds for any change that keeps the order, such as the logarithm of the vibration: the threshold falls between the same two bearings.

Lecture 2 standardised the features before ridge, since the penalty compares the weights. A tree has no weights to compare.

Checkpoint

A tree is grown until every leaf is pure. What is its training error, and what does that tell you?

Block 2

Growing and pruning a tree

What makes a good split

Two panels of the bearing data. Left, the best vertical split on the vibration, which leaves a weighted impurity of 0.104. Right, the best horizontal split on the temperature, which leaves 0.136.
Children that are purer than their parent. The split on the vibration leaves less impurity, 0.104 against 0.136.

Gini impurity

\[ G = 1 - \sum_{k} p_k^2 \]

\(p_k\): the share of class \(k\) in the node

  • Pure node: \(G = 0\)
  • Half and half: \(G = 0.5\)
The Gini impurity and half the entropy against the proportion of faulty bearings in a node. Both are zero at 0 and 1, peak at 0.5, and have almost the same shape.

Why not the error rate?

\[ \text{parent: } 400 \text{ healthy}, 400 \text{ faulty} \]
\[ \text{split A: } (300, 100), (100, 300) \qquad \text{error } 0.25, \; G = 0.375 \]
\[ \text{split B: } (200, 400), (200, 0) \qquad \text{error } 0.25, \; G = 0.333 \]

The error rate cannot tell the splits apart. The Gini impurity prefers B, whose pure child needs no further question.

If both children keep the majority class of the parent, the error rate does not move at all, however much purer one child becomes. The impurity rewards every step towards purity.

Entropy and information gain

\[ H = -\sum_{k} p_k \log_2 p_k \]

The information gain of a split:

\[ \text{gain} = I(\text{parent}) - \sum_{c} \frac{n_c}{n}\, I(c) \]

\(I\) is either \(G\) or \(H\), and each child \(c\) counts by its share of the bearings. scikit-learn uses the Gini impurity by default, and criterion="entropy" rarely changes the tree.

Entropy in numbers

  • Pure node: \(H = 0\) bits
  • Half and half: \(H = 1\) bit, one fair yes or no
  • The bearings, 10% faulty: \(H = 0.469\) bits

Entropy counts the bits needed to name the class of a bearing from the node. With 10% faulty, a guess of healthy is usually right, so less than half a bit is missing.

A split, worked

\[ \text{parent: } 900 \text{ healthy}, 100 \text{ faulty} \qquad G = 1 - 0.9^2 - 0.1^2 = 0.180 \]
\[ \text{vibration} \le 2.97: \; 884, 41 \qquad G = 0.085 \]
\[ \text{vibration} > 2.97: \; 16, 59 \qquad G = 0.336 \]
\[ \tfrac{925}{1000} \cdot 0.085 + \tfrac{75}{1000} \cdot 0.336 = 0.104 \]

The gain is \(0.180 - 0.104 = 0.076\). The left child is nearly pure and carries most of the bearings, so it dominates the weighted sum.

Searching one feature

Sort the bearings by vibration.

Try every midpoint between neighbouring values as a threshold.

Keep the one with the lowest weighted impurity.

The weighted Gini impurity of the children against the threshold on the vibration. The curve starts at the impurity of the parent, 0.18, dips to a minimum of 0.104 at 2.97 mm/s, and rises again.

A split search by hand

Six bearings, sorted by vibration: 1.2, 1.8, 2.4 healthy, 3.1 faulty, 3.7 healthy, 4.5 faulty.

thresholdleftrightweighted Gini
1.5HH H F H F0.400
2.1H HH F H F0.333
2.75H H HF H F0.222
3.4H H H FH F0.417
4.1H H H F HF0.267

Any threshold between 2.4 and 3.1 makes the same split, so the five midpoints are all the candidates. The parent has \(G = 0.444\).

The best split on one feature

Pseudocode

input: x, y
sort x, y by x
for every split i:
    t ← midpoint of x[i−1], x[i]
    g ← weighted Gini
    keep (t, g) if g is lowest
return best (t, g)

numpy

order = np.argsort(x)
x, y = x[order], y[order]
n, best = len(y), (None, np.inf)
for i in range(1, n):
    if x[i] == x[i - 1]:
        continue
    t = (x[i] + x[i - 1]) / 2
    left = i * gini(y[:i])
    right = (n - i) * gini(y[i:])
    g = (left + right) / n
    if g < best[1]:
        best = (t, g)
return best

Greedy, recursively

  1. Search every feature, keep the best split
  2. Split the node in two
  3. Repeat in each child, until a stopping rule holds

Finding the best tree outright is NP-complete: no efficient exact method is known. So the tree is grown one best split at a time, and a split is never revisited.

Growing the bearing tree

Left child: 925 bearings, 41 faulty, \(G = 0.085\)

  • vibration ≤ 2.32: 0.081
  • temperature ≤ 67.9: 0.065

Right child: 75 bearings, 59 faulty, \(G = 0.336\)

  • vibration ≤ 3.56: 0.226
  • temperature ≤ 59.6: 0.250

The same search, run in each child, gives the tree of block 1. Each child chooses its own feature.

Where the frame breaks

Model

a tree

its structure is discrete, not a vector of weights

Loss

local impurity

one node at a time, no loss over the whole tree

Optimiser

greedy splitting

no gradient: the frame breaks

Regression trees

For a numerical target:

  • impurity: the variance of the targets in the node
  • a leaf predicts their mean

The saturation of the turbine, which defeated the line of lecture 1, is one leaf at depth 2.

Turbine power against wind speed with the step functions of regression trees of depths 1, 2 and 4. Depth 1 has two levels; depth 4 follows the ramp in steps and the plateau near 2000 kilowatts.

A regression split, worked

\[ \text{parent: 100 readings, variance } 4.60 \times 10^5 \text{ kW}^2 \]
\[ \text{wind} \le 8.98 \text{ m/s}: \; 68 \text{ readings, mean } 202 \text{ kW}, \; \text{variance } 0.48 \times 10^5 \]
\[ \text{wind} > 8.98 \text{ m/s}: \; 32 \text{ readings, mean } 1508 \text{ kW}, \; \text{variance } 1.75 \times 10^5 \]
\[ 0.68 \cdot 0.48 \times 10^5 + 0.32 \cdot 1.75 \times 10^5 = 0.89 \times 10^5 \]

The split removes 81% of the variance. Each leaf predicts its mean: 202 kW below 8.98 m/s, 1508 kW above. Boosting in block 3 grows these trees on residuals.

Stopping early

  • max_depth
  • min_samples_leaf

Choose them by cross-validation, as the degree in lecture 2.

Here: depth 3, with a validation accuracy of 94.7%.

Training and cross-validated accuracy against the maximum depth from 1 to 12. Training accuracy rises towards 1, while validation accuracy peaks at depth 3 and falls afterwards.

Pruning: grow, then cut back

\[ \loss_\alpha(T) = R(T) + \alpha\, |T| \]

\(R(T)\): the impurity left in the leaves, each weighted by its share of the bearings. \(|T|\): the number of leaves.

\[ \text{lecture 2:} \quad \frac{1}{n}\lVert \vy - \mPhi\vw \rVert^2 + \lambda \lVert \vw \rVert^2 \]

Fit plus a penalty on size, with one knob. For each \(\alpha\) the best subtree of the grown tree can be found exactly, so a global objective is back.

Weakest-link pruning

\[ \alpha_t = \frac{R(t) - R(T_t)}{|T_t| - 1} \]

\(T_t\): the branch below node \(t\). \(R(t)\): the impurity if \(t\) were a leaf. \(\alpha_t\) is the impurity that the branch removes per extra leaf.

Cut the branch with the smallest \(\alpha_t\), recompute, and repeat until only the root is left.

On the bearings: 29 values of \(\alpha\), two of them equal, for a nested sequence of 28 trees from 71 leaves down to 1. Between two neighbouring values the pruned tree does not change, so these values are all the candidates, as the midpoints were for thresholds.

Choosing \(\alpha\)

Every candidate \(\alpha\) gives one pruned tree.

Cross-validation picks \(\alpha = 0.0020\): 10 leaves instead of 71.

Cross-validated accuracy against alpha on a logarithmic axis, with the number of leaves on a second axis. The accuracy peaks at alpha 0.0020, where the tree has 10 leaves.

What pruning removes

Two panels of the bearing data. Left, the fully grown tree with 71 leaves and many small boxes around single bearings. Right, the pruned tree with 10 leaves, which keeps the main boundary around the healthy cluster and drops the small boxes.
Fully grown: 71 leaves, 90.5% on the test bearings. Pruned at \(\alpha = 0.0020\): 10 leaves, 93.3%. The boxes around single bearings go first, since each removes little impurity for the leaves it adds.

The bridge to scikit-learn

tree = DecisionTreeClassifier()
path = tree.cost_complexity_pruning_path(X, y)
path.ccp_alphas   # the candidate values

DecisionTreeClassifier(ccp_alpha=a)

The default ccp_alpha=0 does not prune. Search the candidate values with cross-validation, as for \(\lambda\) in lecture 2.

Checkpoint

Two features, two classes arranged like a chessboard in four quadrants. What does the first greedy split achieve?

The chessboard, drawn

Three panels of 400 toy points. Left, the weighted Gini impurity of the first split against its threshold on x1, flat near 0.5 with its lowest point at 0.59. Middle, the greedy tree of depth 2, whose first split at 0.59 leaves the quadrants mixed. Right, the greedy tree of depth 3, which separates the four quadrants.
The best first split, at 0.59, lowers the Gini impurity only from 0.500 to 0.488. The greedy tree of depth 2 then reaches 73.0% of the points; splitting at 0 on x1, then at 0 on x2 in each child, would reach 100%. Depth 3 recovers, at 99.8%.

Break

Ten minutes

Block 3

Ensembles

Trees are unstable

Two panels, each with its own training set of 1000 bearings drawn from the same generator and the boundary of a fully grown tree. The boxes differ widely between the panels. A star marks one faulty test bearing at 3.03 mm/s and 64.5 degrees, which the left tree calls faulty and the right tree healthy.
Fully grown trees on two training sets from the same factory. Over twenty such sets, 10 of the 20 trees call the starred faulty bearing faulty, and the trees do not all agree on 45% of the test bearings.

Averaging reduces variance

Average \(B\) models, each with variance \(\sigma^2\) and independent of the others:

\[ \mathrm{Var}\Big(\frac{1}{B} \sum_{b=1}^{B} \hat f_b(\vx)\Big) = \frac{\sigma^2}{B} \]

The bias stays: the average is off by as much as one model is.

The catch

Independent models need independent training sets, and we have one set of 1000 bearings.

As in lecture 2, a flexible model such as a deep tree has low bias and high variance, which the previous slide showed. The variance is what averaging should remove.

Bagging: make the training sets from the one we have with the bootstrap, then average the trees grown on them.

The bootstrap

Draw \(n\) bearings from the \(n\), with replacement.

Eight bearings, numbered 1 to 8, give for instance 2 2 7 4 5 5 6 1.

Bearings 2 and 5 appear twice, 3 and 8 not at all.

Each draw is a new training set of the same size, taken from the data instead of from the factory.

Efron, 1979. The bootstrap was made to measure the uncertainty of a statistic. Here it makes many training sets out of one.

What a bootstrap sample holds

\[ P(\text{a bearing is never drawn}) = \Big(1 - \frac{1}{n}\Big)^{n} \]
\[ n = 1000: \quad 0.368 \approx e^{-1} \]

About 37% of the bearings are left out of each sample, and about 63% appear at least once.

Sample 1 of the next slide: 368 bearings never drawn, 355 once, 198 twice, 79 three or four times.

The same with bootstrap samples

Two panels of the bearing data with the boundaries of two fully grown trees, each trained on a different bootstrap sample. The boundaries differ visibly, with 39 and 45 leaves.
Fully grown trees on bootstrap samples 1 and 2 of the 1000 training bearings. The first split moves from 3.49 to 3.20 mm/s, and everything below it changes, as between fresh training sets.

Bagging

Pseudocode

input: X, y, B
repeat B times:
    draw n rows with
        replacement
    grow a full tree
        on those rows
predict: the average of
    the B probabilities
    of faulty

Python

rng = np.random.default_rng(seed)
n, probs = len(y), []
for b in range(B):
    rows = rng.integers(0, n, n)
    tree = DecisionTreeClassifier(
        random_state=0)
    tree.fit(X[rows], y[rows])
    p = tree.predict_proba(X_new)
    probs.append(p[:, 1])
return np.mean(probs, axis=0)

Bagging, in pictures

Three panels of the bearing data with the boundary of 1, 10 and 300 bagged trees. One tree cuts the overlap of the classes into narrow vertical strips; 300 trees draw a boundary that follows the edge of the healthy cluster in fine steps.
The average of 1, 10 and 300 bagged trees. One tree cuts the overlap into narrow strips; the average of 300 follows the edge of the healthy cluster.

Out-of-bag error

Each tree misses about 37% of the bearings.

Predict each bearing with only the trees that never saw it, and score these predictions.

oob_score=True, then read oob_score_.

A validation estimate without a separate split. 300 bagged trees: out-of-bag accuracy 93.7%, test accuracy 93.2%.

Where averaging stops

\[ \mathrm{Var}\Big(\frac{1}{B} \sum_{b=1}^{B} \hat f_b(\vx)\Big) = \rho\, \sigma^2 + \frac{1 - \rho}{B}\, \sigma^2 \]

\(\rho\): the correlation between two trees. The bootstrap samples overlap and come from the same data, so \(\rho > 0\).

\[ B \to \infty: \quad \rho\, \sigma^2 \]

More trees remove only the second term. To go lower, make the trees less alike.

Checkpoint

Three hundred bagged trees turn out to be identical. What does averaging them gain?

Bagged trees are alike

The vibration separates the bearings best, so nearly every bootstrap sample finds it first.

298 of the 300 bagged trees split on the vibration at the root.

ISLP 8.2.2: with one strong feature, the bagged trees look alike, and their predictions are strongly correlated.

Random forests

Bagging, plus one change: at each split, draw \(m\) of the \(p\) features at random, and search only those.

\(m = p\) is bagging. A smaller \(m\) makes the trees less alike.

The default for a classifier: \(m = \sqrt{p}\), max_features="sqrt".

With two features, \(\sqrt{2}\) rounds down to 1: each split searches one feature, chosen at random.

Random forest

Pseudocode

input: X, y, B, m
repeat B times:
    draw n rows with
        replacement
    grow a full tree; at
        every split, search
        m random features
predict: the average of
    the B probabilities

scikit-learn

forest = RandomForestClassifier(
    n_estimators=300,
    max_features="sqrt",
    oob_score=True)
forest.fit(X, y)
forest.oob_score_
forest.predict_proba(X_new)

On two features

baggingforest
root split on vibration298 of 300140 of 300
test bearings on which two trees disagree6.5%6.9%
out-of-bag accuracy93.7%93.9%
test AUC0.900.90

The roots differ, yet two trees disagree on barely more test bearings, and the two ensembles score alike.

With two features, a forest has little room. ISLP 8.2.2 expects a small \(m\) to help most with many correlated features, and reports a small gain over bagging on 500 genes.

The forest boundary

Two panels of the bearing data. Left, the fragmented boundary of one fully grown tree with small boxes around single bearings. Right, the smoother boundary of a random forest of 300 trees, with fewer isolated boxes.
Still axis-aligned steps, but most of the boxes around single bearings are gone.

More trees

Test AUC against the number of trees on a logarithmic axis from 1 to 300, for bagging and the random forest, with the AUC of logistic regression as a dashed line near 0.90. Both curves rise from below 0.79 with one tree to about 0.90 and are flat after 100 trees.
One tree: AUC 0.78 to 0.79. Three hundred: 0.90 for both, as for logistic regression. After 100 trees the curves are flat.

A forest's settings

parameterdefaulteffect
n_estimators100more trees: steadier and slower
max_features"sqrt"fewer: trees less alike; None: bagging
min_samples_leaf1larger: smaller trees
max_depthNonetrees grown fully
oob_scoreFalseTrue: the out-of-bag estimate

On the bearings, min_samples_leaf=5 raises the out-of-bag accuracy of the forest from 93.9% to 94.9%.

Two importances

Impurity-based

For every split on the feature, the impurity decrease, weighted by the bearings in the node. Summed over the tree, scaled to sum to 1, averaged over the trees.

On the training data: feature_importances_

Permutation

Shuffle one column of the test data, and measure the drop in accuracy. Repeat, and average.

On the test data: permutation_importance

Feature importance

Two bar charts of the importance of vibration, temperature and two columns of pure noise. Left, impurity-based importance gives each noise column about 0.09. Right, permutation importance on test data puts both noise columns near zero.
Two columns of pure noise were added. The impurity-based importance gives each about 9%, while shuffling them on the test bearings costs nothing.

From averaging to adding

Forests

Deep trees: low bias, high variance.

Grown independently, then averaged. The average removes variance, and the bias stays.

Boosting

Small trees: high bias, low variance.

Grown one after another, each fitted to what the ensemble still gets wrong. Adding them lowers the bias.

What is left is easiest to see on a curve, so boosting starts on the turbine and the regression trees of block 2. It returns to the bearings in the comparison of models.

Boosting fits what is left

Four panels of turbine power against wind speed with the prediction of a boosted ensemble after 1, 2, 5 and 50 small trees. After one tree the prediction is a single step, after five the plateau appears, and after fifty the curve follows the data closely.
Start from the mean. Each new small tree is fitted to the residuals \(y - F(\vx)\) of the ensemble so far, and added, scaled by 0.3.

The first step, drawn

Three panels of turbine power against wind speed. Left, the data with a flat line at the mean of 620 kilowatts. Middle, the residuals, negative below about 8 m/s and positive above, with a step function of a tree of depth 2 fitted to them. Right, the data with the mean plus 0.3 times the tree, a staircase rising from about 460 to about 1010 kilowatts.
Start from the mean, 620 kW. The residuals \(y - F_0\) are what the mean gets wrong. A tree of depth 2 fits them, and 0.3 times its steps is added. The next tree fits what is still left.

Gradient boosting

Pseudocode

input: X, y, M, η
F ← the mean of y, every row
repeat M times:
    r ← y − F, the residuals
    fit a small tree h to r
    F ← F + η h(X)
predict: the mean of y
    plus η times every h

Python

F = np.full(len(y), y.mean())
F_new = np.full(len(X_new), F[0])
for m in range(M):
    r = y - F
    tree = DecisionTreeRegressor(
        max_depth=2, random_state=0)
    tree.fit(X, r)
    F += rate * tree.predict(X)
    F_new += rate * tree.predict(
        X_new)
return F_new

Shrinkage

\[ F_m(\vx) = F_{m-1}(\vx) + \eta\, h_m(\vx) \]

\(\eta\): the learning rate, as in lecture 1

\(\eta = 1.0\): best after 6 trees. \(\eta = 0.1\): best after 37 trees.

After that, the test error rises again.

Test and training RMSE against the number of trees on a logarithmic axis, for learning rates 1.0 and 0.1. Training error keeps falling, while test error falls to a minimum and rises again, later for the smaller learning rate.

Why small trees

Test RMSE against the number of trees on a logarithmic axis, for boosted trees of depths 1, 2, 4 and 8 at a learning rate of 0.1. All curves fall steeply over the first 20 trees. Depth 8 bottoms out first and highest, near 168 kW; depth 1 bottoms out last and lowest, near 124 kW, and stays flat.
Test error at \(\eta = 0.1\) for trees of depth 1, 2, 4 and 8. Deeper trees reach their best sooner, and their best is worse: 123.5 kW with stumps against 167.8 kW at depth 8.

Where the frame returns

Model

a sum of trees

\(F(\vx) = F_0 + \sum_m \eta\, h_m(\vx)\)

Loss

squared error

one loss over the whole ensemble again

Optimiser

gradient descent

the residual \(y - F\) is the negative gradient of \(\tfrac12 (y - F)^2\): each step adds a tree

Boosting for classes

\[ p = \sigma\big(F(\vx)\big), \qquad \ell = -y \log p - (1 - y) \log(1 - p) \]

The sum of trees \(F\) is a score, as \(z = \vw\T\vx\) was in lecture 3, and the loss is the cross-entropy.

\[ -\frac{\partial \ell}{\partial F} = y - p \]

Lecture 3 derived this gradient. Each tree is fitted to \(y - p\), the residual on the scale of probabilities.

The start is the log-odds of the training data: \(F_0 = \log(0.1 / 0.9) = -2.20\), so every bearing begins at \(p = 0.1\).

The practical default

test bearingsaccuracyAUC
always healthy90.0%0.50
logistic regression94.7%0.90
pruned tree93.3%0.87
random forest93.7%0.90
gradient boosting92.8%0.90

Two features and a boundary close to a line: the line is enough.

No model wins everywhere. On tabular data with many features and interactions, try HistGradientBoostingClassifier next to a simple baseline.

The practical tool

setting of HistGradientBoostingClassifierdefaultmeaning
learning_rate0.1\(\eta\) of the shrinkage slide
max_iter100the number of trees
max_leaf_nodes31the size of each tree
early_stopping"auto"above 10,000 samples, stop when a validation split stops improving

"Hist": each feature is first cut into at most 255 bins, so the split search tries at most 254 thresholds instead of one per sample. It also accepts missing values without imputation.

Checkpoint

You keep adding trees. Which one can overfit: the random forest or the boosted model?

Bagging and boosting side by side

bagging, random forestsboosting
treesdeep, each on its own samplesmall, each fitted to the residuals
builtindependently, in parallelone after another
reducesthe variancethe bias, step by step
more treessteadier, then flateventually overfit
main settingmax_featuresthe learning rate and the number of trees

Takeaways

  1. A tree is a set of rules that cuts the feature space into boxes.
  2. Splits are chosen greedily, by the impurity they leave.
  3. Depth limits and pruning control overfitting, and pruning is a penalty again.
  4. The bootstrap makes many training sets out of one.
  5. Averaging trees grown on them reduces the variance, down to a floor set by how alike the trees are: bagging and random forests.
  6. Boosting is gradient descent in which each step is a tree.

Choosing a model

reads asto tunereach for it when
logistic regressionweightslittle; scale the featuresthe boundary is close to a line
one treerulesdepth or \(\alpha\)the decision must be explained
random forestimportanceslittle; the defaults worka strong first model on a table
gradient boostingpermutation importance\(\eta\), trees, tree sizeaccuracy matters most on a table

Always next to a simple baseline: on the bearings, the line was enough.

Lecture 4 in three choices

Model

a tree, a sum of trees

boxes, and for ensembles many of them

Loss

local impurity

a global loss returns with pruning and boosting

Optimiser

greedy splitting

the change from lecture 3: the frame breaks, and boosting restores it

Further reading

Both books are free to read online. Understanding Deep Learning returns in lecture 5.

Next

Lecture 5

Neural networks: from logistic regression to a neuron, and the chessboard of today as the XOR problem.

Exercise 2

Grid stability: logistic regression in numpy and its evaluation, then the Gini impurity, the split search, trees and forests.

It uses lectures 3 and 4.