Module 10/15 · Weeks 10 · 9 h

Model tuning, trustworthy reporting, monitoring and handover

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. Choose between grid and random hyper-parameter search, and use nested cross-validation to check whether tuning really helps or only reflects selection bias
  2. Report a test result with an uncertainty interval from a bootstrap that resamples whole airframes, and compare it with the baseline in the cost of the task
  3. Check and correct the calibration of probabilities, then choose the threshold from the cost of each kind of error
  4. Detect data drift from the inputs and the alert rate when labels arrive late, and set the conditions for retraining
  5. Explain a model with permutation importance correctly, and hand it over with input checks, a model card, and cautions on personal data and the use of results

Prerequisites: Modules 6 to 9 of this course

Why this matters

The first four modules produced models that were trained and validated the right way, but the analytics centre cannot hand them over yet. The clients still have several questions. The survey company asks: “Is the tuned model really better, or did you just pick the settings that happened to score high?” and “How sure are we, with only 22 motor failures in the test period?” The bottling plant asks: “Where should the cap-rejection threshold sit so that we lose the least money?” Once the models are live, both ask: “If operating conditions change, how will we know the model has stopped being accurate?” and “Why did the model warn about this airframe?” This module answers these in order: tuning a model and checking that it really helped, calibrating probabilities and choosing the threshold from cost, reporting results with uncertainty, monitoring drift, explaining the model, and handing over with ethical use of data. It covers stages 7 and 8 of the workflow in module 6. All data is synthetic, generated by the same functions as before, and all numbers are assumed, including the costs in baht, which are invented to teach the principle and are not the real prices of any organisation.

The examples build on each other. They use the same fleet table and the make_fleet function, with a new build_data function that collects the labelling and feature steps of module 6 in one place. The split into a training period (before day 250) and a test period (after) is the same as in module 7, with one added observation. The positive label of a flight before day 250 has to wait for a failure within the next 21 days, and some of those failures happen after the cut. The last line of the block says that 32 of the 465 positive labels were not yet known to the team on day 250. We keep the split so that the numbers stay continuous with module 7 (the effect on the test score is small), but in a live system the labels of recent flights can only be used after waiting 21 days. This returns in the drift section.

import numpy as np, pandas as pd

def make_fleet(seed=482, n_drones=40, days=365, drift_day=None):          # same as modules 6 and 7
    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)

def build_data(H=21, **kw):                                                 # labels and features exactly as in module 6
    flights, fails = make_fleet(**kw)
    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 + H <= 364)].copy()          # drop the end-of-log rows whose label cannot be decided yet
    data["fault"] = (data.days_left <= H).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())
    return data, fails

FEATURES = ["vib", "temp", "amps", "hours", "ambient", "payload", "vib_r5", "temp_r5", "amps_r5"]
data, fails = build_data()
train = data.day < 250                                                      # train on the past and keep the test period to be touched once
Xtr, ytr, gtr = data.loc[train, FEATURES], data.fault[train], data.drone[train]
Xte, yte = data.loc[~train, FEATURES], data.fault[~train]
print(f"training period: {len(Xtr)} flights, {ytr.sum()} positive ({ytr.mean():.3f}), {gtr.nunique()} airframes; test period: {len(Xte)} flights, {yte.sum()} positive ({yte.mean():.3f})")
print(f"motor failures: {int((fails.day < 250).sum())} in the training period, {int((fails.day >= 250).sum())} in the test period")
mature = data[train & (data.fault == 1)]                                    # positive labels of flights before the cut that wait on a failure after the cut
print(f"positive training flights whose failure date is after day 250: {int((mature.fail_day >= 250).sum())} of {len(mature)}")
training period: 4508 flights, 465 positive (0.103), 40 airframes; test period: 1896 flights, 214 positive (0.113)
motor failures: 39 in the training period, 22 in the test period
positive training flights whose failure date is after day 250: 32 of 465

Tuning hyper-parameters

The parameters of a model are the values learned from data, such as the weights of a logistic regression. The hyper-parameters are the values the developer sets before training, such as tree depth, learning rate and the number of boosting trees. Tuning means trying several sets of values, scoring each with a cross-validation that matches the real question (here, split by airframe), and keeping the set with the best score (scikit-learn developers, page Tuning the hyper-parameters). There are two basic methods. Grid search tries every combination of the listed values, while random search draws sets of values from given ranges for as many trials as the budget allows. Bergstra and Bengio (2012) showed that with the same budget random search usually finds models at least as good as the grid, because most hyper-parameters matter little: the grid wastes trials repeating values of the unimportant ones, while random search gives a different value of the important ones every time.

A deeper problem is selection bias. The best score among many trials is the maximum of noisy numbers, so it is inflated by construction. Cawley and Talbot (2010) showed that this bias can be as large as the differences between learning algorithms. The check is nested cross-validation. The outer loop splits the data into a training part and a held-out part. The inner loop uses only the training part of the outer loop to search the hyper-parameters, and the resulting model is then scored on the held-out part, which the search has never seen (the scikit-learn example is called Nested versus non-nested cross-validation). Every step that chooses something from the data must sit in the inner loop, just as in the principle of module 6.

Example 1 Grid against random, and does tuning really help?

We use scikit-learn’s HistGradientBoostingClassifier, a gradient boosting that is much faster than the earlier one, on the training period of the fleet table. The first part compares a 3 × 3 × 3 = 27-point grid (learning rate, number of trees, depth) with 27 random draws from five hyper-parameters, repeated with five seeds, all using the same 5-fold split by airframe and PR-AUC as the metric. The second part is nested cross-validation repeated twice (5 outer folds twice, 10 folds in all). The inner loop is a random search of 24 draws using a 5-fold split by airframe, compared with the default model on the same outer folds.

from scipy.stats import loguniform, randint
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, StratifiedGroupKFold, cross_val_score

def hgb(**kw): return HistGradientBoostingClassifier(random_state=0, early_stopping=False, **kw)
cv = StratifiedGroupKFold(5, shuffle=True, random_state=0)                  # split by airframe, with the same split every time
dflt = cross_val_score(hgb(), Xtr, ytr, cv=cv, groups=gtr, scoring="average_precision")
print(f"default settings: CV PR-AUC {dflt.mean():.3f} (sd over folds {dflt.std(ddof=1):.3f})")
space = {"learning_rate": loguniform(0.01, 0.3), "max_iter": randint(50, 400), "max_depth": randint(2, 7),
         "min_samples_leaf": randint(10, 120), "l2_regularization": loguniform(1e-3, 10)}
grid = GridSearchCV(hgb(), {"learning_rate": [0.03, 0.1, 0.3], "max_iter": [100, 200, 400], "max_depth": [3, 5, None]},
                    cv=cv, scoring="average_precision", n_jobs=-1).fit(Xtr, ytr, groups=gtr)
print("method               trials  distinct learning rates  best CV PR-AUC")
print(f"grid 3 x 3 x 3       {len(grid.cv_results_['params']):>6}  {3:>23}  {grid.best_score_:>14.3f}")
for seed in range(5):                                                       # random search with the same budget, five seeds
    rs = RandomizedSearchCV(hgb(), space, n_iter=27, cv=cv, scoring="average_precision", random_state=seed, n_jobs=-1).fit(Xtr, ytr, groups=gtr)
    distinct = len({round(p["learning_rate"], 6) for p in rs.cv_results_["params"]})
    print(f"random, seed {seed}       {27:>6}  {distinct:>23}  {rs.best_score_:>14.3f}")
