Lecture 4
Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027
A maintenance engineer: "if the vibration exceeds a limit, inspect the bearing".
Severity charts such as ISO 10816 are tables of such limits.
Can a model learn rules of this kind from data, and which limits would it choose?
a tree
nested yes or no questions on single features
local impurity
judged one split at a time
greedy splitting
no global loss, no gradient: the frame breaks
Exercise 2 implements the Gini impurity and the split search, then trains trees and forests.
Block 1
Is the vibration at most 2.97 mm/s?
The limit was learned from the 1000 training bearings of lecture 3.
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.
A new bearing: 2.5 mm/s, 70 °C.
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.
tree = DecisionTreeClassifier(
max_depth=2)
tree.fit(X_train, y_train)
names = ["vibration",
"temperature"]
print(export_text(tree,
feature_names=names))
|--- 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.
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.
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.
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
Block 2
\(p_k\): the share of class \(k\) in the node
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.
The information gain of a split:
\(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 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.
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.
Sort the bearings by vibration.
Try every midpoint between neighbouring values as a threshold.
Keep the one with the lowest weighted impurity.
Six bearings, sorted by vibration: 1.2, 1.8, 2.4 healthy, 3.1 faulty, 3.7 healthy, 4.5 faulty.
| threshold | left | right | weighted Gini |
|---|---|---|---|
| 1.5 | H | H H F H F | 0.400 |
| 2.1 | H H | H F H F | 0.333 |
| 2.75 | H H H | F H F | 0.222 |
| 3.4 | H H H F | H F | 0.417 |
| 4.1 | H H H F H | F | 0.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\).
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)
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
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.
The same search, run in each child, gives the tree of block 1. Each child chooses its own feature.
a tree
its structure is discrete, not a vector of weights
local impurity
one node at a time, no loss over the whole tree
greedy splitting
no gradient: the frame breaks
For a numerical target:
The saturation of the turbine, which defeated the line of lecture 1, is one leaf at depth 2.
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.
max_depthmin_samples_leafChoose them by cross-validation, as the degree in lecture 2.
Here: depth 3, with a validation accuracy of 94.7%.
\(R(T)\): the impurity left in the leaves, each weighted by its share of the bearings. \(|T|\): the number of leaves.
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.
\(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.
Every candidate \(\alpha\) gives one pruned tree.
Cross-validation picks \(\alpha = 0.0020\): 10 leaves instead of 71.
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
Break
Block 3
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.
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.
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.
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.
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
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)
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%.
\(\rho\): the correlation between two trees. The bootstrap samples overlap and come from the same data, so \(\rho > 0\).
More trees remove only the second term. To go lower, make the trees less alike.
Checkpoint
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.
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.
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
forest = RandomForestClassifier(
n_estimators=300,
max_features="sqrt",
oob_score=True)
forest.fit(X, y)
forest.oob_score_
forest.predict_proba(X_new)
| bagging | forest | |
|---|---|---|
| root split on vibration | 298 of 300 | 140 of 300 |
| test bearings on which two trees disagree | 6.5% | 6.9% |
| out-of-bag accuracy | 93.7% | 93.9% |
| test AUC | 0.90 | 0.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.
| parameter | default | effect |
|---|---|---|
n_estimators | 100 | more trees: steadier and slower |
max_features | "sqrt" | fewer: trees less alike; None: bagging |
min_samples_leaf | 1 | larger: smaller trees |
max_depth | None | trees grown fully |
oob_score | False | True: 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%.
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_
Shuffle one column of the test data, and measure the drop in accuracy. Repeat, and average.
On the test data: permutation_importance
Deep trees: low bias, high variance.
Grown independently, then averaged. The average removes variance, and the bias stays.
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.
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
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
\(\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.
a sum of trees
\(F(\vx) = F_0 + \sum_m \eta\, h_m(\vx)\)
squared error
one loss over the whole ensemble again
gradient descent
the residual \(y - F\) is the negative gradient of \(\tfrac12 (y - F)^2\): each step adds a tree
The sum of trees \(F\) is a score, as \(z = \vw\T\vx\) was in lecture 3, and the loss is the cross-entropy.
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\).
| test bearings | accuracy | AUC |
|---|---|---|
| always healthy | 90.0% | 0.50 |
| logistic regression | 94.7% | 0.90 |
| pruned tree | 93.3% | 0.87 |
| random forest | 93.7% | 0.90 |
| gradient boosting | 92.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.
setting of HistGradientBoostingClassifier | default | meaning |
|---|---|---|
learning_rate | 0.1 | \(\eta\) of the shrinkage slide |
max_iter | 100 | the number of trees |
max_leaf_nodes | 31 | the 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
| bagging, random forests | boosting | |
|---|---|---|
| trees | deep, each on its own sample | small, each fitted to the residuals |
| built | independently, in parallel | one after another |
| reduces | the variance | the bias, step by step |
| more trees | steadier, then flat | eventually overfit |
| main setting | max_features | the learning rate and the number of trees |
| reads as | to tune | reach for it when | |
|---|---|---|---|
| logistic regression | weights | little; scale the features | the boundary is close to a line |
| one tree | rules | depth or \(\alpha\) | the decision must be explained |
| random forest | importances | little; the defaults work | a strong first model on a table |
| gradient boosting | permutation importance | \(\eta\), trees, tree size | accuracy matters most on a table |
Always next to a simple baseline: on the bearings, the line was enough.
a tree, a sum of trees
boxes, and for ensembles many of them
local impurity
a global loss returns with pruning and boosting
greedy splitting
the change from lecture 3: the frame breaks, and boosting restores it
Both books are free to read online. Understanding Deep Learning returns in lecture 5.
Neural networks: from logistic regression to a neuron, and the chessboard of today as the XOR problem.
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.