Simple Algorithm
Machine Learning · Convergence · 24 min

Data Leakage & Contamination

How the test set sneaks into training, and how to stop it.

A model that looks brilliant in evaluation and disappoints in use has, very often, been fed information it will not have when it is used. Data miners call this leakage; a survey of machine-learning-based science found it behind errors in hundreds of published papers; and with web-scale training corpora, benchmark test sets themselves leak into the training data. This lesson gives leakage a precise definition, measures how much a single leaky step can inflate a score, and assembles the defenses.

What you’ll learn

  • Define leakage through the learn–predict separation, and classify leaks into target, preprocessing, selection, temporal, group and duplicate leakage.
  • Quantify how selecting features on the full dataset manufactures signal from noise, and explain why tuning requires nested cross-validation.
  • Explain how duplicates and near-duplicates inflate scores, and how deduplication and an exchangeability-based permutation test detect benchmark contamination.
  • Audit a pipeline for leakage before trusting its results.

What leakage is

KindWhat happensExample
Target leakagea feature is a consequence or a proxy of the target"account closed" in a churn model; a billing code assigned after the diagnosis being predicted
Preprocessing leakagea data-dependent step is fitted on all the data before splittingfeature selection, target encoding or oversampling done before the split
Selection leakagechoices are made by looking at test performancetuning hyperparameters on the test set; reporting the best of many runs
Temporal leakageinformation from after the prediction time is usedrandom splits of time series; features computed over the full history
Group leakagerelated examples sit on both sides of the splitseveral images per patient; several sessions per user
Duplicatestest examples, or near-copies of them, are in the training seta record entered twice; the same photo resized

Surveying the literature, Kapoor and Narayanan (2023) found leakage reported in 17 scientific fields, collectively affecting 294 papers, and organized it into a taxonomy of eight types, "ranging from textbook errors to open research problems." In their own case study of civil-war prediction, the published claims that complex models beat logistic regression did not survive: once the errors were corrected, complex models did not perform substantively better than decades-old logistic regression. Their remedy is the model info sheet, a structured document that walks authors through every type of leakage before publication.

Check your understanding

A model predicts, at the moment of hospital admission, whether a patient will be diagnosed with sepsis during the stay. Which candidate feature leaks the target?

  1. The patient's age
  2. Heart rate measured at admission
  3. Whether intravenous antibiotics were ordered during the stay
  4. The department that admitted the patient
Show the answer

C. Whether intravenous antibiotics were ordered during the stay

Antibiotic orders during the stay are not available at admission, and they are placed largely because sepsis is suspected: the feature is downstream of the very outcome being predicted. In validation it looks wonderfully predictive; at the moment of prediction it does not exist yet.

Leaks through preprocessing and selection

The most common leaks are innocent-looking steps done once, on all the data, before the split. Steps that use only the inputs (standardization, median imputation, principal components) leak a little information about the test inputs. Steps that use the labels can leak a lot, because they choose whatever happens to fit these labels, the held-out ones included.

Predict before you look

There are n=50n=50 examples with labels assigned by coin flips, and p=5,000p=5{,}000 features of pure noise. Roughly how large is the largest absolute correlation between any feature and the labels?

Show the answer

0.5

Each noise feature's sample correlation with the labels has standard deviation about 1/n≈0.141/\sqrt n\approx0.14, and the largest of 5,000 such correlations grows like 2ln⁡p/n\sqrt{2\ln p/n}. In simulation the maximum is typically about 0.50.5 (median 0.510.51). Screening on all the data therefore always finds features that look strongly predictive, and a classifier cross-validated on them inherits the illusion.

Ambroise and McLachlan (2002) documented this in microarray studies, where thousands of genes are screened for a few dozen patients. Selecting genes on all the samples and then cross-validating the classifier on those genes produced error estimates that could reach zero with only a handful of genes; with the selection repeated inside every fold (external cross-validation), or corrected with a bootstrap, the estimated error was no longer zero. The same holds for every label-dependent step: target encoding must be computed out of fold, and oversampling such as SMOTE must happen after the split, or synthetic neighbors of one minority example land on both sides.

Tuning is a selection step too. Varma and Simon (2006) showed that reporting the cross-validated error of a classifier tuned by that same cross-validation gives a significantly biased estimate, while nested cross-validation gives an almost unbiased one; Cawley and Talbot (2010) found that over-fitting the model-selection criterion can degrade performance surprisingly much, and that common evaluation practices suffer from the resulting selection bias.

python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score

# Leaky: features chosen once, with every label in view
#   X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
#   cross_val_score(LogisticRegression(), X_sel, y, cv=5)   # optimistic

pipe = make_pipeline(StandardScaler(), SelectKBest(f_classif, k=20),
                     LogisticRegression(max_iter=1000))