scores = pd.Series(grid.cv_results_["mean_test_score"])
for p in ("learning_rate", "max_iter", "max_depth"):                        # mean grid score by the value of each hyper-parameter
    keys = [str(q[p]) for q in grid.cv_results_["params"]]
    print(f"grid mean CV PR-AUC by {p}: " + ", ".join(f"{k} {v:.3f}" for k, v in scores.groupby(keys).mean().items()))
default settings: CV PR-AUC 0.561 (sd over folds 0.110)
method               trials  distinct learning rates  best CV PR-AUC
grid 3 x 3 x 3           27                        3           0.631
random, seed 0           27                       27           0.610
random, seed 1           27                       27           0.621
random, seed 2           27                       27           0.632
random, seed 3           27                       27           0.599
random, seed 4           27                       27           0.592
grid mean CV PR-AUC by learning_rate: 0.03 0.586, 0.1 0.559, 0.3 0.541
grid mean CV PR-AUC by max_iter: 100 0.573, 200 0.563, 400 0.551
grid mean CV PR-AUC by max_depth: 3 0.581, 5 0.562, None 0.544
rows = []
for rep in range(2):                                                        # two repeats, each shuffling the airframes differently
    outer = StratifiedGroupKFold(5, shuffle=True, random_state=10 + rep)
    for a, b in outer.split(Xtr, ytr, gtr):
        search = RandomizedSearchCV(hgb(), space, n_iter=24, cv=StratifiedGroupKFold(5, shuffle=True, random_state=0), scoring="average_precision",
                                    random_state=0, n_jobs=-1).fit(Xtr.iloc[a], ytr.iloc[a], groups=gtr.iloc[a])       # inner loop: choose the settings without seeing the outer airframes
        score = lambda m: average_precision_score(ytr.iloc[b], m.predict_proba(Xtr.iloc[b])[:, 1])                  # outer loop: airframes never used for the choice
        rows.append((search.best_score_, score(search), score(hgb().fit(Xtr.iloc[a], ytr.iloc[a]))))
r = np.array(rows)
print(f"{len(r)} outer folds (2 repeats x 5 folds of airframes)")
print(f"best score reported by the search (inner CV): {r[:, 0].mean():.3f}")
print(f"tuned model on unseen airframes (outer)    : {r[:, 1].mean():.3f}  (sd over folds {r[:, 1].std(ddof=1):.3f})")
print(f"default model on the same outer folds      : {r[:, 2].mean():.3f}  (sd over folds {r[:, 2].std(ddof=1):.3f})")
print(f"optimism of the search score: {(r[:, 0] - r[:, 1]).mean():+.3f}; tuned minus default: {(r[:, 1] - r[:, 2]).mean():+.3f} (sd of the difference {(r[:, 1] - r[:, 2]).std(ddof=1):.3f})")
final_search = RandomizedSearchCV(hgb(), space, n_iter=30, cv=cv, scoring="average_precision", random_state=0, n_jobs=-1).fit(Xtr, ytr, groups=gtr)
final_params = final_search.best_params_                                    # the settings used in the rest of this module, searched on the whole training period
print("chosen settings:", ", ".join(f"{k} {v:.3g}" for k, v in final_params.items()), f"(search score {final_search.best_score_:.3f})")
10 outer folds (2 repeats x 5 folds of airframes)
best score reported by the search (inner CV): 0.578
tuned model on unseen airframes (outer)    : 0.524  (sd over folds 0.133)
default model on the same outer folds      : 0.531  (sd over folds 0.104)
optimism of the search score: +0.054; tuned minus default: -0.007 (sd of the difference 0.109)
chosen settings: l2_regularization 0.0454, learning_rate 0.0124, max_depth 4, max_iter 277, min_samples_leaf 30 (search score 0.610)

In the first part, the default model scores a PR-AUC of 0.561 (standard deviation between folds 0.110). Every search seems to improve on it: the grid reaches 0.631 and the five random seeds 0.592 to 0.632. No method wins consistently, and the differences are smaller than the variation between random seeds (a range of 0.04). The one clear difference is the number of learning rates tried: the grid tried only 3, the random search all 27. The table of grid averages shows that the most important hyper-parameter is the learning rate (0.586 at 0.03 against 0.541 at 0.3) and that learning more slowly, with shallow trees and fewer of them, always helps. That makes sense for data with few positives and much noise: making the model “cautious” works. The question is whether the rise from 0.561 to about 0.61 to 0.63 is real.

The second part answers it. The score the search reports averages 0.578, but when the models it produces are scored on airframes the search never saw, only 0.524 is left. The selection bias is 0.054. More importantly, the default model on the same folds scores 0.531, so the mean difference between the tuned and default models is −0.007 (standard deviation of the difference 0.109 over 10 folds). There is no evidence that tuning helps unseen airframes. The “improvement” of about 0.05 to 0.07 in the first part is about the size of the selection bias of 0.054. That is no reason to stop tuning, but it is a reason to (1) check with nested cross-validation before claiming that tuning helped, (2) report the outer score as the figure to expect on new airframes rather than the score the search prints, and (3) spend the time on labels, features and splitting first, because these change results far more than tuned settings do. The team keeps the settings searched on the whole training period (the variable final_params) for the rest of the module because they are cautious, with a low learning rate and shallow trees, and according to the outer results they are no worse than the defaults.

Horizontal bar chart with five bars of PR-AUC: default on the same CV 0.561 in grey, best of the search on the same CV 0.610 in pink, score reported by the inner search 0.578 in pink, tuned model on unseen airframes in the outer loop 0.524 in green, and default on unseen airframes 0.531 in green
Figure 1 The score the search reports against the score on unseen airframes

Calibrating probabilities and choosing the threshold from cost

A classifier gives a score between 0 and 1, which can be read as a probability only if it is calibrated: among cases where the model says 30%, about 30% should really happen (Niculescu-Mizil and Caruana, 2005). A model that ranks well (high PR-AUC) can still give probabilities on the wrong scale. There are three tools for checking. The Brier score (Brier, 1950) and the log-loss measure the overall quality of the probabilities. The reliability table splits the scores into bins and compares the value the model predicts with the rate that really occurs in each bin. The ECE (expected calibration error) averages the gap between the two, weighted by bin size; Guo et al. (2017) use ECE as the main metric in their work. Calibration learns a function that maps scores to probabilities. The sigmoid method uses a two-parameter S-shaped curve, and the isotonic method uses a more flexible monotone step function, so it risks overfitting when data is scarce. The scikit-learn guide says that isotonic will perform as well as or better than sigmoid when there are more than about 1,000 samples (scikit-learn developers, page Probability calibration). CalibratedClassifierCV cross-fits inside the training data and never uses the test data.

Calibrated probabilities make the threshold easy to choose. Let be the cost of a false alarm (saying faulty when the item is fine) and the cost of a miss. Raising the alarm has an expected cost of , and staying quiet has . Raising the alarm pays off when , that is, when

(Elkan, 2001). The threshold comes from the cost ratio; it is not the midpoint 0.5 and not the value that maximises F1. The formula works well when the probabilities are right, which is why calibration comes first.

