Data leakage and pipelines
Last updated
Leakage is when information from the test data, or from the future, sneaks into training. The model then looks better in testing than it will ever be in real use, and nothing crashes to warn you. This lesson shows three ways it happens (through scaling, through choosing features, and through time) and the tool that prevents the first two: scikit-learn’s Pipeline, which makes every step learn from training data only.
By the end of this lesson you can
- Explain what data leakage is and why it inflates scores
- Spot leakage through preprocessing, feature selection and time
- Build a scikit-learn Pipeline and cross-validate and tune it as one model
What leakage is
A test score is honest only if the test data played no part in building the model. Data leakage is any way it, or anything the model won't have in real use, gets in anyway. The model then learns from information it won't have later, and the score is too good.
Some leaks are obvious once seen: a feature that's really the answer in disguise, like "days in hospital" when predicting whether a patient will be admitted. The quiet ones happen in the steps before the model: scaling, filling gaps, choosing features. Each of those steps also learns something from data (a mean, a spread, which columns matter), and if it learns from the test rows, the test rows have leaked in.
The pink arrow is the leak: the scaler’s means and spreads were worked out with the test rows in them, so the test rows helped shape the model before it was tested.
Leakage through scaling
Lesson 2.5 scaled the penguins with the training set's means and spreads only. Here's the difference it makes to the numbers the scaler learns:
Fitted on everything, the scaler's mean body mass is 4,201.8 g; on the training rows only, 4,214.6 g. A small difference, and with -NN on penguins it barely changes the score. But it's still the test rows shaping the model, and with other steps (filling missing values with a mean, or choosing features) and smaller data, the same mistake can matter a lot. The rule has no exceptions: anything that learns from data learns from the training rows only. The scaler is fitted on training data, then applied, unchanged, to test data.
Wrong way: choosing features before splitting
Here's leakage at its worst. 100 examples with 5,000 features of pure random noise, and labels from a coin toss. There's nothing to learn: any honest score should be about 0.5.
The leaky way: first pick the 20 features that best match the labels, using all 100 examples, then cross-validate:
0.81, from coin tosses. Out of 5,000 noise columns, some match the labels well by chance, and choosing them used every label, including those of the examples later used for validation. The chosen features "predict" those labels because they were chosen to.
The honest way puts the choosing inside a pipeline, so each fold picks its 20 features from its own training part only:
0.46: no better than guessing, which is the truth. The difference between 0.81 and 0.46 is entirely leakage. This exact mistake has been found in published research on gene data, where thousands of features and few patients are the norm.
Leakage through time
When data has an order in time, a random split lets the model train on the future and be tested on the past. Here's a shop's daily sales for a year, with a model that predicts a day's sales from its date (-NN with : average the three nearest days):
With shuffled folds, the error is 4.5 a day: every test day has training days on both sides of it, so "predicting" it is filling a gap. With TimeSeriesSplit, each fold trains on earlier days and tests on the days after them, as you'd have to in real life. The error is 23.2, about five times worse, and that's the honest number for forecasting.
Any time the question is about the future (sales, prices, weather, whether a customer will leave), split by time, and check that no feature carries information from after the moment of prediction.
scikit-learn’s Pipeline
A pipeline chains steps into one model. make_pipeline(StandardScaler(), KNeighborsClassifier()) behaves like a single classifier: fit fits the scaler on the data it's given, scales that data, and fits -NN to the result; predict scales new data with the already fitted scaler, then predicts.
Because the pipeline is one model, cross_val_score refits the whole thing in each fold, so the scaler only ever sees that fold's training part. Leakage through preprocessing becomes impossible to commit by accident. The penguins score 0.991 averaged over the five folds.
GridSearchCV can tune any step inside: name the step, two underscores, then the setting, as in kneighborsclassifier__n_neighbors. make_pipeline names each step after its class, in lower case.
From now on in this course, whenever a model needs preprocessing, it goes in a pipeline.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- scikit-learn: Common pitfalls and recommended practices: data leakage during preprocessing and feature selection, and how pipelines prevent it
- scikit-learn: Pipelines and composite estimators: Pipeline, make_pipeline and the step__parameter names
- Kaufman, Rosset, Perlich and Stitelman, Leakage in data mining: formulation, detection, and avoidance, ACM TKDD 6(4), 2012: a careful study of leakage, with real competition examples
- scikit-learn: TimeSeriesSplit: cross-validation that keeps time in order