Module 7/15 · Weeks 7 · 9 h

Supervised learning, classification and metrics for imbalanced data

UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS

About 100 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Read a classifier's results with the confusion matrix, precision, recall, F1, MCC and the areas under the ROC and precision-recall curves when positives are rare
  2. Explain the principle and the key settings of logistic regression, SVM, decision trees, random forests and gradient boosting
  3. Choose a model family that suits the shape of the data, and tell when a domain-knowledge feature beats a more complex model
  4. Detect overfitting from tree depth and from the number of boosting trees
  5. Select a model with validation that matches the deployment question, then report the test result once against the technicians' rule

Prerequisites: Module 6 of this course and UAT 306 Artificial Intelligence for UAS (module 2)

Why this matters

Module 6 ended with a clean, correctly split table of fleet flights. The next step is to choose a classification algorithm and measure it properly. Two questions are often confused. The first is how to measure when only about 10% of the labels are positive. The second is which model family to use among logistic regression, SVM, decision trees, random forests and gradient boosting. This module uses two tasks. The first predicts which drone motors will fail within 21 days (the fleet from module 6). The second classifies badly closed bottle caps from the torque of the capping machine on the bottling line, where the relationship is not a straight line. The knowledge unit on machine-learning fundamentals has an example of “96.6% accuracy that loses to guessing”; this module extends that idea into a full set of metrics. Writing logistic regression from scratch belongs to UAT 306 module 2; here the library is called directly. All data is synthetic and all numbers are assumed.

The data used in this module

Examples 1 and 5 use the same fleet table as module 6 (the function make_fleet is identical, line for line), split into a training period (before day 250) and a test period (after it). This matches the question “same airframes, future flights”. The test period is touched once, in Example 5.

import numpy as np, pandas as pd

def make_fleet(seed=482, n_drones=40, days=365, drift_day=None):          # same as module 6
    rng = np.random.default_rng(seed)
    rows, fails = [], []
    for d in range(n_drones):
        base = rng.normal([9.0, 24.0, 18.0], [4.0, 3.0, 2.0])
        life = int(rng.integers(60, 160))
        day, f = int(rng.integers(0, 40)), int(rng.integers(0, life - 10))
        while day < days:
            wear = (f / life) ** 3
            amb, load = rng.normal(31, 3), rng.normal(1.2, 0.4)
            shift = 2.5 if drift_day is not None and day >= drift_day else 0.0
            rows.append(dict(drone=d, day=day, hours=f * 0.4,
                             vib=base[0] + 11 * wear + shift + rng.normal(0, 1.5),
                             temp=base[1] + 7 * wear + 0.3 * (amb - 31) + rng.normal(0, 1.2),
                             amps=base[2] + 3 * wear + 1.5 * (load - 1.2) + rng.normal(0, 0.8),
                             ambient=amb, payload=load))
            f, day = f + 1, day + int(rng.integers(1, 4))
            if f == life:
                if day < days: fails.append(dict(drone=d, day=day, motor_hours=life * 0.4))
                f, life = 0, int(rng.integers(60, 160))
    return pd.DataFrame(rows), pd.DataFrame(fails).sort_values("day").reset_index(drop=True)

flights, fails = make_fleet()
flights = flights.sort_values("day").reset_index(drop=True)
nxt = pd.merge_asof(flights, fails.rename(columns={"day": "fail_day"}), left_on="day", right_on="fail_day", by="drone", direction="forward")
nxt["days_left"] = nxt.fail_day - nxt.day
data = nxt[nxt.days_left.notna() | (nxt.day + 21 <= 364)].copy()          # warn 21 days ahead; rows at the end of the log are dropped
data["fault"] = (data.days_left <= 21).astype(int)
data = data.sort_values(["drone", "day"]).reset_index(drop=True)
for c in ("vib", "temp", "amps"):
    data[c + "_r5"] = data.groupby("drone")[c].transform(lambda s: s.rolling(5, min_periods=1).mean())

FEATURES = ["vib", "temp", "amps", "hours", "ambient", "payload", "vib_r5", "temp_r5", "amps_r5"]
train = data.day < 250                                                      # train on the past; test on the future once, at the end
Xtr, ytr, gtr, dtr = data.loc[train, FEATURES], data.fault[train], data.drone[train], data.day[train]
Xte, yte = data.loc[~train, FEATURES], data.fault[~train]
print(f"training period: {len(Xtr)} flights, {ytr.sum()} positive ({ytr.mean():.3f}); test period: {len(Xte)} flights, {yte.sum()} positive ({yte.mean():.3f})")
training period: 4508 flights, 465 positive (0.103); test period: 1896 flights, 214 positive (0.113)

Metrics for imbalanced data

