Chapter 10: Model Evaluation and Training Control — Implementation
cross_validate: several metrics, training scores and timings at onceComparing two models on the same folds
Group and time-series splits, made visible
Nested cross-validation on real data
A training monitor: divergence detected, learning rate halved
Early stopping with patience, by hand and in scikit-learn
import numpy as np
import warnings
from sklearn.datasets import load_breast_cancer, load_digits
from sklearn.model_selection import (cross_validate, cross_val_score, StratifiedKFold, RepeatedStratifiedKFold,
GroupKFold, TimeSeriesSplit, GridSearchCV, train_test_split)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000))
forest = RandomForestClassifier(n_estimators=200, random_state=0)1. cross_validate¶
cross_val_score returns one metric; cross_validate returns as many as you ask for, the training scores (to spot overfitting) and the time spent fitting.
res = cross_validate(forest, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=0),
scoring=['accuracy', 'recall', 'roc_auc'], return_train_score=True)
for k in ['train_accuracy', 'test_accuracy', 'test_recall', 'test_roc_auc', 'fit_time']:
print(f'{k:15s} {res[k].mean():.3f} ± {res[k].std():.3f}')train_accuracy 1.000 ± 0.000
test_accuracy 0.967 ± 0.019
test_recall 0.980 ± 0.019
test_roc_auc 0.992 ± 0.008
fit_time 0.394 ± 0.016
A training accuracy of 1.000 next to a validation accuracy of about 0.96: the forest fits its training folds perfectly, as forests do, and still generalises well. The gap alone does not condemn a model; the validation score decides.
2. Comparing Two Models on the Same Folds¶
Scores from different folds vary for reasons that have nothing to do with the models. Scoring both models on the same folds and looking at the difference fold by fold removes much of that noise. Repeated stratified k-fold gives 50 paired differences:
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0)
a = cross_val_score(logreg, X, y, cv=cv)
b = cross_val_score(forest, X, y, cv=cv)
d = a - b
print(f'logistic regression {a.mean():.3f} ± {a.std():.3f}')
print(f'random forest {b.mean():.3f} ± {b.std():.3f}')
print(f'paired difference {d.mean():+.3f} ± {d.std():.3f}; logistic regression better in {np.mean(d > 0):.0%} of the folds, tied in {np.mean(d == 0):.0%}')logistic regression 0.977 ± 0.015
random forest 0.961 ± 0.018
paired difference +0.016 ± 0.018; logistic regression better in 72% of the folds, tied in 14%
The two models’ spreads overlap, but the paired differences show a consistent advantage for one of them. (Fold scores are not independent, so a formal test needs care; the corrected resampled t-test of Nadeau and Bengio is the usual choice.)
3. Group and Time-Series Splits¶
We print which rows land in each validation fold. Twelve rows belong to four patients (A to D); GroupKFold never splits a patient.
groups = np.array(list('AAABBBCCCDDD'))
for i, (tr, va) in enumerate(GroupKFold(n_splits=4).split(np.zeros(12), groups=groups)):
print(f'fold {i}: validate on rows {va.tolist()} (patient {"".join(sorted(set(groups[va].tolist())))})')fold 0: validate on rows [9, 10, 11] (patient D)
fold 1: validate on rows [6, 7, 8] (patient C)
fold 2: validate on rows [3, 4, 5] (patient B)
fold 3: validate on rows [0, 1, 2] (patient A)
for i, (tr, va) in enumerate(TimeSeriesSplit(n_splits=4).split(np.zeros(12))):
print(f'split {i}: train on rows {tr.min()}–{tr.max()}, validate on rows {va.min()}–{va.max()}')split 0: train on rows 0–3, validate on rows 4–5
split 1: train on rows 0–5, validate on rows 6–7
split 2: train on rows 0–7, validate on rows 8–9
split 3: train on rows 0–9, validate on rows 10–11
TimeSeriesSplit always validates on rows that come after all the training rows, with a training window that grows: the past predicts the future, never the reverse.
4. Nested Cross-Validation on Real Data¶
An SVM tuned over 36 settings on the breast-cancer data. The inner loop tunes; the outer loop scores the tuned procedure.
from sklearn.svm import SVC
grid = {'svc__C': np.logspace(-2, 3, 6), 'svc__gamma': np.logspace(-4, 1, 6)}
inner, outer = StratifiedKFold(5, shuffle=True, random_state=0), StratifiedKFold(5, shuffle=True, random_state=1)
search = GridSearchCV(make_pipeline(StandardScaler(), SVC()), grid, cv=inner)
nested = cross_val_score(search, X, y, cv=outer)
search.fit(X, y)
print(f'best inner score {search.best_score_:.3f} with C = {search.best_params_["svc__C"]:g}, gamma = {search.best_params_["svc__gamma"]:g}')
print(f'nested estimate {nested.mean():.3f} ± {nested.std():.3f}')best inner score 0.981 with C = 100, gamma = 0.001
nested estimate 0.975 ± 0.012
On real data with a real signal, the gap between the two is small, but the nested estimate is the one that answers “how good will this procedure be on new data?”.
5. A Training Monitor¶
A training loop should check its own vital signs. Below, linear regression on the standardised diabetes data (the chapter’s example, where gradient descent is stable only below ), trained with a monitor that detects divergence (a non-finite loss, or a loss above its starting value), restores the last good weights and halves the learning rate.
from sklearn.datasets import load_diabetes
Xd, yd = load_diabetes(return_X_y=True)
Xd = StandardScaler().fit_transform(Xd); yd = (yd - yd.mean()) / yd.std()
A = np.c_[np.ones(len(yd)), Xd]
def train(eta, epochs=300):
w = np.zeros(A.shape[1]); good = w.copy(); first = None; log = []
for epoch in range(epochs):
r = A @ w - yd
loss = np.mean(r ** 2)
first = loss if first is None else first
if not np.isfinite(loss) or loss > first:
w, eta = good.copy(), eta / 2
log.append((epoch, f'loss {loss:.3g}: diverging, learning rate halved to {eta:g}'))
continue
good = w.copy()
w = w - eta * 2 * A.T @ r / len(yd)
return np.mean((A @ w - yd) ** 2), eta, log
with np.errstate(over='ignore', invalid='ignore'):
final, eta, log = train(eta=5.0)
for epoch, msg in log:
print(f'epoch {epoch:3d}: {msg}')
print(f'final MSE {final:.4f} with learning rate {eta:g}')epoch 1: loss 496: diverging, learning rate halved to 2.5
epoch 3: loss 117: diverging, learning rate halved to 1.25
epoch 5: loss 26.4: diverging, learning rate halved to 0.625
epoch 7: loss 5.54: diverging, learning rate halved to 0.3125
epoch 9: loss 1.22: diverging, learning rate halved to 0.15625
final MSE 0.4830 with learning rate 0.15625
Started with a learning rate twenty times too large, the monitor halves it each time the loss blows up, until it settles below the stable limit and converges. Real frameworks offer the same reflexes: learning-rate schedules that reduce the rate when the validation loss stops improving (ReduceLROnPlateau in PyTorch), gradient clipping, and checks for NaN (Chapter 16).
6. Early Stopping with Patience¶
Validation losses are noisy: a single uptick does not mean the model has started to overfit. Patience waits a number of epochs without improvement before stopping, and returns the best epoch seen.
def early_stop(val_losses, patience):
"""Return (the best epoch, the epoch where training stops): stop after `patience` epochs without a new minimum."""
best, best_epoch = np.inf, 0
for epoch, v in enumerate(val_losses):
if v < best:
best, best_epoch = v, epoch
elif epoch - best_epoch >= patience:
return best_epoch, epoch
return best_epoch, len(val_losses) - 1
digits = load_digits()
X_tr, X_va, y_tr, y_va = train_test_split(digits.data / 16, digits.target, train_size=300, random_state=0, stratify=digits.target)
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import log_loss
net = MLPClassifier(hidden_layer_sizes=(256,), alpha=0, learning_rate_init=0.01, random_state=0)
val = []
with warnings.catch_warnings():
warnings.simplefilter('ignore')
for epoch in range(150):
net.partial_fit(X_tr, y_tr, classes=np.arange(10))
val.append(log_loss(y_va, net.predict_proba(X_va), labels=range(10)))
for patience in [1, 5, 20]:
b, s = early_stop(val, patience)
print(f'patience {patience:2d}: stop after epoch {s + 1}, keep epoch {b + 1} (validation loss {val[b]:.3f})')patience 1: stop after epoch 15, keep epoch 14 (validation loss 0.230)
patience 5: stop after epoch 19, keep epoch 14 (validation loss 0.230)
patience 20: stop after epoch 34, keep epoch 14 (validation loss 0.230)
Here the curve turns cleanly, and all three keep epoch 14; a patience of 1 still stops at the very first uptick, which on a noisier curve comes before the true minimum. A larger patience costs a few epochs and buys safety. scikit-learn builds the same rule in:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
auto = MLPClassifier(hidden_layer_sizes=(256,), alpha=0, learning_rate_init=0.01, early_stopping=True,
validation_fraction=0.2, n_iter_no_change=10, max_iter=500, random_state=0).fit(X_tr, y_tr)
print(f'scikit-learn stopped after {auto.n_iter_} epochs; best validation accuracy {auto.best_validation_score_:.3f}; '
f'accuracy on the 1 497 held-out digits {auto.score(X_va, y_va):.3f}')scikit-learn stopped after 23 epochs; best validation accuracy 0.950; accuracy on the 1 497 held-out digits 0.908
Summary¶
cross_validategives several metrics, training scores and timings in one call.Compare models on the same folds and look at the paired differences.
GroupKFoldkeeps entities together;TimeSeriesSplitvalidates only on the future.Nested cross-validation scores the tuning procedure itself.
A training loop can watch its loss, undo a divergent step and lower the learning rate.
Early stopping with patience tolerates noisy validation curves and keeps the best weights.