grid = {'selectkbest__k': [10, 20, 50], 'logisticregression__C': [0.1, 1, 10]}
inner = StratifiedKFold(5, shuffle=True, random_state=0)
outer = StratifiedKFold(5, shuffle=True, random_state=1)
search = GridSearchCV(pipe, grid, cv=inner)        # tuning inside each outer fold
scores = cross_val_score(search, X, y, cv=outer)   # nested CV: an honest estimate

A pipeline refits every step on each training fold, so nothing is learned from held-out labels. Wrapping the grid search in an outer loop estimates the performance of the whole procedure, tuning included.

Leaks across time, groups and duplicates

Time. A feature is legitimate only if it can be computed from data stamped before the prediction time. "Purchases this month" computed at the end of the month, a customer's total history used to score them mid-history, or a value later revised by a data provider all smuggle in the future. Production systems handle this with point-in-time joins: each training example sees the data exactly as they stood at its own prediction time.

Groups and shortcuts. Splitting images rather than patients lets a model recognize patients. A subtler relative is a shortcut that random splits cannot expose. Zech and colleagues (2018) found that convolutional networks could identify the hospital system that produced a chest radiograph almost perfectly (for 99.95% and 99.98% of the images from two of the three systems), and pneumonia was far more common in one of those two (34.2% of its images, against about 1% in the others). Pneumonia detectors could therefore gain accuracy from where an image was taken (in the authors' words, "the more predictive a hospital system was of pneumonia, the more it was exploited to make predictions"), and their internal performance significantly exceeded their performance at other hospital systems in 3 of 5 comparisons.

Duplicates. Barz and Denzler (2020) found that 3.3% of the CIFAR-10 test images and 10% of the CIFAR-100 test images have duplicates or near-duplicates in the corresponding training sets, and released ciFAIR test sets in which those images are replaced by new ones from the same domain. Language corpora are worse: Lee and colleagues (2022) found one sentence repeated more than 60,000 times in the C4 corpus, train–test overlap affecting over 4% of the validation sets of standard datasets, and over 1% of the unprompted output of language models trained on such data copied verbatim from the training data; deduplicated training emitted memorized text ten times less often.

Exact duplicates are found by hashing; near-duplicates by locality-sensitive hashing (for example MinHash on word shingles) or by nearest neighbors in an embedding space. Deduplicate across the split before anything else.

Contamination at web scale

Models pretrained on large web crawls may have seen benchmark test items verbatim or paraphrased, and then a benchmark score partly measures memory. When the training data are available, contamination is measured by overlap, for example long word sequences shared between test items and training documents. When they are not, only black-box tests remain, and one of the cleanest rests on the exchangeability of the previous lessons.

DerivationA permutation test for contamination (after Oren, Meister, Chatterji, Ladhak & Hashimoto)
  1. H0: (L(id), L(π1),…,L(πm)) is exchangeable, for independent uniform permutations π1,…,πmH_0:\ \big(L(\mathrm{id}),\,L(\pi_1),\dots,L(\pi_m)\big)\ \text{is exchangeable, for independent uniform permutations }\pi_1,\dots,\pi_m

    Let x1,…,xkx_1,\dots,x_k be a benchmark's examples in their published order, and let L(π)=log⁡pθ(xπ(1),…,xπ(k))L(\pi)=\log p_\theta\big(x_{\pi(1)},\dots,x_{\pi(k)}\big) be the model's log-likelihood of the examples concatenated in order π\pi. If the model never saw the benchmark and its examples are exchangeable, the published order is just one more arbitrary order:

  2. p=1+#{j: L(πj)≥L(id)}m+1,PH0(p≤α)≤αp=\frac{1+\#\{j:\ L(\pi_j)\ge L(\mathrm{id})\}}{m+1},\qquad P_{H_0}(p\le\alpha)\le\alpha

    Then the rank of L(id)L(\mathrm{id}) among the m+1m+1 values is uniform (ties only help), so this p-value is valid at every level:

  3. A model trained on the benchmark in its published order tends to find that order far more likely than any shuffle, which drives pp toward its minimum 1/(m+1)1/(m+1). The guarantee runs one way: a small p-value is evidence of contamination, but a large one does not prove its absence, since the model may have seen the items shuffled, paraphrased or translated. Oren and colleagues develop a more powerful sharded version, whose false-positive rate is controlled asymptotically, and used it to audit five popular public language models, finding little evidence of pervasive contamination.

Mitigations, as of the mid-2020s: private test sets that never leave the evaluator; benchmarks refreshed with items created after a model's training data were collected; decontamination filters that remove training documents overlapping known test sets; and reports of contamination analyses alongside scores. Reusing one test set adaptively, many submissions against the same held-out data, is a related way of overfitting a benchmark, studied in the Convergence lesson Benchmark Overfitting & Adaptive Data Analysis.

Audit questionIf the answer is no
Was the data split before any data-dependent step?refit every step inside a pipeline, within each fold
Is every feature available, in this form, at prediction time?drop it or rebuild it with point-in-time data
Does the split match deployment (new groups, the future, new sites)?split by group, by time or by site
Were duplicates removed across the split?hash exactly, then search for near-duplicates
Was the test set used only once, after every choice was made?hold out a fresh test set, or report nested cross-validation
Could the test items be in the (pre)training data?run overlap or permutation tests, or use post-cutoff data

Key takeaways

  • Leakage is information about the target, or about the test data, that will not be available when the model is used. Enforce a learn–predict separation: every feature and every fitted step must be computable, in the same form, from data available at prediction time.
  • Label-dependent steps (feature selection, target encoding, oversampling, tuning) belong inside the training folds. With 5,000 noise features and 50 samples, the best feature correlates about 0.5 with random labels. Report nested cross-validation after tuning.
  • Split by time and by group to match deployment, and deduplicate exact and near-duplicate examples across the split: 10% of CIFAR-100's test images had near-duplicates in its training set.
  • Web-scale training corpora can contain benchmark test sets. Measure overlap when the training data are available, use exchangeability-based permutation tests when they are not, and prefer private or freshly collected test data.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which preprocessing step, fitted on the full dataset before splitting, leaks the most label information into the evaluation?

  1. Standardizing every feature to mean 0 and variance 1
  2. Imputing missing values with each feature's median
  3. Replacing a high-cardinality category by the average label of its rows (target encoding)
  4. Lowercasing all text
Show the answer

C. Replacing a high-cardinality category by the average label of its rows (target encoding)

Target encoding writes the labels themselves, including the held-out ones, into a feature. For a rare category it can nearly copy an example's own label. Compute it out of fold, inside the training data only.

Question 2

A few percent of a benchmark's test images have near-duplicates in its training set. How does this affect the reported accuracy?

  1. No real effect: duplicates are a small fraction
  2. It inflates accuracy: a model can be right on those images by matching memorized near-copies, so part of the score measures memorization
  3. It lowers accuracy, because duplicates confuse the model
  4. It makes the test set harder
Show the answer

B. It inflates accuracy: a model can be right on those images by matching memorized near-copies, so part of the score measures memorization

Near-copies let a model that memorized its training set score on test items without generalizing. A few percent can matter when models differ by a point or two, which is why cleaned test sets such as ciFAIR were built.

Question 3

In the permutation test for benchmark contamination, why is a small p-value evidence that the model saw the benchmark?

  1. Shuffled benchmarks are inherently harder to predict
  2. Language models always prefer the first example of a benchmark
  3. A contaminated model must assign probability one to the published order
  4. Without contamination, the published order is exchangeable with random shuffles, so its likelihood rank is uniform; a consistently top rank is unlikely under that hypothesis
Show the answer

D. Without contamination, the published order is exchangeable with random shuffles, so its likelihood rank is uniform; a consistently top rank is unlikely under that hypothesis

The test needs only exchangeability under the null hypothesis. If the model has no memory of the published order, that order's likelihood is as likely to rank anywhere among the shuffles as any other, so a top rank happens with probability 1/(m+1)1/(m+1).

Question 4

A churn model uses "number of support calls in the customer's final month," computed from complete account histories. It excels in validation and performs poorly when scoring live customers mid-month. What happened?

  1. Temporal leakage: the feature uses information from after the moment of prediction
  2. Overfitting caused by too many parameters
  3. The customers' behavior shifted after deployment
  4. The validation set was too small
Show the answer

A. Temporal leakage: the feature uses information from after the moment of prediction

"Final month" is only known once the customer has left, and calls in that month are partly a symptom of leaving. Live customers have no final month yet. Rebuild the feature from data available at each prediction time.

Further reading

  • S. Kaufman, S. Rosset, C. Perlich & O. Stitelman, "Leakage in data mining: formulation, detection, and avoidance," ACM Transactions on Knowledge Discovery from Data 6(4), 1–21 (2012).
  • S. Kapoor & A. Narayanan, "Leakage and the reproducibility crisis in machine-learning-based science," Patterns 4(9), 100804 (2023).
  • C. Ambroise & G. J. McLachlan, "Selection bias in gene extraction on the basis of microarray gene-expression data," Proceedings of the National Academy of Sciences 99(10), 6562–6566 (2002).
  • B. Barz & J. Denzler, "Do we train on test data? Purging CIFAR of near-duplicates," Journal of Imaging 6(6), 41 (2020).
  • Y. Oren, N. Meister, N. Chatterji, F. Ladhak & T. B. Hashimoto, "Proving test set contamination in black box language models," arXiv:2310.17623 (2023).