How machines learn
Data Leakage: When the Answer Sneaks Into the Question
Recognize target, temporal, preprocessing, group, and selection leakage and build controls that keep evaluation evidence independent.
By the end you can
- Define leakage as information or dependence that gives the model unfair access to the target or held-out data
- Distinguish target, temporal, preprocessing, group, and selection leakage
- Investigate suspiciously strong results using a structured leakage audit
- Design pipelines and review practices that prevent leakage before training
Example
The X-rays that still classified COVID-19 with the lungs blacked out
In the spring of 2020, COVID-19 classifiers trained on chest X-rays were being published faster than anyone could check them, and each arrived with an accuracy figure. Gianluca Maguolo and Loris Nanni ran the test those figures cannot run on themselves. They blacked out the centre of the images, removing most of the lung field — the organ the model was supposed to be reading — and re-ran the classification. The results barely moved. “We show that similar results can be obtained using X-Ray images that do not contain most of the lungs”, they wrote in 2020.
What the models were reading was the border, the cropping, the processing — the fingerprint of where an image came from. Roberts and colleagues reproduced the effect in Nature Machine Intelligence with their own figures. From the non-lung region alone, the source of the Cohen and Kermany datasets could be identified at an AUC between 0.9210 and 0.9997. COVID-19 itself was “diagnosed” at an AUC of 0.68. Positive cases had been assembled from one collection and negative cases from another, so the fastest route to a high score was never pneumonia. It was telling the two collections apart.
- The shortcut was present from the moment the dataset was assembled: source collection tracked the label, so dataset identity was a legitimate-looking column of pixels.
- Nothing in a per-image accuracy score separates lung findings from the markings, cropping and processing that identify a hospital or a repository.
- Random splitting kept both collections on both sides of the split, so the shortcut survived intact into validation and test.
- Occluding most of the lung field left classification results comparable — the diagnostic evidence was demonstrably not what was carrying the score.
- The corrective test is an ablation: remove the region that is supposed to carry the signal, and see whether the number follows it down.
Leakage changes the question the model is actually answering
Data leakage occurs when training or evaluation uses information, transformations, or dependencies that would not be available under the intended prediction conditions, so the resulting score answers an easier or different question.
The IJCNN 2011 Social Network Challenge shows how far apart those two questions can drift. Kaggle released an anonymised graph of 1,133,547 nodes and 7,237,983 edges and asked entrants to say which of 8,960 test edges were real. The winning team recognised the graph as Flickr, crawled Flickr themselves, and matched the anonymised nodes back to accounts. “Using our own crawl of Flickr, we were able to successfully de-anonymize 64.7% of the test edge-set”, they report. They won with a test AUC of 0.981. A separate group, describing the same contest independently, recorded the winners predicting “over 60% of edges which were identified” and classed the episode as leakage. The organisers had set a link-prediction problem. The winning method solved a lookup problem, and the leaderboard could not tell the difference.
Leakage is not limited to an obvious target column: it can enter through time, preprocessing, duplicate entities, selection rules, human review, or features that indirectly encode the outcome.
A leaked model may be mathematically well trained and operationally useless.
Case
Seventeen fields, 294 papers, and a taxonomy of eight leaks
Leakage is not a story about a few sloppy labs. It has been counted across science. Sayash Kapoor and Arvind Narayanan surveyed research fields that had adopted machine learning and reported, in Patterns in 2023, “17 fields where leakage has been found, collectively affecting 294 papers and, in some cases, leading to wildly overoptimistic conclusions”. They set out “a detailed taxonomy of eight types of leakage, ranging from textbook errors to open research problems”.
Then they re-ran one of those literatures. In civil-war prediction, complex models were believed to beat older statistical ones decisively. Once the errors were corrected, the complex models “do not perform substantively better than decades-old LR models”. Nothing about the models had changed. The comparison had.
Visual
Five common ways future or held-out knowledge enters
The categories overlap. But they guide different checks. Group leakage is the one a random split cannot see by construction, and the measured example is radiological.
A network was given 158,323 chest radiographs from three hospital systems — 112,120 from NIH, 42,396 from Mount Sinai and 3,807 from Indiana — and trained to name the hospital instead of the disease. It almost never missed. “CNNs were able to directly detect hospital system of a radiograph for 99.95% NIH (22,050/22,062) and 99.98% MSH (8,386/8,388) radiographs”, Zech and colleagues report in PLOS Medicine in 2018. A second network went finer and separated departments inside Mount Sinai: 5,805/5,805 inpatient and 449/449 emergency-department radiographs.
That would be a curiosity if the hospitals shared a case mix. They did not. Pneumonia prevalence was 34.2% at Mount Sinai against 1.2% at NIH and 1.0% at Indiana. So a model that did nothing but rank cases by the prevalence of the system they came from reached AUC 0.861 (95% CI 0.855–0.866) on the joint Mount Sinai–NIH test set. An image carries its own site membership. A random split scatters sites across every partition. The score that comes out is partly a measurement of prevalence. An independent review in npj Health Systems states the consequence plainly: “Zech et al. (2018) demonstrated that models trained on data from one hospital showed reduced performance on external datasets”.
Target leakage
An input directly or indirectly reveals the label or a post-outcome consequence.
Temporal leakage
The example uses information created after the prediction cutoff or trains on the future to predict the past.
Preprocessing leakage
Statistics, feature selection, imputation, or encoding are learned using validation or test data.
Group leakage
Related records, identities, or near-duplicates cross partitions and make held-out examples familiar.
Selection leakage
The dataset contains labels only for cases chosen by an earlier rule, model, or intervention.
Comparison
Fit transformations inside the training boundary
The order of operations determines whether held-out data influences the model, and the size of that influence has been measured rather than assumed.
Two published microarray results had a handful of genes classifying tumours almost perfectly. Xiong and colleagues had selected three genes using all the tissue samples, then averaged Fisher's rule over 200 random 95/5% training/test splits. The average test error was 10.7% on the colon data and 0% on the leukaemia data, where the internal leave-one-out cross-validation error for those three genes was zero. Christophe Ambroise and Geoffrey J. McLachlan performed the selection inside an external 10-fold cross-validation instead, and separately inside a .632+ bootstrap. The estimated prediction error rose to about 15% on the colon data and about 5% on the leukaemia data. “Using two published data sets, we demonstrate that when correction is made for the selection bias, the cross-validated error is no longer zero for a subset of only a few genes”, they wrote in the Proceedings of the National Academy of Sciences in 2002.
Zero became about five per cent. 10.7% became about fifteen. Nothing about the classifier changed. Only the boundary moved. Kapoor and Narayanan give this failure its own entry in their taxonomy, L1.3, “Feature selection on training and test set”. Nor does it need labels to bite. Moscovich and Rosset showed that even unsupervised, label-free preprocessing carried out outside the training boundary “can introduce a substantial bias into cross-validation estimates”.
Leaky sequence
Split after learning preprocessing from the entire dataset.
- Global mean fills missing values
- All rows choose important features
- Target encoding sees held-out labels
- Reported performance is biased upward
Valid sequence
Split first, fit preprocessing on training data, and reuse it unchanged.
- Training mean fills all partitions
- Feature selection uses training evidence
- Cross-fitting handles target encodings
- Validation and test remain outside fitting
A timestamp should describe availability, not merely occurrence
An event can occur at 10:00. It may become available to the prediction system only at 10:30, after processing. A corrected record may be backfilled days later. Historical tables often store the final value without preserving when the value became known. The costliest version of this is not a late timestamp, though. It is an early one: a field written down precisely because a human had already noticed the thing the model is being asked to predict.
The Epic Sepsis Model has been re-evaluated on exactly that point. Over 77,582 University of Michigan hospitalisations from 2018–2020, sepsis occurred 3,766 times, 4.9% of them. Kamran and colleagues separated the predictions the model issued before clinicians had acted from those it issued afterwards, using receipt of antibiotics, fluids, blood culture and/or lactate measurement as the marker that the team had already recognised sepsis. Their result, published in NEJM AI in 2024, reads: “ESM achieved an AUROC of 0.62 (95% confidence interval [CI], 0.61 to 0.63) when including predictions before sepsis criteria were met and in some cases, after clinical recognition. When excluding predictions after clinical recognition, the AUROC dropped to 0.47 (95% CI, 0.46 to 0.48).”
Moving the prediction moment back to before the moment a clinician acted took a deployed commercial model from 0.62 to below chance. The model did not change. A large part of the 0.62 was a record of what the treating team already suspected, reaching the feature set as an order for a blood culture.
Independent evaluations point the same way. A validation in JAMIA Open covered 145,885 ED encounters at 2 hospitals in 2023 and reported sensitivity of 14.7% within a 6-hour window. A methodological systematic review in npj Digital Medicine covering 91 studies found median AUROC of 0.886 and 0.861 at 6 and 12 hours before onset, falling to 0.783 under full-window external validation. It warns that “retrospective validation still carries the risk of label leakage”.
For each feature, record event time, ingestion time, update time, and the prediction cutoff. Point-in-time reconstruction should use the version genuinely available then — and for any feature a person can influence, record when the person first acted.
Analogy
An analogy: an exam copy with faint answer impressions
An exam booklet arrives with faint impressions on its pages. They were pressed there by an answer key stored on top. A student may appear exceptionally capable while reading clues that will not exist on a clean exam.
Leakage creates the same illusion by placing outcome information or familiar structure inside the input. Nobody has to cheat for this to happen. A blood-culture order is a legitimate clinical field. A patient identifier is an administrative necessity. An image border is a property of the scanner. Leakage arises unintentionally, from data processing, grouping, and selection.
Key idea
Results that should trigger a leakage investigation
Leakage is more likely in three situations. Performance is implausibly high, a simple identifier dominates, or the score collapses under a time or group split. Investigate also when a feature's meaning is difficult to explain before the outcome.
The COVID-19 radiography literature is what an entire field looks like when nobody applies those signals. The Nature Machine Intelligence review identified 2,212 studies, kept 415 after initial screening and 62 after quality screening, and concluded that none of the models it examined were of potential clinical use. It describes public collections duplicated and recombined into “Frankenstein datasets”, in which source identity predicts the label better than pathology does. Every one of those papers reported a number that looked good. The number was the last thing that should have been believed.
None of these signals proves leakage. They indicate that the evidence deserves adversarial review before additional tuning.
Treat surprising success as a debugging opportunity, not only as a reason to celebrate.
Case
KDD Cup 2008: the patient ID that predicted cancer
KDD Cup 2008 is the case worth memorising. The patient identifier alone divided the 1,712 training patients into three ID bands. The malignancy rates in those bands were 36%, 1% and 1.7%. All 18 malignant patients in the top band had IDs between 4,000,000 and 4,870,000. They shared that range with only 3 healthy patients. The identifiers were a fingerprint of which institution had supplied each batch of images.
The team that found this is the team that won, and they published it themselves. Their verdict was blunt. “All models built on this data set are likely to overestimate the true predictive performance of cancer detection when applied to an entirely different population”.
Figure
Position
Treat the good result as a bug report
Every leaderboard, demo and quarterly review teaches the same reflex. A strong number is evidence that the work went well, and whoever doubts it carries the burden of proof. Invert that here. In this one situation the base rates justify inverting it. A result meaningfully better than the task should permit is more often an accounting error than a discovery. The audit that settles it is six steps long.
The evidence in this lesson is not about careless people. Kapoor and Narayanan found leakage across 17 fields and 294 papers, in eight varieties running from textbook errors to open research problems; in corrected civil-war prediction the complex models “do not perform substantively better than decades-old LR models”. At KDD Cup 2008 the shortcut was a patient identifier that split 1,712 patients into bands 36%, 1% and 1.7% malignant, and it was found and published by the team that won. Zech and colleagues were able to name the source hospital for 99.95% of NIH radiographs and 99.98% of Mount Sinai radiographs, and hospital prevalence alone was worth AUC 0.861. The Epic Sepsis Model, a product in live clinical use, scored 0.62 with post-recognition predictions counted and 0.47 without them.
The useful review question is therefore not “is this too good to be true”. That invites a defence rather than an investigation. Ask instead: which single feature is doing most of the work, when was its value written, and does the score survive its removal? Maguolo and Nanni answered all three at once by blacking out the lungs and watching the accuracy stay put. Kamran and colleagues answered them by asking when the blood culture was ordered, and watched 0.62 fall to 0.47. Neither test required a new model.
A score that beats what the task should allow is a bug report until someone has read the feature list.
Steps
Trace every feature through time and partition boundaries
A leakage audit combines data lineage, domain knowledge, and controlled experiments. Step 3 in particular is not merely a good habit. Where the stakes are highest it is written down and signed. On 27 October 2021 the US FDA, Health Canada and the UK MHRA jointly published ten Good Machine Learning Practice guiding principles for medical device development. Principle 4 is titled “Training data sets are independent of test sets”. It reads in full: “Training and test datasets are selected and maintained to be appropriately independent of one another. All potential sources of dependence, including patient, data acquisition and site factors are considered and addressed to assure independence.”
Patient, acquisition and site are named explicitly, by three regulators, in a document about what may be sold to hospitals. The entity, time and site barriers below are that requirement expressed as work.
1. Re-state the prediction moment
Specify exactly when the output must be available.
2. Inventory feature provenance
Record source, timestamps, joins, transformations, and update logic.
3. Rebuild the split
Use entity, time, or site barriers that match deployment.
4. Move preprocessing inside
Fit every learned transform using training data only.
5. Ablate suspicious inputs
Remove features, identifiers, and near-duplicates, then measure the change.
6. Reproduce live construction
Generate examples using the same information path expected in production.
Sometimes the missing labels are the leakage story
A fraud team may know outcomes only for transactions selected for investigation. A hiring system may observe job performance only for applicants who were hired. The labeled sample then reflects previous policies.
This is not repaired by deleting a column. The team must understand the selection process, gather exploration data where appropriate, or narrow claims to the population whose outcomes are observed. Narrowing is precisely what the Epic Sepsis Model re-evaluation did. Kamran and colleagues restricted the score to predictions issued before clinicians had recognised sepsis, and reported 0.47, not 0.62, as the answer to the question the model was bought to answer.
Key takeaways
- Leakage means the learning procedure receives information or dependence unavailable under the intended use, so the score answers a different question. The IJCNN 2011 Social Network Challenge was won by recognising the graph as Flickr and de-anonymising 64.7% of the test edge set, for a test AUC of 0.981.
- Target, temporal, preprocessing, group, and selection leakage enter through different paths and require different controls. Kapoor and Narayanan found eight varieties across 17 fields and 294 papers.
- Historical presence in a database does not prove that a feature was available at prediction time. The Epic Sepsis Model scored AUROC 0.62 with post-recognition predictions counted, and 0.47 — below chance — once they were excluded.
- All learned preprocessing belongs inside the training boundary. Moving gene selection inside an external cross-validation raised Ambroise and McLachlan's estimated error from 0% to about 5% on the leukaemia data, and from 10.7% to about 15% on the colon data.
- Implausible scores, dominant identifiers, and sharp drops under realistic splits are reasons to investigate leakage. Networks named the source hospital for 99.95% of NIH radiographs, and ranking by hospital prevalence alone reached AUC 0.861.
- Selection leakage reflects which outcomes were observed under prior policies, and may require new data or narrower claims rather than column deletion.