Leakage (machine learning)
Leakage, often called data leakage, happens in machine learning when a model is built using information that would not be available at the moment it makes real predictions.[1] The model gets help during testing that it will not get in use, so its measured accuracy is higher than its true accuracy.[2]
A trivial example is a model that takes the answer itself as an input and so concludes that "it rains on rainy days".[2] Real cases are usually subtle, such as test data that share patients with the training data, or a cleaning step run on all the data before it was split. Leakage has been found in at least 294 published papers across 17 scientific fields.[3]
The basic idea
In supervised learning, a model learns to predict a target (the outcome) from features (the input variables). To estimate how it will do on new cases, model builders hold back a test set that the model does not train on.[4] The score on the test set stands in for performance once the model is in real use.
That score is honest only if the test set is kept fully separate during every step of preprocessing, modeling, and evaluation.[3] If any information from the test set reaches the model before it is scored, the model learns relationships that new data will not offer. Its test score then no longer shows how it would do on fresh data.[3]
Leakage can also enter through a feature, even with a clean split. Two textbook examples are:[2]
- an "account number" feature in a model that predicts whether a customer will open a bank account, although numbers are assigned only after an account is opened;
- an "interviewer name" feature in a model that predicts which phone customers will leave, where one salesperson handled customers who had already said they were leaving.
Why leakage matters
Leakage makes performance estimates too optimistic.[1] A client may find out only after the model is put to use, when it does systematically worse than promised, and even then the cause can be hard to trace.[2] A leaky model can also be a worse model, beaten in practice by a leak-free one that could have been built instead.[2]
A scikit-learn demonstration shows how large the effect can be.[1] It uses 200 samples with 10,000 random features and random labels, so no model should beat chance (accuracy about 0.5).
- Picking the 25 best features from all the data, then splitting, gave a test accuracy of 0.76.
- Splitting first and picking features from the training data alone gave 0.5.
Types of leakage
Kapoor and Narayanan sorted the leakage they found in published science into eight types.[3] The types fall into three groups: no clean separation of training and test data (L1), features that are not legitimate (L2), and test data not drawn from the population the claim is about (L3).[3]
| Code | Type | Example |
|---|---|---|
| L1.1 | No test set | Training and testing on the same data |
| L1.2 | Preprocessing on training and test data together | Filling in missing values or oversampling before the split |
| L1.3 | Feature selection on training and test data together | Choosing features by how well they do on all the data |
| L1.4 | Duplicates in the dataset | The same record lands in both training and test sets |
| L2 | Illegitimate features | Use of blood-pressure drugs as a feature to predict high blood pressure |
| L3.1 | Temporal leakage | Test data dated before the training data |
| L3.2 | Non-independence of training and test samples | Different images of the same patient on both sides |
| L3.3 | Sampling bias in the test set | Leaving borderline autism cases out of the test set |
Some types, such as sampling bias, were not counted as leakage in earlier work.[3] Kapoor and Narayanan include them because they share the same cause (false links between features and outcome) and the same effect (overestimated performance).[3]
Leaking features
A leaking feature carries information about the target that will not be known when the prediction is needed.[2] One instance is a proxy for the outcome, a feature that stands in for the answer itself.[5] In one medical study, taking drugs for high blood pressure was used to predict high blood pressure, a feature that makes the task trivial if known and is unavailable for a new patient if not.[5]
Whether a feature is legitimate depends on the problem and needs domain knowledge.[5] For this reason Kapoor and Narayanan give no subtypes for L2 and ask researchers to justify each feature.[5]
Preprocessing and feature selection before the split
Any step that learns from data can leak if it sees the test set.[1] This includes scaling, imputation of missing values, oversampling (which adds copies or synthetic versions of examples from rare classes), principal component analysis (a method that compresses many features into a few), and feature selection.[1][3] Oversampling before the split, for example, puts samples derived from the training data into the test set.[3]
Feature selection is a classic case. In 2002 Ambroise and McLachlan showed that gene-expression studies reporting near-zero error with only a few genes had chosen those genes using the same samples they tested on.[6] When gene selection was redone inside each round of cross-validation, the error was no longer zero.[6]
Tuning on the test set
Hyperparameters are settings chosen before training, such as model size. Adjusting them until the test score is best leaks knowledge of the test set into the model.[4] The usual fix is a separate validation set for tuning, with the test set used only for the final score.[4]
Cross-validation used to pick hyperparameters has the same problem when its score is also reported as the result.[7] Cawley and Talbot showed in 2010 that this selection bias can be as large as the differences between learning methods.[8] Nested cross-validation runs the tuning in an inner loop and estimates error in an outer loop on data the tuning never saw.[7]
Duplicates and related samples
A random split assumes each sample is independent of the others, which often fails.[4] When several samples come from one patient, subject, or device, a random split can place related samples on both sides. The model can then score well by recognizing the person rather than learning the task.[4]
The effect can be large.
- In digital pathology, scores were inflated by up to 41% when image tiles from the same subject were in both training and validation sets.[9]
- In brain-scan studies, repeating 20% of subjects inflated the correlation between predicted and true values by 0.06 to 0.29 across four datasets.[10]
Group-wise splitting keeps every sample of a group on one side. Scikit-learn's GroupKFold, for instance, ensures the same group never appears in both training and test folds.[4]
Temporal leakage
When a model predicts a future outcome, its test data should not include data from before the training data.[3] Otherwise the model is trained on data "from the future".[3] Data close together in time are also correlated, so a shuffled split gives poor error estimates.[4]
A time-ordered split avoids this. Scikit-learn's TimeSeriesSplit trains on the first folds and tests on fold , so each training set includes all earlier ones.[4] See time series cross-validation.
The date that matters is when information becomes known, not the date it describes. Stock models look very good if they assume quarterly company data are available a day after the quarter ends, though such data usually become public about three weeks later.[11]
Test sets that miss the target population
A test set chosen from a narrower group than the claim covers also inflates results.[3] In one autism study, excluding borderline cases, which are often the hardest to diagnose, left a test set that did not represent the general population.[3] This is a form of selection bias.
Site differences can act the same way. Zech and colleagues found that a neural network trained on chest X-rays could tell which hospital system an image came from for 99.95% of images from one system and 99.98% from another.[12] Pneumonia models can pick up the same site cues.[12] Performance on X-rays from outside hospitals was significantly lower than on held-out X-rays from the training hospitals in 3 of 5 comparisons.[12]
Formal definition
Kaufman, Rosset, and Perlich defined leakage as the introduction of information about the target that should not be legitimately available to learn from.[2] What counts as legitimate is set by the exact statement of the problem, not by the data alone.[2] Their definition covers leakage both in features and in training examples.[2]
The no-time-machine rule
The most common legitimacy rule in prediction is what they call the no-time-machine requirement.[2] A feature is allowed only if it is observable earlier than the target it helps predict:
- is the target to be predicted.
- is the set of all possible features.
- is the time feature becomes observable to the user of the model.
- is the time the prediction is required.
Some problems need a stricter rule that leaves a gap before the target:[2]
The gap removes immediate triggers of the target. In a model of shoppers who become big spenders, buying a diamond right before the target date would give the answer away, so a large enough rules it out.[2]
Leakage in training examples
Leakage can also hide in which examples are used for training, even when every feature is legitimate.[2] In KDD Cup 2007, predictions were to be made as of the end of 2005. A winning entry built its training examples with data from 2006, so its final model leaked although it contained no illegitimate feature.[2]
Learn-predict separation
Kaufman and colleagues propose two steps to avoid leakage.[2]
- Tag every observation with its legitimacy, such as the time it became observable, when the data are collected.
- Build training examples only from inputs that are legitimate for every evaluation target, with a cut in time between training and evaluation examples.
Detecting leakage
The first warning sign is performance that seems too good. Pyle called such results "a dead giveaway" of leakage.[2] Kaufman and colleagues suggest three checks, each of which needs domain knowledge:[2]
- Exploratory data analysis, which looks for surprising patterns, such as an ID number that strongly predicts the target.
- Comparing results with expected or earlier results. Many entries in the INFORMS 2010 forecasting challenge contradicted prior evidence that stock prices cannot be predicted well from public information.
- Early testing in the field, where leakage shows up as a gap between estimated and real performance.
In KDD Cup 2008, on breast cancer detection from mammograms, the patient ID had strong and unexpected predictive power.[2] Analysts of the data suggested that it was merged from several sources with consecutive ID ranges, and that some sources chose their patients with prior knowledge of their condition.[2]
Code can also be checked automatically. A 2022 tool that checks code without running it found leakage to be widespread in more than 100,000 public data science notebooks.[13]
Preventing leakage
- Split the data into training and test sets first, before any preprocessing.[1]
- Fit every data-dependent step, such as scaling, imputation, or feature selection, on training data only. A pipeline that chains these steps with the model does this automatically.[1]
- Split by group when samples share a patient, subject, or device.[4]
- Split by time when predicting the future, training only on earlier data.[4]
- Tune hyperparameters on validation data or with nested cross-validation, and use the test set once.[4][7]
- Check that every feature would be known at prediction time, using domain knowledge.[5]
- Report these choices. Kapoor and Narayanan's model info sheets ask 21 questions meant to rule out each type of leakage.[3]
Fixing leakage after the fact is hard. In several competitions, attempts to remove a leak created new ones that were harder to find.[2] In the INFORMS 2008 pneumonia challenge, organizers removed target values hidden in the features, but records with all condition codes missing still gave the target away.[2]
Leakage in published research
Kapoor and Narayanan reviewed 22 papers that had found errors in machine learning studies.[3] Together these reported leakage in 294 papers across 17 fields, including medicine, neuroimaging, genomics, and computer security.[3] They link this to the wider reproducibility crisis.[3]
Civil war prediction
Their case study tested 12 civil war prediction papers that shared code and data.[3] Errors appeared in 4 of them, exactly the 4 that claimed complex models beat logistic regression.[3]
- One paper imputed missing values on training and test data together.[5]
- Two reused an imputed dataset incorrectly.[5]
- One used proxies for the target variable.[5]
After correction, the complex models did no better than logistic regression, except in one paper.[3] There the gap in area under the curve (AUC), a score of how well a model ranks positive cases above negative ones where 1 is perfect and 0.5 is chance, shrank from 0.14 to 0.01.[3]
Neuroimaging
Rosenblatt and colleagues tested five forms of leakage in brain connectivity models across four datasets.[10] Leaky feature selection and repeated subjects inflated performance sharply, while other forms had small effects. Small datasets made the effects of leakage worse.[10]
Contamination in large language models
Large language models train on huge collections of text copied from the web, which can contain the test sets of the benchmarks used to evaluate them.[14] This train-test overlap is often called data contamination.[14]
The GPT-3 team tried to remove such overlaps, but a bug left some in, and retraining was too costly.[14] They found little effect on most benchmarks but flagged a few where contamination could inflate results.[14] See evaluation of large language models.
History of the term
The problem was known under several names before it had a formal definition.[2]
- Pyle called it "anachronisms", meaning information out of place in time.
- Nisbet and colleagues called it "leaks from the future" and listed it among the top 10 data mining mistakes.
- Rosset and colleagues described it as "the unintentional introduction of predictive information about the target by the data collection, aggregation and preparation process".
Kaufman, Rosset, and Perlich gave a formal definition at the KDD conference in 2011.[2] An extended version, with Stitelman as a further author, appeared in 2012.[11] Kapoor and Narayanan's 2023 taxonomy extended the idea to machine-learning-based science.[3]
Related problems
Leakage overlaps with, but differs from, several other problems.
- Overfitting means fitting noise in the training data. Testing on the training data, the simplest leak, is a textbook case of it.[3]
- Distribution shift is a change between the data a model was tested on and the data it meets later. Kapoor and Narayanan treat poor generalization to a different population as related to leakage but distinct from it.[3]
- Privacy leakage is a different use of the word. It means a trained model revealing sensitive facts about its training data.[15]
References
- Common pitfalls and recommended practices, scikit-learn documentation, 2026.
- Leakage in data mining: formulation, detection, and avoidance, Kaufman, Rosset, and Perlich, Proceedings of the 17th ACM SIGKDD Conference, 2011.
- Leakage and the reproducibility crisis in machine-learning-based science, Kapoor and Narayanan, Patterns, 2023.
- Cross-validation: evaluating estimator performance, scikit-learn documentation, 2026.
- Leakage and the reproducibility crisis in ML-based science (preprint), Kapoor and Narayanan, arXiv, 2022.
- Selection bias in gene extraction on the basis of microarray gene-expression data, Ambroise and McLachlan, PNAS, 2002.
- Nested versus non-nested cross-validation, scikit-learn documentation, 2026.
- On over-fitting in model selection and subsequent selection bias in performance evaluation, Cawley and Talbot, Journal of Machine Learning Research, 2010.
- AI slipping on tiles: data leakage in digital pathology, Bussola et al., arXiv, 2019.
- Data leakage inflates prediction performance in connectome-based machine learning models, Rosenblatt et al., Nature Communications, 2024.
- Leakage in data mining: formulation, detection, and avoidance, Kaufman, Rosset, Perlich, and Stitelman, ACM Transactions on Knowledge Discovery from Data, 2012.
- Variable generalization performance of a deep learning model to detect pneumonia in chest radiographs, Zech et al., PLOS Medicine, 2018.
- Data leakage in notebooks: static detection and better processes, Yang et al., arXiv, 2022.
- Language models are few-shot learners, Brown et al., arXiv, 2020.
- Survey: leakage and privacy at inference time, arXiv, 2021.