The confusion matrix counts four outcomes: TP (alerted and failed), FP (alerted but did not fail), FN (not alerted but failed) and TN (not alerted and did not fail). Each metric looks at this table from a different angle.

  • accuracy is the share predicted correctly; it is swamped by the large class when positives are rare.
  • precision : of the flights alerted, how many really fail. Whether technicians trust the system depends on this.
  • recall : of the flights that were really close to failing, how many were caught. This is tied to the risk of a motor failing mid-job.
  • F1 is the harmonic mean of the previous two.
  • balanced accuracy is the mean of the recall of each class; predicting the large class every time scores 0.5.
  • MCC (Matthews correlation coefficient) uses all four cells, is 0 when no better than guessing and 1 when always right, so imbalance cannot fool it.

These metrics depend on the threshold (0.5 by default). To measure the quality of the ranking of scores independently of the threshold, use the areas under two curves. The ROC curve plots the catch rate (recall) against the false-alarm rate of healthy flights ; the area under it (ROC-AUC) is the probability that a randomly chosen risky flight scores higher than a randomly chosen healthy one. The precision-recall curve plots precision against recall; the area under it (PR-AUC, or average precision) is computed as . A predictor with no knowledge scores a ROC-AUC of 0.5 but a PR-AUC equal to the prevalence. Saito and Rehmsmeier (2015) compared the two curves and concluded that the precision-recall plot is more informative on imbalanced data, because the false-alarm rate divides by the many healthy flights, so hundreds of false alarms still look like a small rate. Chicco and Jurman (2020) recommend MCC over F1 and accuracy for two-class classification.

Example 1 Metrics of a baseline and of logistic regression

Compare three models on the training period using five airframe folds (each flight’s prediction comes from the fold that was not used for training). The first predicts healthy for every flight. The second is logistic regression with standardised features. The third is the same as the second but gives positives more weight (class_weight="balanced"). Threshold-dependent metrics are computed at 0.5; ROC-AUC and PR-AUC are means over the 5 folds.

from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, f1_score, matthews_corrcoef, balanced_accuracy_score
from sklearn.model_selection import StratifiedGroupKFold, cross_val_predict, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

cv = StratifiedGroupKFold(5, shuffle=True, random_state=0)                  # split by airframe inside the training period
models = {"always healthy": DummyClassifier(strategy="prior"),
          "logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
          "logistic balanced": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000, class_weight="balanced"))}
oof = {}
print("model               TP  FP  FN   TN  acc   prec  recall  F1    MCC   bal.acc  ROC-AUC  PR-AUC")
for name, model in models.items():
    oof[name] = cross_val_predict(model, Xtr, ytr, cv=cv, groups=gtr, method="predict_proba")[:, 1]
    pred = (oof[name] >= 0.5).astype(int)                                   # default threshold 0.5
    tn, fp, fn, tp = confusion_matrix(ytr, pred).ravel()
    roc, ap = (cross_val_score(model, Xtr, ytr, cv=cv, groups=gtr, scoring=s).mean() for s in ("roc_auc", "average_precision"))
    print(f"{name:<19}{tp:>4}{fp:>5}{fn:>5}{tn:>5}  {(pred == ytr).mean():.3f} {tp / max(tp + fp, 1):>5.2f} {tp / (tp + fn):>6.2f}  {f1_score(ytr, pred):.2f}  {matthews_corrcoef(ytr, pred):.2f}   {balanced_accuracy_score(ytr, pred):.2f}    {roc:.3f}    {ap:.3f}")
model               TP  FP  FN   TN  acc   prec  recall  F1    MCC   bal.acc  ROC-AUC  PR-AUC
always healthy        0    0  465 4043  0.897  0.00   0.00  0.00  0.00   0.50    0.500    0.103
logistic            150  122  315 3921  0.903  0.55   0.32  0.41  0.37   0.65    0.918    0.617
logistic balanced   373  758   92 3285  0.811  0.33   0.80  0.47  0.43   0.81    0.914    0.623

Predicting healthy every time scores accuracy 0.897, almost the same as logistic regression (0.903) and above the weighted model (0.811), although it is useless (recall 0 and MCC 0). Accuracy therefore cannot be used to compare these models. Logistic regression at threshold 0.5 reaches precision 0.55 but recall only 0.32: it catches 150 of 465 flights. When the positives get more weight, recall becomes 0.80 (373 flights caught) but precision falls to 0.33 because false alarms grow from 122 to 758. The summary metrics MCC (0.37 to 0.43) and balanced accuracy (0.65 to 0.81) rise because they are tied to recall, while ROC-AUC (0.918 against 0.914) and PR-AUC (0.617 against 0.623) barely change. The two models rank flights almost identically; what differs is the chosen operating point. Two conclusions follow. First, re-weighting or moving the threshold slides along the same curve; it does not make the model better. Second, that point must be chosen from the cost of the work (module 10).

Grouped bar chart with three groups for three models and four bars each: accuracy, precision, recall and MCC. Always healthy: accuracy 0.897, the others 0. Logistic regression: 0.903, 0.55, 0.32, 0.37. Weighted logistic regression: 0.811, 0.33, 0.80, 0.43
Figure 1 Metrics at threshold 0.5 for three models