Example 2 Calibrate a random forest and choose the cap-rejection threshold from cost

Back to the capper on the bottling line (the cap-defect data from module 7, with the same four features and without the feature that gives the answer away). Each cap is independent, so rows can be split at random: 1,800 caps to fit and 1,200 to evaluate. Assume that rejecting one good cap costs 3 baht (the cap and bottle that must be set aside) and that letting one defective cap reach a customer costs 60 baht (a return and the handling of the complaint). The table compares the raw random forest with versions calibrated by sigmoid and isotonic, using probability-quality metrics and the cost per 1,000 caps at the threshold 0.5 and at .

from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import brier_score_loss, log_loss
from sklearn.model_selection import StratifiedKFold, train_test_split

def make_capper(seed=482, n=3000):                                          # same as module 7
    rng = np.random.default_rng(seed)
    speed = rng.uniform(200, 400, n)
    setpoint = 1.7 + 0.004 * (speed - 300)
    torque = setpoint + rng.normal(0, 0.28, n)
    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)
    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
Xa, Xb, ya, yb = train_test_split(Xc, yc, test_size=0.4, stratify=yc, random_state=0)      # each cap is independent, so a random split by cap is fine
def forest(): return RandomForestClassifier(300, min_samples_leaf=3, random_state=0, n_jobs=-1)
inner = StratifiedKFold(5, shuffle=True, random_state=0)
models = {"raw forest": forest().fit(Xa, ya),
          "sigmoid": CalibratedClassifierCV(forest(), method="sigmoid", cv=inner).fit(Xa, ya),
          "isotonic": CalibratedClassifierCV(forest(), method="isotonic", cv=inner).fit(Xa, ya)}
C_GOOD, C_BAD = 3.0, 60.0                                                   # assumed costs (baht): rejecting one good cap and letting one defective cap reach a customer
p_star = C_GOOD / (C_GOOD + C_BAD)                                          # the threshold with the lowest expected cost when the probabilities are right
print(f"{len(Xa)} caps to fit, {len(Xb)} to evaluate (defect rate {yb.mean():.3f}); threshold p* = {C_GOOD:g}/({C_GOOD:g}+{C_BAD:g}) = {p_star:.4f}")
def cost_per_1000(p, t):
    flag = p >= t
    return (C_GOOD * (flag & (yb == 0)).sum() + C_BAD * (~flag & (yb == 1)).sum()) / len(yb) * 1000
def ece(p, bins=6):                                                         # calibration error, with bins cut at quantiles of the score
    idx = np.clip(np.searchsorted(np.quantile(p, np.linspace(0, 1, bins + 1)), p, side="right") - 1, 0, bins - 1)
    return sum((idx == k).mean() * abs(p[idx == k].mean() - yb.values[idx == k].mean()) for k in range(bins))
print("model        Brier  log-loss  ECE    cost/1000 at 0.5   at p*")
for name, m in models.items():
    p = m.predict_proba(Xb)[:, 1]
    print(f"{name:<12} {brier_score_loss(yb, p):.4f}  {log_loss(yb, p):.3f}   {ece(p):.3f}  {cost_per_1000(p, 0.5):>14.0f}  {cost_per_1000(p, p_star):>7.0f}")
print(f"reference: Brier of always predicting the defect rate {yb.mean() * (1 - yb.mean()):.4f}; accept everything {C_BAD * yb.mean() * 1000:.0f}; reject everything {C_GOOD * (1 - yb.mean()) * 1000:.0f} per 1000 caps")
for name in ("raw forest", "sigmoid"):                                      # reliability table with 6 bins
    obs, pred = calibration_curve(yb, models[name].predict_proba(Xb)[:, 1], n_bins=6, strategy="quantile")
    print(f"{name:<10} predicted: " + " ".join(f"{v:.3f}" for v in pred) + "\n           observed : " + " ".join(f"{v:.3f}" for v in obs))
1800 caps to fit, 1200 to evaluate (defect rate 0.088); threshold p* = 3/(3+60) = 0.0476
model        Brier  log-loss  ECE    cost/1000 at 0.5   at p*
raw forest   0.0419  0.199   0.024            2802     1718
sigmoid      0.0378  0.156   0.013            2458     1555
isotonic     0.0364  0.182   0.014            2105     1645
reference: Brier of always predicting the defect rate 0.0805; accept everything 5300; reject everything 2735 per 1000 caps
raw forest predicted: 0.004 0.012 0.021 0.039 0.077 0.355
           observed : 0.020 0.025 0.030 0.020 0.035 0.400
sigmoid    predicted: 0.022 0.023 0.025 0.030 0.042 0.357
           observed : 0.030 0.025 0.020 0.015 0.040 0.400

The reliability table of the raw forest shows the problem. In the lowest bin the forest predicts a probability of 0.004, but the caps in that bin are really defective at 0.020, because the labels contain a hidden 2% error from the camera inspection and no group of caps can have fewer than 2% defects. The forest is over-confident at the low end. The sigmoid predicts 0.022, which is closer to the truth. ECE falls from 0.024 to 0.013 and the Brier score from 0.0419 to 0.0378 (a predictor that always predicts the defect rate scores 0.0805). Isotonic gets a Brier score of 0.0364 but a higher log-loss than sigmoid (0.182 against 0.156), as the guide warns that it is more flexible and overfits more easily. The business result is much clearer. At the threshold 0.5 the raw forest costs 2,802 baht per 1,000 caps, more than rejecting every cap (2,735 baht), because at this threshold it lets 56 of 106 defective caps (53%) reach the customer and rejects only 1 good cap. Switching to brings the cost down to 1,718 baht (39% lower, by rejecting 347 good caps but missing only 17 defective ones), and calibrating with sigmoid brings it to 1,555 baht (a further 9%). Isotonic gives 1,645 baht. The difference between the two calibration methods is within the noise of an evaluation set of 1,200 caps (about 106 defective), so it should not be interpreted. The conclusions: the threshold must come from the costs, calibrated probabilities make the theory applicable, and assumed prices must be written in the report, because if the cost of a defective cap reaching a customer is changed to 150 baht the threshold becomes .

Reliability diagram. The horizontal axis is the mean predicted probability of each bin and the vertical axis is the defect rate that really occurred. The dashed diagonal is perfect calibration. Pink points for the raw forest lie below the diagonal in the low bins, for example predicted 0.004 and observed 0.020. Green points for the sigmoid lie closer to the diagonal
Figure 2 Reliability of the probabilities from the raw random forest and the sigmoid-calibrated one

Reporting the test result with uncertainty and the cost of the task

When the model and the threshold are chosen, the test set is touched once. The reported figures must answer three questions: what result was obtained, how sure are we, and how much better is it than what the client does today, in units the client understands.

First, uncertainty. The bootstrap (Efron, 1979) resamples the test set itself (with replacement) and recomputes the metric thousands of times; the 2.5th to 97.5th percentiles are the 95% uncertainty interval. The point to watch is the unit of resampling. Flights of the same airframe are not independent (the data is grouped; see the splitting section of module 6). Resampling single flights acts as if there were more independent data than there really is, and the interval comes out too narrow. Field and Welsh (2007) studied the bootstrap for clustered data, which resamples whole clusters; here that means resampling whole airframes (40 of them, with replacement). Second, the cost of the task. The whole alert policy must be simulated, rather than counting the flights that were predicted correctly, because one motor has several positive flights before it fails, one inspection is enough, and a warning one day before failure is too late for the technician to do anything.

