Sub topic 3
Why preprocessing outside a pipeline leaks information
This chapter assumes you can fit a scikit-learn model with fit and predict and split data with train_test_split. It also assumes you know the fit/transform pattern from the previous chapters. The goal is to explain what data leakage is, show how it enters a workflow that looks harmless, and show why a Pipeline closes the gap.
What data leakage means
Data leakage happens when information from data you will not have at prediction time influences how a model is built. The model then looks better during evaluation than it will be in use.
In preprocessing, leakage has a specific form. Many steps learn something from data in fit:
StandardScalerlearns a mean and a standard deviation per column.SimpleImputerlearns a median or most frequent value.OneHotEncoderlearns the set of categories.SelectKBestlearns which columns correlate with the target.PCAlearns directions of variance.
If you call fit on rows that later end up in a validation or test set, those rows have shaped the preprocessing. Your evaluation data is no longer fully unseen.
A gentle example: scaling before splitting
The most common version is to scale the whole dataset and then split it. The code below skips the model and shows only what the scaler learns. The test rows are deliberately larger than the training rows, as can happen with time-ordered data.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X = np.concatenate([np.arange(15.0), np.arange(100.0, 105.0)]).reshape(-1, 1)
y = np.array([0] * 15 + [1] * 5)
X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=False, test_size=5)
leaky_scaler = StandardScaler().fit(X) # sees the test rows
honest_scaler = StandardScaler().fit(X_train) # sees only training rows
print("mean used when leaking:", leaky_scaler.mean_[0])
print("mean learned from train:", honest_scaler.mean_[0])The leaky scaler's mean is pulled upward by the test rows. Your training features are shifted using knowledge of what the test set looks like. A scaler is a mild case, because a mean and a standard deviation carry little information. The effect on a final score is usually small. Small does not mean absent, and the same habit scales up to steps that learn much more.
A severe example: feature selection on random data
Supervised steps such as SelectKBest use the labels. If they see the labels of validation rows, the damage can be large. The following experiment uses features that are pure noise and labels that are random, so no model can honestly score above about 0.5.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))
y = rng.integers(0, 2, size=100)
# Leaky: select the 20 "best" columns using all 100 rows, then cross-validate.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5).mean()
# Honest: selection happens inside each training fold only.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(f"leaky accuracy: {leaky:.2f}")
print(f"pipeline accuracy: {honest:.2f}")The leaky number comes out well above chance, typically around 0.8 or higher. The pipeline number stays near 0.5, which is the truth for random data. With 2000 noise columns, a few correlate with the labels by luck. Selecting them using all rows hands the model those lucky columns, and cross-validation cannot tell. The accuracy it reports reflects the selection step having seen every label.
This pattern is the standard way people publish results that later fail to reproduce. The tell is a high score on data where you have few rows and many columns.
How leakage gets through cross-validation
Cross-validation exists to estimate performance on unseen data. It splits the rows into folds, trains on some, and scores on the held-out fold. That protection holds only if everything that learns from data is repeated inside each fold.
When you preprocess first and cross-validate afterward, the folds are cut from data that is already transformed. The held-out fold's rows have influenced the transformation applied to the training rows. The split is real, but it comes too late.
The diagram contrasts the two orders of operations.
The fix: fit on training data, transform everything else
The rule has two parts:
- Call
fit(orfit_transform) only on training data. - Call
transformon validation and test data using what the training data taught the step.
You can follow this rule by hand. For a single train/test split, it looks like this:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # learn from train only
X_test_scaled = scaler.transform(X_test) # reuse train statistics
clf = LogisticRegression(max_iter=1000).fit(X_train_scaled, y_train)
print(clf.score(X_test_scaled, y_test))This is correct, and the test set remains clean. The trouble starts when you add cross-validation or hyperparameter search. You would have to write a loop that, for every fold, builds a new scaler, fits it on that fold's training rows, transforms both parts, fits a model, and scores. Every extra step multiplies the bookkeeping, and any slip reintroduces leakage without raising an error.
What a Pipeline does about it
A Pipeline is an estimator that wraps the steps and the final model. It follows the rule for you. When you call fit on it, each transformer is fit on the training data passed in and then used to transform it, and the final estimator is fit on the result. When you call predict or score, each transformer only calls transform.
Because the pipeline is a single estimator, cross_val_score clones it for every fold, fits the clone on the training part, and scores it on the held-out part. Each fold gets a fresh scaler built from that fold's training rows. The next chapter builds pipelines in detail. This is the same idea applied to the earlier scaling example:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
print(cross_val_score(pipe, X, y, cv=5).mean())Here the full X is passed in, and that is safe. The pipeline splits it, and the scaler never sees a validation row during fit.
Common sources of leakage
Scaling and feature selection are the well-known cases. The same mistake appears in other forms, so look for any step that learns from data.
| Leak source | What it learns | Why it leaks if done before splitting |
|---|---|---|
| `StandardScaler`, `MinMaxScaler` | Means, ranges | Validation rows shift the training scale |
| `SimpleImputer` | Median or most frequent value | Fill values include validation information |
| `OneHotEncoder` | Category list | Test-only categories become visible during fitting |
| `SelectKBest`, model-based selection | Column relevance to labels | Validation labels choose the columns |
| `PCA` | Variance directions | Validation rows shape the components |
| Target encoding | Mean of target per category | Validation labels enter the training features |
| Oversampling such as SMOTE | Synthetic rows from neighbors | Copies of validation rows appear in training |
Some leakage is not about transformers at all. Duplicate rows that land in both train and test, features computed from the label, and time-series data split at random rather than by time all give optimistic scores. A pipeline cannot fix those. They require you to think about how the data was collected.
Leakage from tuning choices
A related error is judging a model on the same data used to choose its settings. If you try 50 values of a hyperparameter and report the best cross-validation score, that number is slightly optimistic, because you picked the maximum of 50 noisy estimates. This is selection bias rather than preprocessing leakage, but it has the same effect: a score better than you will see later.
Two habits keep this in check:
- Keep a test set that is touched once, after all choices are made.
- Put every data-dependent choice, including thresholds, selected features, and imputation, inside the object you cross-validate.
A checklist for your own code
Before trusting an evaluation score, ask these questions:
- Does any
fitcall happen on data that includes validation or test rows? - Does any step use the labels? If so, is it inside the pipeline?
- Was the split made before any computation that looks across rows?
- Does the score look too good for the amount of data? Very high accuracy with many columns and few rows is a warning sign.
- Can duplicates or near duplicates appear on both sides of the split?
A quick sanity test is to shuffle the labels and run the whole evaluation again. A leak-free workflow should score near chance. If your score stays high on shuffled labels, something is feeding label information into the folds.
Summary of the working model
- Steps that learn in
fitmust see only training data. - Splitting after preprocessing makes cross-validation optimistic, mildly for scalers and severely for supervised selection.
- Writing the per-fold loop yourself is possible but fragile.
- A
Pipelinerepeats fit-on-train, transform-on-validation for each fold automatically, so leakage cannot enter through preprocessing. - Pipelines do not fix duplicated rows, label-derived features, or poorly designed splits.
Exercise
You run SelectKBest(k=10) on all rows of a dataset, then call crossvalscore on the 10 selected columns and get 0.95 accuracy. A colleague runs the same selection inside make_pipeline and gets 0.71. Which score do you trust as an estimate for new data, and why?
Show answer
Trust 0.71. In your version, SelectKBest used the labels of every row, including the rows later held out by cross-validation, so the chosen columns were picked with knowledge of the validation labels. In the pipeline version, selection is refit inside each training fold and never sees that fold's validation labels. The gap between the two numbers measures the leakage.
Exercise
Which of these can safely be done on the full dataset before splitting, and which must go inside a pipeline? (a) np.log1p on a column, (b) median imputation, (c) converting a column from centimeters to meters, (d) PCA with 5 components.
Show answer
(a) and (c) are safe, because they transform each value independently and learn nothing from other rows. (b) and (d) must go inside the pipeline, because the median and the principal components are computed across rows, so fitting them on validation rows leaks information.
Exercise
How could you test whether a cross-validated workflow contains leakage, using only the labels?
Show answer
Shuffle y (for example with numpy.random.default_rng(0).permutation(y)) and run the full evaluation on the shuffled labels. With no real relationship between features and labels, an honest workflow should score near chance, around 0.5 for balanced binary classes. A score well above chance indicates that label information is reaching the evaluation folds through preprocessing or another leak.