Each metric also answers differently when the prevalence changes, which happens when a model moves to another fleet. The next example re-weights the healthy flights to simulate a prevalence of 2%, 5%, 10.6% and 30% for the same model (computed from the same scores; nothing is retrained).

Example 1 (continued) When prevalence changes, ROC-AUC stays put but precision moves

from sklearn.metrics import average_precision_score, roc_auc_score
p = oof["logistic"]
n_pos, n_neg = int(ytr.sum()), int((ytr == 0).sum())
print("prevalence  ROC-AUC  PR-AUC  precision at 0.5")
for pi in (0.02, 0.05, 0.106, 0.30):
    w = np.where(ytr == 1, 1.0, n_pos * (1 - pi) / (pi * n_neg))             # weight the negatives so that the prevalence equals pi
    flag = p >= 0.5
    prec = (w * (flag & (ytr == 1))).sum() / (w * flag).sum()
    print(f"{pi:>9.3f}  {roc_auc_score(ytr, p, sample_weight=w):>7.3f}  {average_precision_score(ytr, p, sample_weight=w):>6.3f}  {prec:>16.3f}")
logit = models["logistic"].fit(Xtr, ytr)
odds = np.exp(logit[-1].coef_[0])                                           # odds ratio per 1 SD of each feature
print("odds ratio per 1 SD:", ", ".join(f"{f} {o:.2f}" for f, o in sorted(zip(FEATURES, odds), key=lambda t: -t[1])[:4]))
prevalence  ROC-AUC  PR-AUC  precision at 0.5
    0.020    0.898   0.186             0.179
    0.050    0.898   0.341             0.360
    0.106    0.898   0.511             0.559
    0.300    0.898   0.767             0.821
odds ratio per 1 SD: vib_r5 5.72, temp_r5 3.80, hours 2.16, amps_r5 1.10

This table is computed from the pooled scores of all 5 folds at once, so it differs from the per-fold averages in the previous table (ROC-AUC 0.918, PR-AUC 0.617). ROC-AUC stays at 0.898 for every prevalence because it measures how well risky flights are ranked above healthy ones, which does not depend on the proportions. PR-AUC and precision change a lot. At a prevalence of 2%, precision at threshold 0.5 drops to 0.179; at 30% it is 0.821. Same model, same scores, and the number technicians see differs by almost a factor of five. This agrees with UAT 306 module 1: precision depends on prevalence. Machine-learning results must always state the prevalence of the data they were measured on, and the precision to expect in the field must be projected from the prevalence of the fleet where the model will be used.

Line chart with prevalence 0.02, 0.05, 0.106 and 0.30 on the horizontal axis. The pink ROC-AUC line is flat at 0.898. The green PR-AUC line rises from 0.186 to 0.341, 0.511 and 0.767
Figure 2 ROC-AUC and PR-AUC of one model as the prevalence changes

Logistic regression on the fleet data

Logistic regression predicts a probability (the derivation and training by gradient descent are in UAT 306). Its strength is that it can be explained. After the features are standardised, is the odds ratio for a one-standard-deviation (SD) increase in the feature. In Example 1 the mean vibration of the last 5 flights (vib_r5) has an odds ratio of 5.72: if recent vibration is one SD higher with the other features unchanged, the odds that the motor fails are 5.72 times larger. Next come temp_r5 at 3.80 and hours at 2.16. The model is fast, stable and a good baseline, but it assumes that the log-odds change linearly and additively with the features. When the truth is different, it misses, as the next section shows.

When the relationship is not linear: the capping machine

The capping machine on the bottling line tightens the cap with a torque. The recipe sets a target torque (setpoint) that rises slightly with line speed. A cap is defective when the measured torque differs from the setpoint by more than 0.5 N·m, either low (loose cap) or high (cracked cap) (all values assumed). The probability of a defect is therefore not a monotone function of torque, and “too low” depends on the line speed. The labels carry about 2% hidden error from camera inspection. The data is synthetic, 3,000 caps.

Example 2 Model families on a two-sided defect

Compare them with five-fold cross-validation (each cap is independent, so rows can be split at random). The metric is PR-AUC. The last row of the table is a special case: logistic regression with the added feature , since the PLC already knows the setpoint. The SVM PR-AUC table by and follows.

from sklearn.model_selection import StratifiedKFold
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier

def make_capper(seed=482, n=3000):
    rng = np.random.default_rng(seed)
    speed = rng.uniform(200, 400, n)                                        # line speed (bottles per minute)
    setpoint = 1.7 + 0.004 * (speed - 300)                                  # torque the recipe sets for this speed (N m)
    torque = setpoint + rng.normal(0, 0.28, n)                              # measured torque
    amps = 2.0 + 0.004 * speed + rng.normal(0, 0.15, n)
    temp = rng.normal(32, 3, n)
    bad = (np.abs(torque - setpoint) > 0.5) ^ (rng.random(n) < 0.02)        # loose or cracked cap, plus 2 % wrong labels
    return pd.DataFrame(dict(torque=torque, speed=speed, amps=amps, temp=temp, setpoint=setpoint, defect=bad.astype(int)))