The simulation rules (all values assumed): when a flight scores at or above the threshold, the technician inspects that airframe once (1,500 baht) and does not inspect the same airframe more often than every 7 days. If an inspection happens 3 to 21 days before the motor fails, the failure counts as caught and the motor is replaced as planned (6,000 baht). If not, the motor fails mid-job (40,000 baht, including the emergency replacement and the lost survey work). The total cost is . The threshold is chosen on the training period using out-of-fold scores obtained from the split by airframe. Four policies are compared: run to failure and replace, inspect on a fixed schedule every 30 days, the technicians’ rule (vib_r5 above 16), and the model.

Example 3 The one-shot test result for the fleet, as cost and an uncertainty interval

from sklearn.model_selection import cross_val_predict
oof = cross_val_predict(hgb(**final_params), Xtr, ytr, cv=cv, groups=gtr, method="predict_proba")[:, 1]    # scores of the training period, from airframes not used for fitting
final = hgb(**final_params).fit(Xtr, ytr)
pte = final.predict_proba(Xte)[:, 1]                                        # touch the test set once
print(f"test PR-AUC {average_precision_score(yte, pte):.3f} (prevalence {yte.mean():.3f}); out-of-fold PR-AUC on the training period {average_precision_score(ytr, oof):.3f}")

C_INSP, C_PLAN, C_FAIL = 1500, 6000, 40000                                  # assumed costs (baht): one inspection, a planned replacement and a motor failing mid-job
MIN_LEAD, WINDOW, COOLDOWN = 3, 21, 7                                       # the warning must come 3 to 21 days before the failure, and the same airframe is not inspected more often than every 7 days
def tally(flights, flag, failures):
    # per airframe: inspections, failures caught and failures missed
    out = {d: dict(insp=0, caught=0, missed=0) for d in range(40)}
    days = {d: [] for d in range(40)}
    for d, g in flights.assign(flag=flag).sort_values("day").groupby("drone"):
        last = -1e9
        for day, f in zip(g.day, g.flag):
            if f and day - last >= COOLDOWN: days[d].append(day); last = day
    for d in range(40): out[d]["insp"] = len(days[d])
    for r in failures.itertuples():
        hit = any(MIN_LEAD <= r.day - x <= WINDOW for x in days[r.drone])
        out[r.drone]["caught" if hit else "missed"] += 1
    return out
def money(out, drones=range(40)):
    n, c, m = (sum(out[d][k] for d in drones) for k in ("insp", "caught", "missed"))
    return n, c, m, C_INSP * n + C_PLAN * c + C_FAIL * m
dtr, dte = data[train].reset_index(drop=True), data[~train].reset_index(drop=True)
ftr, fte = fails[fails.day < 250], fails[fails.day >= 250]
print("choose the alert threshold on the training period (out-of-fold scores)")
print("tau  inspections  caught  missed  cost (thousand THB)")
costs = {}
for tau in (0.1, 0.2, 0.3, 0.4, 0.5, 0.6):
    n, c, m, cost = money(tally(dtr, oof >= tau, ftr)); costs[tau] = cost
    print(f"{tau:.1f}  {n:>11}  {c:>6}  {m:>6}  {cost / 1000:>19.1f}")
tau = min(costs, key=costs.get)
schedule = np.zeros(len(dte), bool)                                         # scheduled inspection every 30 days, at the first flight on or after days 270, 300 and 330
for d, g in dte.groupby("drone"):
    for day in (270, 300, 330):
        later = g.index[g.day >= day]
        if len(later): schedule[later[0]] = True
policies = {"run to failure": np.zeros(len(dte), bool), "every 30 days": schedule, "technician rule": (dte.vib_r5 > 16).to_numpy(), f"model, tau {tau}": pte >= tau}
tabs = {k: tally(dte, v, fte) for k, v in policies.items()}
print(f"test period, {len(fte)} motor failures, tau {tau} chosen on the training period")
print("policy              inspections  caught  missed  cost (thousand THB)")
for k, t in tabs.items():
    n, c, m, cost = money(t)
    print(f"{k:<19} {n:>11}  {c:>6}  {m:>6}  {cost / 1000:>19.1f}")
rng = np.random.default_rng(0)
yv, by_drone = yte.to_numpy(), [np.flatnonzero(dte.drone.to_numpy() == d) for d in range(40)]
ap_rows = [average_precision_score(yv[i], pte[i]) for i in (rng.integers(0, len(yv), len(yv)) for _ in range(1000))]                # resample flights with replacement
ap_drones = [average_precision_score(yv[i], pte[i]) for i in (np.concatenate([by_drone[d] for d in rng.integers(0, 40, 40)]) for _ in range(1000))]   # resample airframes with replacement
print(f"test PR-AUC {average_precision_score(yv, pte):.3f}: 95% interval resampling flights [{np.percentile(ap_rows, 2.5):.3f}, {np.percentile(ap_rows, 97.5):.3f}], resampling airframes [{np.percentile(ap_drones, 2.5):.3f}, {np.percentile(ap_drones, 97.5):.3f}]")
draws = [rng.integers(0, 40, 40) for _ in range(2000)]                      # draw 40 airframes with replacement, 2,000 times
model_key = f"model, tau {tau}"
for other in ("run to failure", "every 30 days", "technician rule"):
    diff = np.array([money(tabs[model_key], d)[3] - money(tabs[other], d)[3] for d in draws]) / 1000
    lo, hi = np.percentile(diff, [2.5, 97.5])
    print(f"model minus {other:<15}: {money(tabs[model_key])[3] / 1000 - money(tabs[other])[3] / 1000:>7.1f} thousand THB, 95% interval over airframes [{lo:.1f}, {hi:.1f}]")
test PR-AUC 0.753 (prevalence 0.113); out-of-fold PR-AUC on the training period 0.500
choose the alert threshold on the training period (out-of-fold scores)
tau  inspections  caught  missed  cost (thousand THB)
0.1          342      35       4                883.0
0.2          264      32       7                868.0
0.3          204      29      10                880.0
0.4          145      21      18               1063.5
0.5          104      16      23               1172.0
0.6           70      10      29               1325.0
test period, 22 motor failures, tau 0.2 chosen on the training period
policy              inspections  caught  missed  cost (thousand THB)
run to failure                0       0      22                880.0
every 30 days               120       9      13                754.0
technician rule              96      16       6                480.0
model, tau 0.2               94      20       2                341.0
test PR-AUC 0.753: 95% interval resampling flights [0.697, 0.802], resampling airframes [0.658, 0.848]
model minus run to failure :  -539.0 thousand THB, 95% interval over airframes [-727.0, -355.0]
model minus every 30 days  :  -413.0 thousand THB, 95% interval over airframes [-630.0, -208.5]
model minus technician rule:  -139.0 thousand THB, 95% interval over airframes [-269.0, -37.0]

