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

Open in Colab

The first principle is that you must not fool yourself, and you are the easiest person to fool.

Richard Feynman

10.1 A Score Is a Measurement

Chapter 9 chose hyperparameters on validation data and reported a test score. But a test score is computed on a sample of data, and a different sample would give a different number. How different?

We train the same logistic regression on the breast-cancer data 50 times, each time with a different random 80/20 split, and record the test accuracy:

50 splits: from 0.947 to 1.000, mean 0.980, standard deviation 0.012

The same model, on the same data, scores anywhere from 0.947 to 1.000 depending on which 114 tumours happened to land in the test set. A single split could make it look perfect, or merely good. Comparing two models whose scores differ by less than this spread, on one split, is comparing noise.

Evaluation is a procedure, and this chapter is about procedures whose results can be trusted: how to split, how often, and what to report.

10.2 Hold-Out: Training, Validation and Test

The simplest procedure splits the data once:

PartTypical shareUsed for
Training60–80%fitting the parameters
Validation10–20%choosing hyperparameters and models, early stopping
Test10–20%one final, unbiased estimate

Hold-out is fine when data are plentiful (tens of thousands of examples): every part is then large enough for its score to be stable. With a few hundred examples, as above, a single validation part is noisy, and it wastes data that could have been used for training.

10.3 k-Fold Cross-Validation

k-fold cross-validation uses every example for validation exactly once:

  1. Split the (training) data into kk parts of equal size, the folds.

  2. For each fold i=1,…,ki = 1, \dots, k: train on the other k−1k - 1 folds, and score on fold ii.

  3. Report the mean of the kk scores, and their standard deviation.

the five fold scores: [0.965 0.982 0.956 0.956 1.   ]
5-fold: 0.972 ± 0.017

Every example is used for training k−1k - 1 times and for validation once, so the estimate uses the data far better than a single split, and the spread of the fold scores shows how stable it is.

  • Choosing kk: 5 or 10 are the usual choices. A larger kk trains on more data each time (less pessimistic) but costs more fits and gives correlated folds.

  • Leave-one-out (k=nk = n): train on all but one example, nn times. Nearly unbiased, expensive, and its estimate can have high variance; use it for very small datasets.

  • Repeated k-fold: run k-fold several times with different shuffles and average, to reduce the variance of the estimate further.

10.4 Splits That Respect the Data

A random split assumes the examples are independent and identically distributed. When they are not, the split must say so.

Stratified folds

With imbalanced classes, random folds can contain very different shares of the rare class, and some may contain none at all. Stratified k-fold keeps the class proportions the same in every fold. Here, 200 examples with 10.5% positives:

share of positives in each fold, random:     [0.1   0.15  0.125 0.075 0.075]
share of positives in each fold, stratified: [0.1   0.1   0.1   0.1   0.125]

Random folds range from 7.5% to 15% positives; stratified folds stay at 10–12.5%. For classification, scikit-learn’s cross_val_score stratifies by default.

Group folds

When several rows belong to the same entity (a patient, a customer, an apartment sold twice), all of them must fall on the same side of every split, or the model is scored on entities it has already seen (Chapter 7, Section 7.9). GroupKFold takes a groups array and keeps each group in one fold.

Time-series splits

When the data are ordered in time and the model will predict the future, it must never be trained on the future. TimeSeriesSplit trains on an expanding window of the past and validates on the period that follows:

SplitTrain onValidate on
1months 1–4month 5
2months 1–5month 6
3months 1–6month 7

10.5 Nested Cross-Validation

When hyperparameters are tuned by cross-validation (Chapter 9), the best cross-validated score is optimistic: it is the maximum of many noisy estimates, and the winner is partly the luckiest. To estimate how well the whole procedure, tuning included, performs, put the tuning inside another cross-validation:

  • the inner loop (on each outer training part) chooses the hyperparameters;

  • the outer loop scores the tuned model on data the inner loop never saw.

The effect is clearest on data with nothing to learn: 60 examples, 20 features of noise, random labels, and an SVM tuned over 64 settings of CC and γ\gamma.

best cross-validated score of the search: 0.583
nested estimate of the tuned procedure:   0.467   (majority class: 0.533)

On pure noise, the search reports 0.583: it found a setting that happened to fit the folds. The nested estimate, 0.467, says what is true: the tuned model is no better than guessing. On real data the gap is usually smaller, but it is always in the same direction.

10.6 Learning Curves

A learning curve plots training and validation scores against the size of the training set. It answers the most expensive question in a project: will more data help?

logistic regression: sizes [45, 113, 227, 341, 455]
   training   [0.987 0.986 0.989 0.983 0.988]
   validation [0.873 0.944 0.965 0.972 0.979]
deep decision tree: sizes [45, 113, 227, 341, 455]
   training   [1. 1. 1. 1. 1.]
   validation [0.81  0.884 0.912 0.907 0.926]
Source
<Figure size 1100x330 with 2 Axes>

How to read them:

PatternMeaningWhat helps
Both curves high and close togethera good fitnothing urgent
Both curves low, close together, flathigh bias (underfitting)a richer model or features; more data will not
A large gap; validation still risinghigh variance (overfitting)more data, or regularisation