cap = make_capper()
Xc, yc = cap[["torque", "speed", "amps", "temp"]], cap.defect
print(f"capping events: {len(cap)}, defect rate {yc.mean():.3f}")
cvc = StratifiedKFold(5, shuffle=True, random_state=0)
def ap5(model, X=Xc):
    s = cross_val_score(model, X, yc, cv=cvc, scoring="average_precision")
    return f"{s.mean():.3f} (sd {s.std(ddof=1):.3f})"
Xe = Xc.assign(err=(cap.torque - cap.setpoint).abs())                       # domain-knowledge feature: how far from the recipe value
tests = [("logistic", make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), Xc),
         ("SVM RBF, no scaling", SVC(), Xc),
         ("SVM RBF, scaled", make_pipeline(StandardScaler(), SVC()), Xc),
         ("decision tree, depth 3", DecisionTreeClassifier(max_depth=3, random_state=0), Xc),
         ("random forest", RandomForestClassifier(300, min_samples_leaf=3, random_state=0, n_jobs=-1), Xc),
         ("gradient boosting", GradientBoostingClassifier(random_state=0), Xc),
         ("logistic + |torque - setpoint|", make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), Xe)]
for name, model, X in tests:
    print(f"{name:<31} PR-AUC {ap5(model, X)}")
print("SVM RBF scaled, PR-AUC by C and gamma")
print("        gamma=0.01  0.1    1      10")
for C in (0.1, 1, 10, 100):
    row = [cross_val_score(make_pipeline(StandardScaler(), SVC(C=C, gamma=g)), Xc, yc, cv=cvc, scoring="average_precision").mean() for g in (0.01, 0.1, 1, 10)]
    print(f"C={C:<6}" + "".join(f"{v:>9.3f}" for v in row))
capping events: 3000, defect rate 0.088
logistic                        PR-AUC 0.177 (sd 0.067)
SVM RBF, no scaling             PR-AUC 0.116 (sd 0.014)
SVM RBF, scaled                 PR-AUC 0.761 (sd 0.052)
decision tree, depth 3          PR-AUC 0.327 (sd 0.013)
random forest                   PR-AUC 0.746 (sd 0.039)
gradient boosting               PR-AUC 0.706 (sd 0.043)
logistic + |torque - setpoint|  PR-AUC 0.801 (sd 0.051)
SVM RBF scaled, PR-AUC by C and gamma
        gamma=0.01  0.1    1      10
C=0.1       0.766    0.775    0.723    0.485
C=1         0.775    0.781    0.733    0.486
C=10        0.774    0.773    0.754    0.387
C=100       0.792    0.759    0.693    0.381

Logistic regression scores a PR-AUC of only 0.177, close to the prevalence (0.088), because a straight boundary can separate only “high torque” or “low torque” on one side; it cannot separate both ends, nor shift with speed. An SVM looks for the boundary with the widest margin from the nearest points of the two classes (Cortes and Vapnik, 1995). The RBF kernel lets the boundary curve. sets how much margin violation is tolerated (high tries to get every training point right) and sets the radius of influence of each point (high is narrow and memorises individual points). An SVM uses distances between points, so it is sensitive to scale. Line speed runs from 200 to 400 while torque and motor current span only a few units. Without standardisation, distances are dominated by line speed and the PR-AUC falls to 0.116, worse than logistic regression. After standardisation it is 0.761. The and table shows that a small (0.01 to 0.1) gives 0.76 to 0.79 for almost every . The maximum in the table, 0.792 at and , differs from the other values in that band by less than the fold standard deviation (about 0.05), so it should not be chosen for a 0.01 difference. Results collapse at (0.381 to 0.486) because each point has such a narrow influence that the boundary memorises the training data.

A depth-3 tree scores 0.327, still too coarse for the diagonal band that depends on speed. A random forest (0.746) and gradient boosting (0.706) capture the pattern without being told (next sections). The result most worth remembering is the last row, though. Logistic regression with the feature scores 0.801, the highest, because that feature states the question directly: “how far is it from the recipe?” The line’s PLC already knows the setpoint. Domain knowledge turned into a feature beat the more complex models. This agrees with the benchmark by Grinsztajn et al. (2022), which found that tree-based models remain strong on medium-sized tabular data (around ten thousand rows) because they tolerate uninformative features (here amps and temp) and capture irregular functions. But when a feature already holds the answer, a simple model is enough.

Horizontal bar chart of PR-AUC for seven models on defective caps: logistic regression 0.177, SVM without scaling 0.116, SVM scaled 0.761, depth-3 tree 0.327, random forest 0.746, gradient boosting 0.706, logistic with distance-from-setpoint feature 0.801
Figure 3 PR-AUC of several model families on the two-sided cap defect