On the training period the lowest total cost lies on a flat stretch between thresholds 0.1 and 0.3 (883.0, 868.0 and 880.0 thousand baht). They differ too little to choose by the difference, so 0.2, which is marginally the lowest, is taken. At higher thresholds the cost jumps because more motor failures are missed (0.5 gives 1,172.0 thousand baht). The test period has 22 motor failures. Running to failure costs 880.0 thousand baht. Inspecting on a 30-day schedule uses 120 inspections but catches only 9 of 22, because the warning window of 19 days (3 to 21 days) is shorter than the inspection cycle, and costs 754.0 thousand baht. The technicians’ rule catches 16 of 22 with 96 inspections (480.0 thousand baht) and the model catches 20 of 22 with 94 inspections (341.0 thousand baht). The difference between the model and the technicians’ rule is −139.0 thousand baht, with a 95% interval from resampling whole airframes of −269.0 to −37.0, which does not straddle zero but is very wide. The figure rests on only 22 motor failures, assumed costs and a single test window, and it does not include the uncertainty from choosing the threshold and from retraining. The honest statement is “in this test window the model cost about 29% less than the technicians’ rule, and that is unlikely to be luck alone”, not “it saves 139,000 baht a year”.

The difference between the two resampling choices shows in the test PR-AUC of 0.753. Resampling single flights gives a 95% interval of 0.697 to 0.802 (width 0.105), but resampling whole airframes gives 0.658 to 0.848 (width 0.190), almost twice as wide. The uncertainty of this task comes from the number of airframes, not the number of flights. Note also that the out-of-fold score on the training period, split by airframe, is 0.500, far below the 0.753 of the test period, because the two numbers answer different questions (new airframes against the same airframes in the future), as module 6 taught. Report the one that matches the client’s question.

Horizontal bar chart of the total cost of four policies in the test period in thousand baht: run to failure 880.0 in pink, inspect every 30 days 754.0 in yellow, technician rule 480.0 in blue, model 341.0 in green
Figure 3 Total cost of four alert policies in the test period (assumed values)

Monitoring data drift after deployment

A model is trained on past data but used on the future. When the inputs or the relationships change, performance can decay without any error appearing. Gama et al. (2014) survey adaptation to concept drift and separate a change in the distribution of the inputs from a change in the relationship between inputs and labels. The difficulty in maintenance is late labels: the label of today’s flight is known when the motor fails or 21 days have passed. Monitoring must therefore first use what is known immediately: the distribution of the inputs against a reference window with a two-sample test such as the Kolmogorov-Smirnov statistic (SciPy developers, ks_2samp), and the alert rate. Labels and real metrics confirm later. Rabanser et al. (2019) compared methods for detecting dataset shift and found that a two-sample test applied after reducing dimensionality with a pre-trained classifier worked best in their experiments, but our data has only a few features, so each can be tested directly. One caution: flight data is correlated over time and within an airframe, so the p-values of the KS test will be too small. Look at the size of the statistic D against its normal range rather than at the p-value.

Example 4 Vibration shifts up by 2.5 m/s² after day 200: what can we watch, and how much does retraining help?

Simulate two worlds. In the first nothing changes (the original data). In the second the baseline vibration rises by 2.5 m/s² from day 200 (assumed, for example a new batch of propellers), with the motors failing on exactly the same days. The old model is trained on flights before day 129 because, on day 150, the labels of later flights are not yet mature. The first table watches every 30 days and shows the values of both worlds side by side. The second table scores days 250 and later for the old model and for a model retrained on flights before day 229 (labels mature up to day 250 exactly). The threshold is the one from Example 3.

from scipy.stats import ks_2samp
clean = data                                                                # the world with no change, which is the data of the earlier examples
live, _ = build_data(drift_day=200)                                         # the world where vibration rises by 2.5 m/s^2 from day 200 (assumed, for example a new batch of propellers)
ref = clean[clean.day < 129]                                                # on day 150 only the labels of flights before day 129 are known (21 days of waiting)
old = hgb(**final_params).fit(ref[FEATURES], ref.fault)
print("window      n   KS vib_r5      alert rate        PR-AUC       (clean / drift)")
ks_clean, ks_drift = [], []
for lo in range(150, 344, 30):
    wc, wd = (d[(d.day >= lo) & (d.day < lo + 30)] for d in (clean, live))
    pc, pd_ = old.predict_proba(wc[FEATURES])[:, 1], old.predict_proba(wd[FEATURES])[:, 1]
    k1, k2 = ks_2samp(ref.vib_r5, wc.vib_r5).statistic, ks_2samp(ref.vib_r5, wd.vib_r5).statistic
    ks_clean.append(k1); ks_drift.append(k2)
    print(f"{lo}-{lo + 29}  {len(wd):>4}  {k1:.3f} / {k2:.3f}   {(pc >= tau).mean():.3f} / {(pd_ >= tau).mean():.3f}   {average_precision_score(wc.fault, pc):.3f} / {average_precision_score(wd.fault, pd_):.3f}")
print(f"largest KS in the clean windows {max(ks_clean):.3f}; smallest KS in the drift windows from day 210 {min(ks_drift[2:]):.3f}")
print("KS of the other features in the drift world, window 270-299:", ", ".join(f"{f} {ks_2samp(ref[f], live[(live.day >= 270) & (live.day < 300)][f]).statistic:.3f}" for f in ("temp_r5", "amps_r5", "hours")))
print(f"days 250+ at tau {tau}: prevalence clean {clean[clean.day >= 250].fault.mean():.3f}, drift {live[live.day >= 250].fault.mean():.3f} (same failures, only the vibration baseline moved)")
print("world  model                        alert rate  precision  recall  PR-AUC")
for name, world in (("clean", clean), ("drift", live)):
    ev = world[world.day >= 250]
    for label, m in (("old, trained before day 129", old), ("retrained before day 229", hgb(**final_params).fit(world[world.day < 229][FEATURES], world[world.day < 229].fault))):
        p = m.predict_proba(ev[FEATURES])[:, 1]; flag = p >= tau; hit = (flag & (ev.fault == 1)).sum()
        print(f"{name:<6} {label:<27} {flag.mean():>10.3f}  {hit / flag.sum():>9.2f}  {hit / ev.fault.sum():>6.2f}  {average_precision_score(ev.fault, p):>6.3f}")
window      n   KS vib_r5      alert rate        PR-AUC       (clean / drift)
150-179   584  0.093 / 0.093   0.070 / 0.070   0.239 / 0.239
180-209   599  0.078 / 0.118   0.110 / 0.120   0.452 / 0.447
210-239   592  0.100 / 0.305   0.111 / 0.149   0.719 / 0.613
240-269   580  0.065 / 0.282   0.138 / 0.178   0.686 / 0.675
270-299   603  0.077 / 0.232   0.078 / 0.114   0.391 / 0.398
300-329   613  0.077 / 0.280   0.085 / 0.119   0.663 / 0.574
330-359   297  0.113 / 0.299   0.145 / 0.182   0.635 / 0.627
largest KS in the clean windows 0.113; smallest KS in the drift windows from day 210 0.232
KS of the other features in the drift world, window 270-299: temp_r5 0.072, amps_r5 0.054, hours 0.089
days 250+ at tau 0.2: prevalence clean 0.113, drift 0.113 (same failures, only the vibration baseline moved)
world  model                        alert rate  precision  recall  PR-AUC
clean  old, trained before day 129      0.107       0.59    0.56   0.572
clean  retrained before day 229         0.151       0.59    0.79   0.751
drift  old, trained before day 129      0.142       0.55    0.69   0.557
drift  retrained before day 229         0.167       0.55    0.81   0.695

