Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 10: Model Evaluation and Training Control — Implementation

Open in Colab
  1. cross_validate: several metrics, training scores and timings at once

  2. Comparing two models on the same folds

  3. Group and time-series splits, made visible

  4. Nested cross-validation on real data

  5. A training monitor: divergence detected, learning rate halved

  6. Early stopping with patience, by hand and in scikit-learn

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.

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:

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.

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)
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.

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 η=0.248\eta = 0.248), 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.

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.

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:

scikit-learn stopped after 23 epochs; best validation accuracy 0.950; accuracy on the 1 497 held-out digits 0.908

Summary

  • cross_validate gives several metrics, training scores and timings in one call.

  • Compare models on the same folds and look at the paired differences.

  • GroupKFold keeps entities together; TimeSeriesSplit validates 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.