Decision trees

A decision tree splits the data again and again with a condition on one feature (for example torque some value), choosing the condition that makes the resulting groups as “pure” as possible. The Gini impurity of a group is , where is the share of class in the node. A group with a single class has . To choose a split, try every feature and every cut point and keep the one with the lowest sum of over the two child nodes, weighted by their sample counts.

Example 3 Gini by hand on 12 caps, and when a tree gets too deep

Take 12 caps at a line speed near 300 bottles per minute (chosen to include four defective caps). The speed is almost constant, so torque alone is enough to decide. The example prints the Gini of the root node, the best single cut and the depth-2 tree. It then compares the PR-AUC of the training set and of a 30% hold-out as the tree depth grows.

from sklearn.tree import export_text
near = cap[cap.speed.between(290, 310)]                                     # speed almost constant, so torque alone is enough
small = pd.concat([near[near.defect == 1].sample(4, random_state=1), near[near.defect == 0].sample(8, random_state=1)]).sort_values("torque")
t, d = small.torque.round(2).to_numpy(), small.defect.to_numpy()
print("torque:", " ".join(f"{v:.2f}" for v in t))
print("defect:", " ".join(f"{v:>4d}" for v in d))
gini = lambda lab: 1 - sum((np.mean(lab == k)) ** 2 for k in (0, 1)) if len(lab) else 0.0
print(f"root Gini {gini(d):.3f}")
best = min(((len(d[t <= c]) * gini(d[t <= c]) + len(d[t > c]) * gini(d[t > c])) / len(d), c) for c in (t[:-1] + t[1:]) / 2)
print(f"best single split: torque <= {best[1]:.3f}, weighted Gini {best[0]:.3f}")
tree2 = DecisionTreeClassifier(max_depth=2, random_state=0).fit(small[["torque"]], small.defect)
print(export_text(tree2, feature_names=["torque"], decimals=3))
torque: 1.17 1.21 1.54 1.58 1.62 1.68 1.74 1.83 2.16 2.34 2.46 2.76
defect:    1    0    0    0    0    0    0    0    0    1    1    1
root Gini 0.444
best single split: torque <= 2.250, weighted Gini 0.148
|--- torque <= 2.250
|   |--- torque <= 1.190
|   |   |--- class: 1
|   |--- torque >  1.190
|   |   |--- class: 0
|--- torque >  2.250
|   |--- class: 1

The root has 4 defective caps out of 12, so . The best single cut is torque (midway between 2.16 and 2.34). The left side has 9 caps with 1 defective, ; the right side has 3 caps, all defective, . The weighted total is , far below 0.444. The depth-2 tree splits the left side again at 1.190 and obtains the rule “torque or is a defective cap”, which is exactly the two-sided acceptance window. The caution is that there are only 12 caps, so the cut points move easily.

from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
Xa, Xb, ya, yb = train_test_split(Xc, yc, test_size=0.3, stratify=yc, random_state=0)
print("depth  train PR-AUC  held-out PR-AUC")
for depth in (1, 2, 3, 4, 6, 8, 12, None):
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(Xa, ya)
    a = average_precision_score(ya, tree.predict_proba(Xa)[:, 1]); b = average_precision_score(yb, tree.predict_proba(Xb)[:, 1])
    print(f"{str(depth):>5}  {a:>12.3f}  {b:>15.3f}")
depth  train PR-AUC  held-out PR-AUC
    1         0.178            0.145
    2         0.326            0.200
    3         0.395            0.230
    4         0.512            0.241
    6         0.694            0.399
    8         0.836            0.479
   12         0.954            0.454
 None         1.000            0.413

In the depth table, the training score climbs to 1.000 when depth is unlimited, meaning the tree memorises every training row, while the hold-out score peaks at depth 8 (0.479) and then falls to 0.454 and 0.413. That is overfitting. Depth must be chosen on a validation set, not the training set. A single tree is also unstable: a small change in the data gives a different tree, which leads to the idea of a forest.

Line chart of two curves against tree depth 1, 2, 3, 4, 6, 8, 12 and unlimited. The pink line is the training PR-AUC, rising from 0.178 to 1.000. The green line is the hold-out, rising to 0.479 at depth 8 and then falling to 0.454 and 0.413
Figure 4 Training and hold-out PR-AUC by tree depth

Random forests and gradient boosting

A random forest trains hundreds of trees on bootstrap resamples, lets each node choose from a random subset of features so that the trees differ, and averages their output (Breiman, 2001). Averaging reduces the variance of deep trees while keeping their flexibility. Example 4 measures this by retraining with six different seeds: a single deep tree scores a mean of 0.309 with a standard deviation of 0.036, while the forest scores 0.694 and 0.005. The samples left out of each tree’s bootstrap (about one third) can be used as a free validation set, called the out-of-bag score, but they are drawn at random by row, so the problem from module 6 appears when the data has groups. Example 5 shows the numbers.