The KS of vib_r5 in the unchanged world never exceeds 0.113, while in the shifted world it is 0.232 to 0.305 from the window starting at day 210, and the KS of the other features stays low (temp_r5 0.072, amps_r5 0.054, hours 0.089 in the window 270 to 299), which says that something changed at the vibration sensor in particular. This observation can be made immediately without waiting for labels. The alert rate also moves, from 0.111 to 0.149 in the window 210 to 239 and from 0.138 to 0.178 in the window 240 to 269. The metrics that use labels, however, hardly show the difference. The PR-AUC of a 30-day window swings from 0.239 to 0.719 even in the unchanged world (a few tens of positive flights per window), and the difference between the two worlds reverses in some windows (0.391 against 0.398), so the PR-AUC of a short window cannot serve as a warning. The totals from day 250 onwards give a clearer picture. The old model in the shifted world raises an alert on 0.142 of flights against 0.107 (up 33%), precision falls from 0.59 to 0.55, recall rises from 0.56 to 0.69 and PR-AUC falls from 0.572 to 0.557. The effect of this kind of drift is therefore more alerts and more wrong ones, rather than a worse ranking of the failing motors, because the shift moved the values in the direction that makes every airframe look more worn. If the values shifted the other way, expect more misses, which is more dangerous (try it in lab step 5). Retraining on flights before day 229, which holds 29 days of post-shift data, lifts PR-AUC to 0.695 in the shifted world, but in the unchanged world retraining also lifts it, to 0.751, because there is more data. The two must therefore not be set against the old model to claim that this is all the effect of fixing the drift. The gap between 0.751 and 0.695 is the price of having only 29 days of post-shift data.

Line chart of two series of the KS statistic of vib_r5 by 30-day window from 150-179 to 330-359. The green line, the world with no change, stays between 0.065 and 0.113. The pink line, the world with the vibration shift, starts equal to the green and then rises to 0.305, 0.282, 0.232, 0.280 and 0.299. A dashed line at 0.2
Figure 4 KS statistic of the 5-flight mean vibration against the reference window

The retraining condition should therefore be written as a rule in advance that uses signals known immediately, for example “KS of vib_r5 above 0.2 in two consecutive 30-day windows, or the alert rate changes by more than 30% for 60 days” (0.2 is above the highest value of the normal world, 0.113, and below the lowest of the shifted world, 0.232), and then confirmed with labels that have matured over a longer period. Drift caused by a change of sensor or equipment (new propellers, new ESC firmware) should be checked against the maintenance records rather than answered with immediate retraining, because sometimes the thing at fault is the sensor, not the drone.

Explaining a model with permutation importance

Clients do not trust a model that cannot say why it warned, and the developers need an explanation to check that the model relies on something reasonable. The importance computed from the structure of a random forest (feature_importances_, which measures how much a feature reduces node impurity on the training data) has problems: it is biased towards continuous numerical features, and because it is computed on the training data it also counts what the model uses to memorise the training data. Permutation importance (Breiman, 2001) measures more directly: shuffle the values of one feature in a held-out data set so that it loses its relationship with the label, and see how much the metric drops, . The scikit-learn guide (page Permutation feature importance) recommends computing it on a held-out set to see what contributes to the model’s ability to generalise, and warns that when two features are correlated, permuting one still leaves the other for the model to use, so both look less important than they are. The remedy used in the example is to shuffle correlated columns together as a group.

Example 5 Feature importance on unseen airframes, and handing over the model

Train a random forest on 30 airframes of the training period and hold out 10 unseen airframes for evaluation. Compare the impurity importance (from the training data) with the permutation importance (on the held-out airframes, 30 shuffles), then shuffle the correlated pairs together.

from sklearn.model_selection import GroupShuffleSplit
a, b = next(GroupShuffleSplit(1, test_size=0.25, random_state=0).split(Xtr, ytr, gtr))           # hold out 10 airframes the model has never seen
rf = RandomForestClassifier(300, min_samples_leaf=5, random_state=0, n_jobs=1).fit(Xtr.iloc[a], ytr.iloc[a])
Xh, yh = Xtr.iloc[b], ytr.iloc[b]
base = average_precision_score(yh, rf.predict_proba(Xh)[:, 1])
rng = np.random.default_rng(0)
def drop(cols, reps=30):
    # drop in PR-AUC when the rows of the listed columns are shuffled together, averaged over several rounds
    ds = []
    for _ in range(reps):
        Xp = Xh.copy(); Xp[cols] = Xh[cols].to_numpy()[rng.permutation(len(Xh))]
        ds.append(base - average_precision_score(yh, rf.predict_proba(Xp)[:, 1]))
    return np.mean(ds), np.std(ds, ddof=1)
print(f"{Xh.shape[0]} flights of {gtr.iloc[b].nunique()} unseen airframes, PR-AUC {base:.3f}; correlation of vib with vib_r5 {data.vib.corr(data.vib_r5):.2f}")
print("feature     impurity importance (training)   permutation drop in PR-AUC (sd over 30 shuffles)")
for f, imp in sorted(zip(FEATURES, rf.feature_importances_), key=lambda t: -t[1]):
    m, s = drop([f]); print(f"{f:<10} {imp:>22.3f} {m:>22.3f} ({s:.3f})")
print("shuffled together:")
for grp in (["vib", "vib_r5"], ["temp", "temp_r5"], ["amps", "amps_r5"]):
    m, s = drop(grp); print(f"{' + '.join(grp):<20} {m:>13.3f} ({s:.3f})")
1121 flights of 10 unseen airframes, PR-AUC 0.639; correlation of vib with vib_r5 0.95
feature     impurity importance (training)   permutation drop in PR-AUC (sd over 30 shuffles)
hours                       0.241                  0.217 (0.020)
vib_r5                      0.185                  0.099 (0.025)
temp_r5                     0.154                  0.097 (0.029)
amps_r5                     0.132                  0.021 (0.019)
vib                         0.108                  0.017 (0.011)
temp                        0.064                 -0.012 (0.005)
amps                        0.060                  0.012 (0.017)
payload                     0.029                  0.003 (0.002)
ambient                     0.026                  0.002 (0.002)
shuffled together:
vib + vib_r5                 0.211 (0.043)
temp + temp_r5               0.144 (0.030)
amps + amps_r5               0.062 (0.025)

The impurity importance gives amps_r5 0.132, vib 0.108 and temp 0.064, but when shuffled on unseen airframes the score hardly drops (0.021, 0.017 and −0.012). The model uses these features to recognise airframes it has seen, which does not help with new ones. What really helps is hours (0.217), vib_r5 (0.099) and temp_r5 (0.097). This agrees with what the logistic regression of module 7 said about odds ratios (the recent mean vibration and bearing temperature, and the flight hours of the current motor) and with the physics of wear. Vibration and vib_r5 are correlated at 0.95, so shuffling them separately gives 0.017 and 0.099, 0.116 in total, but shuffling them together gives 0.211, almost twice as much. Reading features one at a time would underestimate the importance of vibration by half. The temperature pair (0.144 against 0.085) and the current pair (0.062 against 0.033) behave the same way. Remember that importance says what the model uses, not what causes the failure, and that it is uncertain when computed from only 10 airframes (the standard deviation of the shuffles of 0.02 to 0.04 does not include the variation from choosing the airframes).

