Mathematical foundations
Empirical Risk, Selection, and Generalization
Understand empirical and population risk, adaptive model selection, validation wear-out, and the limits of iid generalization under deployment shift.
By the end you can
- Define empirical, validation, test, and deployment risk
- Treat preprocessing and tuning as parts of the learning algorithm
- Explain how adaptive selection can create optimistic performance estimates
- Audit whether a generalization claim matches the intended future distribution
The algorithm includes more than the final fit call
Feature selection, preprocessing, hyperparameter search, early stopping, threshold choice, and manual iteration all use data. They belong to the learning algorithm when analyzing generalization. A guarantee for a fixed predictor does not automatically apply after choosing among thousands of candidates on the same validation set.
This is not a classroom scruple. On 27 October 2021 three medical-device regulators — the US FDA, Health Canada and the UK MHRA — jointly published ten Good Machine Learning Practice guiding principles. The fourth is titled “Training Data Sets Are Independent of Test Sets”. It states: “Training and test datasets are selected and maintained to be appropriately independent of one another.” The principle does not stop at storing the files separately. It requires that all potential sources of dependence, including patient, data acquisition and site factors, be considered and addressed. Three regulators had to write that down because splits fail in practice, for reasons that never appear in the fit call.
The failure has been counted. Kapoor and Narayanan went looking for data leakage across the sciences and reported the tally in Patterns in 2023: “Through a survey of literature in fields that have adopted ML methods, we find 17 fields where leakage has been found, collectively affecting 294 papers and, in some cases, leading to wildly overoptimistic conclusions.” Their civil-war-prediction case study is the mechanism in miniature. The reported superiority of ML models over logistic regression disappeared once the leakage was corrected. An independent group then put a size on which channels matter. Working across four datasets in Nature Communications, they concluded that “Leakage via feature selection and repeated subjects drastically inflates prediction performance, whereas other forms of leakage have minor effects”.
Reproducible code is not enough. Feature selection run before the split is reproducible, and it is also the channel that moved the numbers most. The information flow from data to every design choice must be included.
Training minimizes an empirical quantity while deployment depends on a population
A learning algorithm sees a finite sample and chooses a predictor using empirical risk. Deployment performance depends on population risk under the future data-generating process. Generalization is the gap between those two quantities. It is not a mysterious property stored inside a model. It is a relationship among data, algorithm, hypothesis class, loss, and target population.
The first task is to define the population and sampling mechanism that make the comparison meaningful. Every case in this lesson is a case where that definition was skipped and a number survived anyway, until someone measured it somewhere else.
Generalization is always relative to a population, loss, and data-collection process.
Case
Image classifiers that fit random labels, 2017
Capacity alone does not settle the question. Take a state-of-the-art convolutional network, replace every training label with a random one, and train it with the usual stochastic gradient methods. It fits. Zhang and colleagues reported in 2017 that such networks “easily fit a random labeling of the training data”. The obvious remedy did not remove the effect: “This phenomenon is qualitatively unaffected by explicit regularization”. A model class able to memorize arbitrary labels cannot have its generalization explained by the class alone. Learning and memorizing produce the same training curve. Zero training error tells you nothing about which one just happened.
Key idea
IID generalization does not cover distribution shift
Classical generalization often compares sample and population under the same distribution. A deployed system can violate that assumption through seasonality, policy changes, new devices, and feedback loops.
Google Flu Trends was trained to reproduce CDC influenza-like-illness rates, and against that target it fitted well. Then the behaviour it was reading moved underneath it. Lazer and colleagues went back over the record in Science in March 2014 and found the model had been wrong for years: “GFT also missed by a very large margin in the 2011–2012 flu season and has missed high for 100 out of 108 weeks starting with August 2011”. The same paper marks the moment it became impossible to ignore, in February 2013: “Nature reported that GFT was predicting more than double the proportion of doctor visits for influenza-like illness (ILI) than the Centers for Disease Control and Prevention (CDC)”. An independent evaluation in PLOS Computational Biology had already reached the same verdict. It found the system “completely missing the first wave of the 2009 influenza A/H1N1 pandemic, and greatly overestimating the intensity of the A/H3N2 epidemic during the 2012/2013 season”, and stated plainly: “We conclude that GFT data may not provide reliable surveillance for seasonal or pandemic influenza”.
Shift across sites and devices has a measured base rate rather than an anecdote. A 2022 systematic review in Radiology: Artificial Intelligence went through 83 published external-validation studies covering 86 deep-learning radiology algorithms. Its result: “The vast majority (70 of 86, 81%) reported at least some decrease in external performance compared with internal performance, with nearly half (42 of 86, 49%) reporting at least a modest decrease (≥0.05 on the unit scale) and nearly a quarter (21 of 86, 24%) reporting a substantial decrease (≥0.10 on the unit scale).” Losing accuracy off-site is the common case, not the exception.
A small iid test error therefore does not guarantee robust performance after shift. Separate stress tests, temporal holdouts, and monitoring are needed. The theorem and the deployment claim must refer to the same data-generating process.
A valid iid estimate can answer the wrong future-distribution question.
Comparison
Training, validation, test, and deployment risk
Each estimate has a distinct role and a distinct exposure to adaptive reuse. Training risk is the objective value on the data used to fit parameters. It is optimistically biased for selection and useful mainly as an optimization diagnostic. Validation risk guides model and hyperparameter choices, which makes it part of the adaptive algorithm and liable to wear out through repeated use. Test risk estimates the locked procedure after selection. It should be consulted sparingly, and contamination invalidates it. Deployment risk is the actual loss under live conditions. It is the only one a patient, a customer, or a clinician ever meets.
The distance between the reported number and the deployed one has been measured on a system running in hospitals. Epic Systems reported that its proprietary Sepsis Model scored an AUC of 0.76–0.83. Wong and colleagues, writing in JAMA Internal Medicine in 2021, validated it externally on 27,697 patients and 38,455 hospitalizations at Michigan Medicine between December 2018 and October 2019. They measured a hospitalization-level AUC of 0.63 (95% CI, 0.62–0.64), with 33% sensitivity. The paper states it directly: “Our observed hospitalization-level model performance (AUC, 0.63) was substantially worse than that reported by Epic Systems (AUC, 0.76-0.83)”. Its conclusion is unhedged: “This external validation cohort study suggests that the ESM has poor discrimination and calibration in predicting the onset of sepsis.”
The finding survived a second group and different hospitals. A 2024 study in JAMIA Open ran the same test across 145,885 encounters in two county emergency departments. Sensitivity was 14.7%, PPV 7.6%. Its verdict: “The ESPMv1 provides suboptimal diagnostic characteristics for undifferentiated patients in a county ED.” Two independent deployments, one vendor-reported range, and a gap that did not close.
Training risk
Objective value on data used to fit parameters.
- Optimistically biased for selection
- Useful for optimization diagnostics
- Not an external estimate
- Can expose underfitting
Validation risk
Guides model and hyperparameter choices.
- Part of the adaptive algorithm
- Can wear out through repeated use
- Needs split integrity
- Supports comparison, not final proof
Test risk
Estimates the locked procedure after selection.
- Should be used sparingly
- Requires representative sampling
- Still has uncertainty
- Can be invalidated by contamination
Deployment risk
Actual loss under live conditions.
- May differ because of shift
- Includes workflow effects
- Can alter future data
- Requires monitoring
Analogy
Selection and familiarity inflate the winning audition score
The best performer is chosen after hundreds of auditions on the same stage. The winner’s score reflects skill. It also reflects having been picked on that stage, and knowing it well. A fresh performance on a new stage is more informative about how good the performer really is. But rehearse against the “fresh” stage often enough and it becomes part of the selection process too.
Adaptive reuse wears a stage out. By the time the last rehearsal is over there is no unfamiliar stage left to judge on.
A test set stops being external evidence once it guides design choices.
Case
CIFAR-10 and ImageNet rebuilt in 2019, and the accuracy that fell
Two famous test sets were rebuilt from scratch in 2019. Recht and colleagues followed the original creation processes for CIFAR-10 and ImageNet, then re-scored existing models on the new sets. Nothing about the models had changed. The numbers still fell: “accuracy drops of 3% - 15% on CIFAR-10 and 11% - 14% on ImageNet”. The interesting part is their diagnosis. They attribute the drop to harder images rather than to adaptivity. Even a benchmark that was not worn out by reuse can hand back a number that does not survive a second sample drawn the same way.
Steps
Audit a generalization claim
A report claiming that a model will perform well beyond its sample can be checked step by step. Two review teams ran that audit at scale, on the same subject, and neither found a survivor. Roberts and colleagues screened 2,212 studies of machine learning applied to COVID-19 chest radiographs and CT scans, and analysed 62 of them after quality screening. Their finding, in Nature Machine Intelligence on 15 March 2021: “Our review finds that none of the models identified are of potential clinical use due to methodological flaws and/or underlying biases.” A separate living review in The BMJ reached the same place. Its 2020 update appraised 51 studies describing 66 prediction models and rated all of them at high or unclear risk of bias: “This review indicates that proposed models are poorly reported, at high risk of bias, and their reported performance is probably optimistic. Hence, we do not recommend any of these reported prediction models to be used in current practice.”
Hundreds of published models, two independent appraisals, and a verdict of probably optimistic in every case. The six steps below are the checks those reviewers were applying, in the order a reader can apply them.
1. Define the population
Name units, time horizon, geography, and inclusion rules.
2. Trace data reuse
Include preprocessing, tuning, analysis, and manual choices.
3. Define the loss
Connect mathematical error to the decision being evaluated.
4. Quantify selection
Record model count, search budget, and validation exposure.
5. Estimate uncertainty
Use appropriate resampling or held-out evidence.
6. Test shift
Evaluate temporal, subgroup, and environment changes.
Visual
From population to selected model
Several adaptive steps can widen the gap between observed validation performance and future risk. The population distribution is the environment the system is meant to face. The sample is what a finite collection process actually produced. The hypothesis class bounds what may be chosen. Training and tuning use the sample repeatedly. The selected predictor is the single function that meets future data.
Each arrow is a place where information can flow the wrong way. Feature selection performed before the split moves it backwards, and across four datasets that was the channel found to inflate reported performance most. Site, device and patient dependence moves it sideways. That is why Guiding Principle 4 names patient, data acquisition and site factors by name.
- 1
Population distribution
The environment and units the system is intended to face.
- 2
Sample
Finite observations produced by a sampling process.
- 3
Hypothesis class
The candidate predictors the algorithm may choose.
- 4
Training and tuning
Adaptive procedures that use the sample repeatedly.
- 5
Selected predictor
The final function evaluated on future data.
Example
Polynomial fitting and the generalization gap
A small regression problem illustrates how training error alone can mislead.
The real-data version of the same picture is a model that fits its own hospitals and loses ground elsewhere. A pneumonia CNN was trained on 158,323 chest radiographs from three institutions, pooling Mount Sinai and NIH data. Internally it scored an AUC of 0.931. At a third hospital it had never seen, it scored 0.815. Zech and colleagues, reporting in PLOS Medicine, summarised the pattern: “Pneumonia-screening CNNs achieved better internal than external performance in 3 out of 5 natural comparisons.” The polynomial makes the mechanism visible on a handful of points. The radiographs show what it costs at 158,323.
- Low degree: The model may miss real curvature and have high training and test error.
- Moderate degree: The model can capture signal while preserving stable predictions.
- Very high degree: Training error can approach zero while test error rises — the small-scale form of the memorization the random-label experiment demonstrated.
- Regularization: Penalizing complexity can reduce variance at the cost of some fit, and it did not remove the random-label result.
- Split dependence: One lucky test split can still make an unstable model look strong, which is why 0.931 and 0.815 came from the same trained network.
Key takeaways
- Empirical risk is computed on sampled data while population risk concerns the target environment: Epic's Sepsis Model was reported at AUC 0.76–0.83 by Epic Systems and measured at 0.63 with 33% sensitivity across 38,455 hospitalizations at Michigan Medicine.
- Generalization depends jointly on data, algorithm, hypothesis class, loss, and population, and a class that can fit random labels cannot explain it on its own.
- Validation-guided decisions are part of the learning algorithm, preprocessing and feature selection included; Kapoor and Narayanan found leakage documented in 17 fields and 294 papers.
- Repeated use can turn a test set into a selection set, which is why the US FDA, Health Canada and the UK MHRA made independence of training and test sets Guiding Principle 4 on 27 October 2021.
- IID generalization does not automatically address distribution shift: 81% of 86 externally validated radiology algorithms performed worse off-site, and Google Flu Trends ran high in 100 of 108 weeks from August 2011.
- A complete audit traces every data-dependent decision before accepting a future-performance claim; two review teams applying that standard to COVID-19 prediction models recommended none of them for practice.