Sub topic 6
Avoiding Data Leakage with Pipelines
This chapter assumes you can run cross_val_score and read its output, and that you know scikit-learn's fit, transform, and predict methods. It also assumes you are comfortable with NumPy arrays and basic pandas.
What data leakage is
Data leakage happens when information from outside the training data influences the model during training. In cross-validation, the information that leaks is usually the test fold. The score then measures how well the model remembers the test fold, not how well it generalizes.
Leakage is easy to introduce because it needs no bug in the usual sense. The code runs and the score looks good. The score is simply too optimistic.
The most common cause is preprocessing before splitting. Any step that learns something from data is part of the model. Examples are the mean in a scaler, the medians in an imputer, the components in PCA, and the features picked by a selector. If such a step is fitted on all rows before cross-validation, every test fold has already contributed to it.
Why it matters: a leak you can measure
Scaling leaks only a little, so the effect is often tiny. Supervised feature selection leaks a lot, because it uses the labels. The next example uses data with no signal at all: 2000 random features and random labels. An honest estimate of accuracy is 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 StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 2000))
y = np.array([0, 1] * 30)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Leaky: the 20 "best" features are chosen using all 60 rows and labels.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=cv)
# Correct: selection is refit on the training part of each fold.
pipe = make_pipeline(
SelectKBest(f_classif, k=20),
LogisticRegression(max_iter=1000),
)
honest = cross_val_score(pipe, X, y, cv=cv)
print(f"leaky : {leaky.mean():.3f}")
print(f"honest: {honest.mean():.3f}")Run it and compare the two lines. The leaky score is typically far above 0.5, often above 0.9, even though the labels are random. The honest score stays near 0.5. With 2000 features, some correlate with the labels by chance. The leaky version picks them using the test rows too, so those rows are effectively part of training.
How a pipeline prevents it
A Pipeline chains transformers and a final estimator into one object with fit and predict. When cross_val_score receives a pipeline, it clones it and does the following for each fold:
- Call
fit_transformon the training rows for each transformer in turn. - Fit the final estimator on the transformed training rows.
- Call
transform(notfit) on the test rows with the already-fitted transformers. - Predict and score on the transformed test rows.
The pipeline version is equivalent to this manual loop:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = []
for train_idx, test_idx in cv.split(X, y):
scaler = StandardScaler().fit(X[train_idx]) # statistics from training rows only
X_train = scaler.transform(X[train_idx])
X_test = scaler.transform(X[test_idx]) # test rows are only transformed
clf = LogisticRegression(max_iter=1000).fit(X_train, y[train_idx])
scores.append(clf.score(X_test, y[test_idx]))
print(np.round(scores, 3), round(float(np.mean(scores)), 3))Writing this loop once is a good way to see what the pipeline does for you. In real work, prefer the pipeline. It is shorter, and it is much harder to get wrong when you add steps or a hyperparameter search.
What counts as "learning from data"
Not every transformation needs to live in the pipeline. The rule is whether the step estimates anything from the data it sees.
| Step | Learns from data? | Must be inside the pipeline? |
|---|---|---|
| `StandardScaler`, `MinMaxScaler` | Yes (mean, scale, min, max) | Yes |
| `SimpleImputer` | Yes (median, mode) | Yes |
| `SelectKBest`, `VarianceThreshold` | Yes (scores, variances) | Yes |
| `PCA`, `TfidfVectorizer` | Yes (components, vocabulary, IDF) | Yes |
| Target or mean encoding | Yes (uses labels) | Yes |
| Oversampling such as SMOTE | Yes (creates samples from neighbors) | Yes, and only on training rows |
| `np.log1p` on a column | No (row by row) | Not required |
| Fixed unit conversion | No | Not required |
Oversampling needs special care. If you oversample before splitting, copies or near-copies of one sample land in both training and test folds. The test score then rewards memorizing. The imbalanced-learn package provides its own Pipeline class that applies samplers only while fitting, and skips them at prediction and scoring time. The scikit-learn Pipeline does not support steps that change the number of rows.
Mixed column types with ColumnTransformer
Real tables have numeric and categorical columns that need different handling. ColumnTransformer applies a different transformer to each column group. You then place it as one step in the pipeline, so everything inside it is also refit per fold.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 200
df = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.lognormal(mean=10, sigma=0.5, size=n),
"city": rng.choice(["a", "b", "c"], size=n),
})
y = ((df["age"] + rng.normal(0, 15, n)) > 50).astype(int)
df.loc[rng.choice(n, 20, replace=False), "age"] = np.nan # missing values
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, df, y, cv=cv)
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")The imputer's medians, the scaler's statistics, and the encoder's category list are all learned from the training rows of each fold. handle_unknown="ignore" matters here. A category that appears only in a test fold would otherwise raise an error. Seeing that error is a sign the encoder is correctly fitted on training rows only.
Other routes for leakage
A pipeline protects against fitted-preprocessing leaks. It does not protect against everything.
- Duplicates and near-duplicates. If the same record appears twice, one copy can land in training and one in testing. Deduplicate before splitting.
- Related samples. Several rows from one patient, user, or device are not independent. The grouped-splitting chapter covers this.
- Time. Training on the future to predict the past inflates scores. The time-series chapter covers this.
- Target-derived features. A column such as "treatment outcome code" that is only known after the label exists carries the answer. No pipeline can detect this. It requires thinking about when each feature becomes available.
- Repeated peeking. If you look at cross-validation scores and then change preprocessing or features many times, the folds slowly leak into your decisions. Hyperparameter tuning has the same problem, which nested cross-validation addresses later.
Practical checks
- Pass the raw feature matrix and the pipeline to
cross_val_score. If you pass a transformed array, you are probably leaking. - Name steps clearly and address their parameters with the double-underscore syntax, such as
selectkbest__korlogisticregression__C. - Use
cross_validate(..., return_estimator=True)to inspect each fold's fitted pipeline. For example, check that the selected features differ between folds. - Run a sanity check with shuffled labels, as in the first example. A trustworthy procedure scores near chance on random labels. A score well above chance points to a leak.
- After cross-validation, fit the pipeline once on all training data for the final model. Cross-validation estimates performance. It does not produce the model you deploy.
Exercise
A colleague standardizes all features with StandardScaler().fit_transform(X), then runs 5-fold cross-validation on the scaled array and reports the score. Explain precisely what leaks, how to fix the code, and why the reported score is likely higher than the true generalization performance.
Show answer
The scaler's mean and standard deviation are computed from all rows, including the rows that later form each test fold. Each test fold therefore influenced the transformation applied to the training data, and test rows are scaled using statistics that include themselves. Fix it by putting the scaler and the model in one pipeline, for example make_pipeline(StandardScaler(), LogisticRegression()), and passing raw X to cross_val_score. The scaler is then refit on the training rows of each fold and only applied to the test rows. For plain scaling the inflation is usually small. It is larger for steps that use labels, such as supervised feature selection or target encoding.