Gradient boosting builds shallow trees one after another; each new tree learns the error that is left by the previous ensemble (Friedman, 2001): , where is the added tree and is the learning rate (shrinkage), which scales down the effect of each tree. A small needs more trees but usually generalises more stably. A forest reduces the variance of deep trees; boosting reduces the bias of shallow trees. The main settings to tune are the tree depth, and the number of trees.

Example 4 The variance of a forest, and the learning rate of boosting

Use the defective-cap data and the same hold-out as Example 3.

single, forest = [], []
for seed in range(6):                                                      # retrain with different seeds to see the variance of the result
    single.append(average_precision_score(yb, DecisionTreeClassifier(max_features=2, random_state=seed).fit(Xa, ya).predict_proba(Xb)[:, 1]))
    forest.append(average_precision_score(yb, RandomForestClassifier(200, min_samples_leaf=3, random_state=seed, n_jobs=-1).fit(Xa, ya).predict_proba(Xb)[:, 1]))
print(f"one deep tree  : mean {np.mean(single):.3f}, sd across seeds {np.std(single, ddof=1):.3f}")
print(f"random forest  : mean {np.mean(forest):.3f}, sd across seeds {np.std(forest, ddof=1):.3f}")
print("boosting, held-out PR-AUC after n trees (depth-3 trees)")
print("learning rate     10     50    100    200    300")
for lr in (1.0, 0.3, 0.1, 0.03):
    gb = GradientBoostingClassifier(n_estimators=300, learning_rate=lr, max_depth=3, random_state=0).fit(Xa, ya)
    stages = {k: average_precision_score(yb, p[:, 1]) for k, p in enumerate(gb.staged_predict_proba(Xb), 1)}
    print(f"{lr:>13}" + "".join(f"{stages[k]:>7.3f}" for k in (10, 50, 100, 200, 300)))
one deep tree  : mean 0.309, sd across seeds 0.036
random forest  : mean 0.694, sd across seeds 0.005
boosting, held-out PR-AUC after n trees (depth-3 trees)
learning rate     10     50    100    200    300
          1.0  0.495  0.492  0.540  0.557  0.576
          0.3  0.599  0.583  0.558  0.618  0.647
          0.1  0.398  0.644  0.672  0.685  0.704
         0.03  0.297  0.438  0.575  0.639  0.659

The forest cuts the standard deviation across seeds from 0.036 to 0.005 and lifts the mean from 0.309 to 0.694. In the boosting table, wobbles and grows slowly (0.495 to 0.576) because each tree corrects too aggressively. rises faster but stumbles (0.599 at 10 trees, down to 0.558 at 100). rises steadily to 0.704 at 300 trees, and is still climbing at 0.659 after 300 trees, meaning it needs more trees. The working rule is to use a small learning rate and choose the number of trees with a validation set or early stopping, not from the training score.

Line chart of four lines of hold-out PR-AUC against the number of trees 10, 50, 100, 200 and 300. Learning rate 1.0 stays around 0.5 to 0.58, rate 0.3 wobbles between 0.56 and 0.65, rate 0.1 rises steadily to 0.704, rate 0.03 rises slowly to 0.659
Figure 5 PR-AUC of gradient boosting by number of trees and learning rate

Choosing a model that matches the deployment question

Back to the fleet. The model selection step must use validation that matches the deployment question, as in module 6. Example 5 reports two columns. The first is walk-forward: train on the past up to a cut day (days 100, 150 and 200) and validate on the next 50 days. It answers “same airframes, future flights”. The second splits by airframe and answers “new airframes”. Both use only the training period (before day 250). Once a model is chosen, it is refitted on the whole training period and the test set is touched once, compared with the technicians’ rule at an alert budget of 10% of the flights.

Example 5 Choose the fleet model and report the test result once

from sklearn.base import clone
models = {"always healthy": DummyClassifier(strategy="prior"),
          "logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
          "SVM RBF": make_pipeline(StandardScaler(), SVC(C=1, gamma=0.01)),
          "decision tree, depth 3": DecisionTreeClassifier(max_depth=3, random_state=0),
          "random forest": RandomForestClassifier(300, min_samples_leaf=5, random_state=0, n_jobs=-1),
          "gradient boosting": GradientBoostingClassifier(n_estimators=150, learning_rate=0.05, max_depth=3, random_state=0)}
def score_of(model, X):
    return model.decision_function(X) if hasattr(model, "decision_function") and not hasattr(model, "predict_proba") else model.predict_proba(X)[:, 1]
def walk_forward(model, cuts=(100, 150, 200), width=50):                    # train on the past up to the cut day, validate on the next 50 days
    out = []
    for c in cuts:
        a, b = (dtr < c).values, ((dtr >= c) & (dtr < c + width)).values
        fitted = clone(model).fit(Xtr[a], ytr[a])
        out.append(average_precision_score(ytr[b], score_of(fitted, Xtr[b])))
    return np.array(out)