import json, os, tempfile, joblib
RANGES = {"vib": (0, 60), "temp": (0, 90), "amps": (0, 60), "hours": (0, 200), "ambient": (-10, 60), "payload": (0, 5), "vib_r5": (0, 60), "temp_r5": (0, 90), "amps_r5": (0, 60)}
def check_input(df):                                                        # check the inputs before predicting: all columns present, none missing, all inside the accepted range
    missing = [c for c in FEATURES if c not in df]
    if missing: raise ValueError(f"missing columns {missing}")
    for c, (lo, hi) in RANGES.items():
        bad = int((~df[c].between(lo, hi)).sum())
        if bad: raise ValueError(f"{c}: {bad} value(s) outside [{lo}, {hi}] or missing")
    return df[FEATURES]
path = os.path.join(tempfile.mkdtemp(), "motor_risk_v1.joblib")
joblib.dump({"model": final, "features": FEATURES, "tau": tau}, path)       # save the trained model together with the feature list and the threshold
bundle = joblib.load(path)                                                  # load only files the team created itself; a model file from another source can run code
print("reloaded model gives identical scores:", np.array_equal(bundle["model"].predict_proba(Xte)[:, 1], pte))
bad_batch = Xte.head(5).copy(); bad_batch.iloc[0, bad_batch.columns.get_loc("vib")] = -3.0
for name, batch in (("good batch", Xte.head(5)), ("bad batch ", bad_batch)):
    try: check_input(batch); print(f"{name}: accepted")
    except ValueError as err: print(f"{name}: rejected, {err}")
card = {"model": "motor_risk_v1 (HistGradientBoostingClassifier)",
        "use": f"rank flights by risk that the motor fails within 21 days; alert at score >= {tau}; a technician decides the action",
        "not for": "judging pilots or crews, or releasing an aircraft without inspection",
        "training data": f"{len(Xtr)} flights of {gtr.nunique()} airframes, days 0-249 (synthetic)",
        "valid range": f"motor hours up to {Xtr.hours.max():.0f}; airframes of the fleet only",
        "test result": f"PR-AUC {average_precision_score(yte, pte):.2f} at prevalence {yte.mean():.3f}; {money(tabs[model_key])[1]} of {len(fte)} failures caught with {money(tabs[model_key])[0]} inspections",
        "known limits": "22 failures in the test period; costs are assumed; labels arrive 21 days late",
        "retrain when": "KS of vib_r5 above 0.2 in two consecutive 30-day windows, or the alert rate moves by more than 30% for 60 days"}
print(json.dumps(card, indent=1, ensure_ascii=False))
reloaded model gives identical scores: True
good batch: accepted
bad batch : rejected, vib: 1 value(s) outside [0, 60] or missing
{
 "model": "motor_risk_v1 (HistGradientBoostingClassifier)",
 "use": "rank flights by risk that the motor fails within 21 days; alert at score >= 0.2; a technician decides the action",
 "not for": "judging pilots or crews, or releasing an aircraft without inspection",
 "training data": "4508 flights of 40 airframes, days 0-249 (synthetic)",
 "valid range": "motor hours up to 63; airframes of the fleet only",
 "test result": "PR-AUC 0.75 at prevalence 0.113; 20 of 22 failures caught with 94 inspections",
 "known limits": "22 failures in the test period; costs are assumed; labels arrive 21 days late",
 "retrain when": "KS of vib_r5 above 0.2 in two consecutive 30-day windows, or the alert rate moves by more than 30% for 60 days"
}

The last block is what is delivered with the model, in four parts. First, save the model with joblib together with the list of features and the threshold in one file. Reloaded, it must return every score unchanged. The caution is that this kind of file runs code when loaded, so load only files that the team created and whose origin has been checked, and use the same scikit-learn version as when it was saved (scikit-learn developers, page Model persistence); record the library versions with the file. Second, check the inputs before every prediction. The example rejects a batch with a negative vibration value rather than letting the model predict from broken data without telling anyone. Third, the model card (Mitchell et al., 2019) states the intended use, the training data, the test result, the limits and the retraining condition. The numbers in the card come from variables of the earlier blocks so that the document and the real results cannot disagree. Fourth, monitoring according to the conditions in the drift section.

Grouped bar chart for three pairs of features: vibration, temperature and current. Each group has two bars. The sum of the separate shuffles is 0.116, 0.085 and 0.033, and the joint shuffles give 0.211, 0.144 and 0.062. The values are the drop in PR-AUC
Figure 5 Drop in PR-AUC when correlated features are shuffled separately against together

Personal data and the ethical use of results

A maintenance model looks like purely technical work, but flight logs and production logs often contain data that identifies people, such as the name or ID of a pilot, the time and place of work, operator IDs and the customer’s site. Four things must be done before and after handover. First, collect only what is necessary. Section 22 of the Personal Data Protection Act B.E. 2562 (2019) allows personal data to be collected only as necessary under the lawful purpose of the data controller. The feature table in this module holds only sensor values and motor hours, with no column that identifies a person, which should be the default, and an identifier needed for joining tables (the airframe ID) should be a code that is not tied to a person’s name. Second, tie the use of the results to the purpose. A model that predicts motor failure should not be used to rank pilots, appraise people or settle liability, because it was not trained and validated for that, and the model card must state this prohibition (the “not for” field). Third, keep a person in the decision. The prediction is a risk ranking for the technician to consider, not an order to release or ground an aircraft. Decisions on flight safety remain the duty of those with authority under CAAT rules, and a report must always state its uncertainty and its cost assumptions. The NIST AI Risk Management Framework (AI RMF 1.0, 2023), a voluntary guidance, organises the work into four functions, Govern, Map, Measure and Manage, which match what this module did: assigning owners and rules (Govern), stating the context and scope of use (Map), measuring with uncertainty (Measure), and monitoring with a retraining condition (Manage). Fourth, disclose the limits. The model card and the report must say which fleet and period the training data came from, which range of values the model is valid for, and how many failures the test result rests on, because the end users cannot see these limits from the model itself.

Module lab

Lab: hand over a maintenance model with results you can trust

  1. Run the first part of Example 1 with your group’s seed, raise the random-search budget to 60 draws and compare the best score with that of 27 draws. Write whether the score rose because the model improved or because the maximum of noisy numbers rose.
  2. Repeat the nested cross-validation of Example 1 with the hyper-parameters of a random forest (number of trees, max_depth, min_samples_leaf) and report the selection bias and the difference from the default with its standard deviation.
  3. Run Example 2 with the cost of a defective cap reaching a customer set to 20, 60 and 150 baht. Compute by hand and see how the cost per 1,000 caps differs between the raw forest and the calibrated one at .
  4. Run Example 3 with the cost of a motor failing mid-job set to 15,000 and 100,000 baht. Record how the chosen threshold and the result against the technicians’ rule change, and write a one-sentence report statement that is honest about the uncertainty interval.
  5. Run Example 4 with the vibration shift set to 1.0 and 5.0 (and also try negative values). See how KS, the alert rate and recall change, and whether the retraining rule you set still catches it.
  6. Run Example 5 on the bottling-line data of module 9 (or real PLC records held by the department). Compute the grouped permutation importance of the correlated sensors and write one paragraph of explanation that a technician can understand.
  7. Write a one-page model card for your own work, stating the use, the prohibitions, the training data, the test result with its uncertainty interval, the retraining condition and the personal data that were removed from the table.