The logistic regression’s curves meet near 0.98: it is close to what this model can do. The deep tree keeps a training accuracy of 1.000 and a gap of about 0.07 even with all the data: it overfits, and its validation curve is still rising, so more data would help it, but a forest or a shallower tree would help sooner.

10.7 Watching Training: Converging or Diverging?

Models trained by iterative optimisation (gradient descent and its variants, Chapters 8 and 15) should be watched while they train. The record of the loss, epoch after epoch, is the model’s vital sign.

The learning rate

Linear regression on the standardised diabetes data, trained by full-batch gradient descent with four learning rates η\eta. For this loss, theory says gradient descent converges only when η<1/λmax⁡\eta < 1/\lambda_{\max}, where λmax⁡\lambda_{\max} is the largest eigenvalue of X⊤X/nX^\top X / n; here 1/λmax⁡=0.2481/\lambda_{\max} = 0.248.

1 / lambda_max = 0.248
eta = 0.01: MSE after 0, 10, 50, 200 epochs: ['1.000', '0.678', '0.513', '0.486']
eta = 0.1 : MSE after 0, 10, 50, 200 epochs: ['1.000', '0.489', '0.485', '0.484']
eta = 0.25: MSE after 0, 10, 50, 200 epochs: ['1.000', '0.878', '1.512', '38.453']
eta = 0.3 : MSE after 0, 10, 50, 200 epochs: ['1.000', '317.711', 'overflow', 'overflow']

Four behaviours, each with a cause:

Loss curveDiagnosisAction
falls slowly, still falling at the end (η=0.01\eta = 0.01)learning rate too small, or too few epochsraise η\eta, train longer
falls fast and flattens (η=0.1\eta = 0.1)convergingkeep
falls, then rises slowly (η=0.25\eta = 0.25)just above the stable rate: diverginglower η\eta
explodes to overflow and NaN (η=0.3\eta = 0.3)diverginglower η\eta a lot; check the scaling of the inputs
jumps up and down without settlingoscillating: η\eta too large, or batches too small and noisylower η\eta, larger batches, a learning-rate schedule
flat from the startstuck: a bug, dead units, a wrong loss, unscaled inputscheck the data and the gradients

Training against validation, epoch by epoch

A neural network (one hidden layer of 256 units, Chapter 15) learns 300 handwritten digits. After each epoch we record the loss on the training data and on 1 497 validation digits:

lowest validation loss at epoch 14: 0.230; at epoch 150: 0.299
training loss at epoch 14: 0.0495; at epoch 150: 0.00055
Source
<Figure size 650x330 with 1 Axes>

Both losses fall together at first: the network is learning things that generalise. From epoch 14 on, the training loss keeps falling towards zero while the validation loss turns back up: the network has started memorising its 300 examples. That turning point is where early stopping keeps the weights (scikit-learn: MLPClassifier(early_stopping=True); in PyTorch, by saving the model whenever the validation loss improves, Chapter 16).

10.8 Reporting a Result

  • Report the mean and the spread (standard deviation across folds, or a confidence interval), not a single number.

  • Compare models with the same folds (paired), and treat differences smaller than the spread with suspicion.

  • Say which procedure produced the number: k-fold, nested, or a held-out test set used once.

  • Fix the random seeds and keep the code, so that someone else gets the same number.

10.9 Summary

  • One test split gives one noisy measurement: the same model scored 0.947 to 1.000 across 50 splits.

  • k-fold cross-validation uses each example for validation once; report mean ± standard deviation.

  • Stratify for imbalanced classes; group for repeated entities; respect time for forecasting.

  • Nested cross-validation estimates the performance of tuning itself; the best search score is optimistic.

  • Learning curves tell whether more data will help (high variance) or not (high bias).

  • Watch the loss while training: converging, stalling, oscillating or diverging each have a cause; when training and validation losses part ways, stop early.

Exercises

  1. Why can two models with test accuracies of 0.96 and 0.97 on one split not be said to differ? What would you do instead?

  2. Write the steps of 5-fold cross-validation for a model whose preparation includes a scaler. Where is the scaler fitted?

  3. A dataset has 20 000 rows from 400 customers. Which splitter do you use, and why?

  4. Explain, with the words “inner” and “outer”, what nested cross-validation estimates that plain cross-validation does not.

  5. A learning curve shows training accuracy 0.99 and validation accuracy 0.80 at the largest size, with validation still rising. What do you recommend?

  6. A loss curve goes 2.3, 1.1, 0.9, 1.4, 3.7, nan. Diagnose and give two fixes.

  7. Training loss falls steadily, validation loss falls until epoch 30 and then rises. What should be saved, and when should training stop?

Further Reading

  • G. James, D. Witten, T. Hastie, R. Tibshirani, An Introduction to Statistical Learning, 2nd ed., Springer, 2021, Chapter 5 (resampling methods).

  • S. Varma, R. Simon, “Bias in error estimation when using cross-validation for model selection”, BMC Bioinformatics, 2006 (nested cross-validation).

  • S. Raschka, “Model evaluation, model selection, and algorithm selection in machine learning”, arXiv:1811.12808, 2018.

  • I. Goodfellow, Y. Bengio, A. Courville, Deep Learning, MIT Press, 2016, Chapter 11 (practical methodology).