print("model                   walk-forward (same airframes)   by airframe (new airframes)")
chosen = {}
for name, model in models.items():
    wf = walk_forward(model)
    ga = cross_val_score(model, Xtr, ytr, cv=cv, groups=gtr, scoring="average_precision")
    chosen[name] = wf.mean()
    print(f"{name:<23} {wf.mean():>10.3f} (sd {wf.std(ddof=1):.3f})          {ga.mean():>10.3f} (sd {ga.std(ddof=1):.3f})")
best_name = max((n for n in chosen if n != "always healthy"), key=chosen.get)
final = clone(models[best_name]).fit(Xtr, ytr)                              # refit on the whole training period, then touch the test set once
s_te = score_of(final, Xte)
k = int(round(0.10 * len(yte))); top = np.argsort(-s_te)[:k]                # alert budget: 10 % of flights
tp = int(yte.to_numpy()[top].sum())
rule = (data.loc[~train, "vib_r5"] > 16).to_numpy()
print(f"selected: {best_name}; test PR-AUC {average_precision_score(yte, s_te):.3f}")
print(f"model, top 10% of flights : {k} alerts, precision {tp / k:.2f}, recall {tp / yte.sum():.2f}")
print(f"technician rule           : {int(rule.sum())} alerts, precision {(rule & (yte.to_numpy() == 1)).sum() / rule.sum():.2f}, recall {(rule & (yte.to_numpy() == 1)).sum() / yte.sum():.2f}")
oob = RandomForestClassifier(300, min_samples_leaf=5, oob_score=True, random_state=0, n_jobs=-1).fit(Xtr, ytr)    # OOB draws rows at random, so flights of one airframe are mixed
print(f"random forest out-of-bag PR-AUC {average_precision_score(ytr, oob.oob_decision_function_[:, 1]):.3f} (rows drawn at random, airframes mixed)")
model                   walk-forward (same airframes)   by airframe (new airframes)
always healthy               0.102 (sd 0.022)               0.103 (sd 0.013)
logistic                     0.534 (sd 0.109)               0.617 (sd 0.082)
SVM RBF                      0.508 (sd 0.117)               0.599 (sd 0.118)
decision tree, depth 3       0.341 (sd 0.078)               0.457 (sd 0.124)
random forest                0.550 (sd 0.127)               0.597 (sd 0.140)
gradient boosting            0.554 (sd 0.104)               0.593 (sd 0.107)
selected: gradient boosting; test PR-AUC 0.760
model, top 10% of flights : 190 alerts, precision 0.71, recall 0.63
technician rule           : 325 alerts, precision 0.42, recall 0.63
random forest out-of-bag PR-AUC 0.831 (rows drawn at random, airframes mixed)

Every trainable model clearly beats guessing the large class (0.102), and the single depth-3 tree is weakest (0.341). But the remaining options, logistic regression, SVM, random forest and gradient boosting, differ by no more than 0.05, while the standard deviation across validation windows is as high as 0.10 to 0.13 (each window has only 76 to 118 positive flights). A difference that small is within the noise and should not be over-interpreted. The airframe column gives the same picture: logistic regression, 0.617, is not beaten (random forest 0.597 and boosting 0.593), in line with the general conclusion that when the signal is monotone and has no complicated interactions, a well-standardised linear model can compete. The team used the rule “choose the highest mean in the validation that matches the real use of the company (same airframes, future)”, which gives gradient boosting (0.554) with a slim lead.

After refitting on the whole training period and testing once, gradient boosting scores a PR-AUC of 0.760 against a test-period prevalence of 0.113. At an alert budget of 10% of the flights (190 alerts) it reaches precision 0.71 and recall 0.63. The technicians’ rule raises 325 alerts to reach the same recall of 0.63, with precision of only 0.42. Put differently, the model matches the old rule’s recall with 135 fewer alerts. This is the result of one test window (flights from day 250 to the end of the log, 214 positive flights), so it still needs to be reported with its uncertainty in module 10, and for a new drone the result should be expected to drop towards the airframe column (about 0.6). The last line gives one more reason to choose the validation yourself: the out-of-bag score of the random forest is 0.831, far above the 0.597 of the airframe split and also above the 0.760 on the real test, because OOB draws rows at random, so flights of the same airframe sit on both the training and the validation side.

Module lab