Common mistakes

Watch out

  • Reporting the best score of a search as the expected result. The maximum of noisy numbers is inflated; use the outer score of nested cross-validation.
  • Spending time on tuning before checking the labels, the features and the split, which change results far more.
  • Using uncalibrated probabilities and then choosing the threshold from cost theory.
  • Using the threshold 0.5, or the one that maximises F1, without asking what each kind of error costs.
  • Bootstrapping single flights although flights of the same airframe are not independent, which gives an interval that is too narrow.
  • Counting correctly predicted flights instead of simulating the whole policy. A warning too late for the technician to act is worthless.
  • Choosing the threshold or the model on the test set, or touching the test set more than once.
  • Waiting for labels before monitoring. Labels are late, so watch the inputs and the alert rate first, and do not use the PR-AUC of a short window with few events as a warning signal.
  • Retraining at every drift without checking whether a sensor has drifted or the equipment has really changed.
  • Reading impurity importance, or the single-feature permutation importance of correlated features, as a reason or a cause.
  • Loading model files from unknown sources, and not recording the library versions with the model.
  • Keeping person-identifying columns in the training table without need, or using a maintenance model to assess people.

Summary

  • Hyper-parameters are set before training. Random search is no worse than the grid at the same budget and tries more values of the important hyper-parameters.
  • The best score from a search carries selection bias; check it with nested cross-validation. In the example the bias is 0.054 and tuning did not help unseen airframes.
  • Probabilities must be calibrated before use. The threshold with the lowest expected cost is , and the assumed costs must be stated.
  • Report the test result once, with an uncertainty interval that resamples whole airframes, and compare it with the baseline through the cost of the whole policy.
  • Monitor drift with the inputs and the alert rate, which are known immediately; late labels confirm afterwards. Set the retraining condition in advance.
  • Permutation importance on unseen airframes is more trustworthy than impurity importance, and correlated features must be shuffled as a group.
  • Hand over with input checks, a model card, prohibitions on use, only the personal data that is necessary, and a person making the decision.

Self-check questions

  1. A 4 × 4 × 4 grid over three hyper-parameters uses how many trials, and how many learning rates are tried, compared with 64 random draws where the learning rate is drawn from a continuous range?
  2. A search reports a PR-AUC of 0.62, but on unseen airframes in the outer loop it scores 0.55, and the default scores 0.56 on the same outer folds. What is the selection bias, and what do you conclude about tuning?
  3. Rejecting a good cap costs 3 baht and a defective cap reaching a customer costs 150 baht. What threshold gives the lowest expected cost, and should a cap with a predicted probability of 0.03 be rejected?
  4. The alert rate rises from 0.107 to 0.142. By what percentage, and has the criterion “changes by more than 30% for 60 days” been triggered?
  5. Shuffling vib drops PR-AUC by 0.017 and shuffling vib_r5 by 0.099, but shuffling both together drops it by 0.211. Why is the sum of the first two (0.116) smaller?
Answers
  1. The grid uses trials, but only 4 learning rates are tried (each repeated 16 times), whereas 64 random draws give 64 different learning rates.
  2. The bias is , and the difference between the tuned and default models on the outer loop is . There is no evidence that tuning helps new airframes; the apparent gain came from picking the maximum of noisy numbers.
  3. . A probability of 0.03 is above , so the cap should be rejected (the expected cost of rejecting is baht, lower than the expected cost of releasing it, baht).
  4. The rise is , about 33%, which is over 30%, but the criterion requires it to hold for 60 days. One window is not enough; keep watching to see whether it persists.
  5. The two features are correlated at 0.95. When one is shuffled the model can still use the information in the other, so each one’s importance on its own is too low. Shuffled together they show the full importance (0.211), almost twice the sum of the single values.

Key formulas

Threshold with the lowest expected cost
Brier score
Two-sample Kolmogorov-Smirnov statistic
Permutation importance of feature j
Total cost of an alert policy

Key references

  1. Géron, A. (2022). Hands-on machine learning with Scikit-Learn, Keras, and TensorFlow (3rd ed.). O'Reilly.
  2. Bergstra, J., & Bengio, Y. (2012). Random search for hyper-parameter optimization. Journal of Machine Learning Research, 13(10), 281–305. link
  3. Cawley, G. C., & Talbot, N. L. C. (2010). On over-fitting in model selection and subsequent selection bias in performance evaluation. Journal of Machine Learning Research, 11, 2079–2107. link
  4. scikit-learn developers. Tuning the hyper-parameters of an estimator (scikit-learn 1.9). scikit-learn user guide. link
  5. scikit-learn developers. Nested versus non-nested cross-validation (scikit-learn 1.9). scikit-learn examples. link
  6. Efron, B. (1979). Bootstrap methods: Another look at the jackknife. The Annals of Statistics, 7(1), 1–26. link
  7. Field, C. A., & Welsh, A. H. (2007). Bootstrapping clustered data. Journal of the Royal Statistical Society: Series B, 69(3), 369–390. link
  8. Niculescu-Mizil, A., & Caruana, R. (2005). Predicting good probabilities with supervised learning. In Proceedings of the 22nd International Conference on Machine Learning (pp. 625–632). ACM. link
  9. Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. (2017). On calibration of modern neural networks. In Proceedings of the 34th International Conference on Machine Learning (PMLR 70, pp. 1321–1330). link
  10. Elkan, C. (2001). The foundations of cost-sensitive learning. In Proceedings of the 17th International Joint Conference on Artificial Intelligence (IJCAI'01). link
  11. scikit-learn developers. Probability calibration (scikit-learn 1.9). scikit-learn user guide. link
  12. Brier, G. W. (1950). Verification of forecasts expressed in terms of probability. Monthly Weather Review, 78(1), 1–3. link
  13. Gama, J., Žliobaitė, I., Bifet, A., Pechenizkiy, M., & Bouchachia, A. (2014). A survey on concept drift adaptation. ACM Computing Surveys, 46(4), Article 44. link
  14. Rabanser, S., Günnemann, S., & Lipton, Z. C. (2019). Failing loudly: An empirical study of methods for detecting dataset shift. In Advances in Neural Information Processing Systems 32 (arXiv:1810.11953). link
  15. SciPy developers. scipy.stats.ks_2samp: Two-sample Kolmogorov-Smirnov test. SciPy reference guide. link
  16. Breiman, L. (2001). Random forests. Machine Learning, 45(1), 5–32. link
  17. scikit-learn developers. Permutation feature importance (scikit-learn 1.9). scikit-learn user guide. link
  18. scikit-learn developers. Model persistence (scikit-learn 1.9). scikit-learn user guide. link
  19. Mitchell, M., Wu, S., Zaldivar, A., Barnes, P., Vasserman, L., Hutchinson, B., Spitzer, E., Raji, I. D., & Gebru, T. (2019). Model cards for model reporting. In Proceedings of the Conference on Fairness, Accountability, and Transparency (pp. 220–229). ACM. link
  20. National Institute of Standards and Technology. (2023). Artificial intelligence risk management framework (AI RMF 1.0) (NIST AI 100-1). link
  21. พระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. 2562. ราชกิจจานุเบกษา, 136(69 ก), 52–95. 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: Law, safety and risk · Management, innovation and professional practice · Artificial intelligence and computer vision · Mission planning, flight and simulation