Lab: choose and evaluate a classifier to fit the task

  1. Run Example 1 on the fleet data with your group’s seed. Change the threshold to 0.3, 0.5 and 0.7, tabulate precision and recall, and compare with the technicians’ rule from module 6.
  2. Use Example 1 (continued) to project the model’s precision for a fleet whose prevalence is expected to be 3% (assumed), and write how many false alarms technicians will see for each correct alert.
  3. Run Example 2 with the acceptance window changed (0.5 to 0.3 and 0.8 N·m). Record how each model’s PR-AUC changes, and try removing the feature err.
  4. Pick a new set of 12 caps (a different random_state), then compute the Gini of the root node and the best cut by hand. Compare with DecisionTreeClassifier.
  5. Tabulate learning rates 0.3, 0.1 and 0.03 against 50 to 500 trees of gradient boosting on the cap data. Choose the values from the hold-out and state where overfitting starts.
  6. Run Example 5 with the test cut at 200 and 300. State whether the selected model changes, with a reason based on the standard deviation.
  7. Write a one-page report for your own application, giving the chosen model family, the main metric, the expected prevalence, the alert budget and the baseline.

Common mistakes

Watch out

  • Reporting only accuracy or ROC-AUC when positives are rare. Predicting the large class every time already gives 90% accuracy, and ROC-AUC does not tell technicians how many false alarms to expect.
  • Using the default threshold 0.5 without thinking. Re-weighting or moving the threshold changes the point on the same curve; it does not change the quality of the model.
  • Trusting precision from data with a different prevalence than the real work.
  • Using an SVM or other distance-based model without standardising. The large-scale feature dominates.
  • Letting and grow too large. The boundary memorises the training data.
  • Choosing the tree depth or the number of boosting trees from the training score.
  • Using out-of-bag scores or random row splits on data with groups. The numbers are inflated.
  • Choosing a more complex model because the scores differ by 0.02, when that is smaller than the fold standard deviation.
  • Forgetting to ask whether domain knowledge can be turned into a feature that answers the question directly.

Summary

  • Choose metrics that suit rare positives: read precision, recall, MCC and PR-AUC together, not accuracy alone.
  • ROC-AUC does not change with prevalence, but precision and PR-AUC do. Always state the prevalence with the result.
  • Logistic regression is a strong, explainable baseline but assumes the log-odds are linear.
  • An SVM needs standardisation and tuned and . A decision tree learns cut points by Gini, but a single tree is unstable and overfits easily.
  • A random forest reduces variance by averaging; gradient boosting adds shallow trees one at a time with a small learning rate.
  • A feature built from domain knowledge may beat a more complex model.
  • Select models with validation that matches the deployment question, then touch the test set once. Differences smaller than the standard deviation should not be interpreted.

Self-check questions

  1. A confusion matrix has TP = 40, FP = 60, FN = 10, TN = 890. Compute accuracy, precision, recall and F1.
  2. What ROC-AUC and PR-AUC does a predictor with no knowledge get on data with a prevalence of 6%?
  3. The logistic regression of Example 1 has an odds ratio of 5.72 per SD for vib_r5. If vib_r5 rises by 2 SD (other features unchanged), by what factor do the odds change?
  4. A depth-12 tree has a training PR-AUC of 0.954 and a hold-out of 0.454, while depth 8 has 0.836 and 0.479. Which depth should be chosen, and why?
  5. Why is the out-of-bag score of the random forest on the fleet data (0.831) higher than the score when splitting by airframe (0.597)?
Answers
  1. accuracy , precision , recall , F1 .
  2. ROC-AUC is 0.5 and PR-AUC equals the prevalence, 0.06.
  3. The odds are multiplied by (the effects of the two SDs multiply).
  4. Depth 8, because its hold-out score is higher (0.479 against 0.454). The gap between training and hold-out is wider at depth 12 (0.50 against 0.36), showing overfitting, and the training score cannot be used to choose.
  5. OOB draws rows at random, so flights of the same airframe are in both a tree’s training sample and its validation sample. The tree memorises each airframe’s baseline and the result is inflated. Splitting by airframe has no such leak.

Key formulas

Precision and recall
F1 and MCC
Gini impurity of a tree node
Adding a tree in boosting

Key references

  1. Géron, A. (2022). Hands-on machine learning with Scikit-Learn, Keras, and TensorFlow (3rd ed.). O'Reilly.
  2. scikit-learn developers. Metrics and scoring: Quantifying the quality of predictions (scikit-learn 1.9). link
  3. Cortes, C., & Vapnik, V. (1995). Support-vector networks. Machine Learning, 20(3), 273–297. link
  4. Breiman, L. (2001). Random forests. Machine Learning, 45(1), 5–32. link
  5. Friedman, J. H. (2001). Greedy function approximation: A gradient boosting machine. The Annals of Statistics, 29(5), 1189–1232. link
  6. Saito, T., & Rehmsmeier, M. (2015). The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets. PLOS ONE, 10(3), e0118432. link
  7. Chicco, D., & Jurman, G. (2020). The advantages of the Matthews correlation coefficient (MCC) over F1 score and accuracy in binary classification evaluation. BMC Genomics, 21, Article 6. link
  8. Grinsztajn, L., Oyallon, E., & Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? In Advances in Neural Information Processing Systems 35 (Datasets and Benchmarks Track) (arXiv:2207.08815). link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Artificial intelligence and computer vision · Automation, robotics and swarms · Mathematics, physics and statistics