Sub topic 11
Fitting Preprocessing on Training Data Only
This chapter assumes you can split data with train_test_split, you know what cross-validation does, and you have used scikit-learn estimators with fit and predict. It covers one rule and the tools that enforce it: any step that learns something from data must learn it from the training data only.
Why preprocessing can leak
Scaling, imputing missing values, selecting features, and encoding categories all look like data cleanup. They are not. Each one computes numbers from the data you give it:
StandardScalercomputes a mean and standard deviation per column.SimpleImputercomputes a median or most frequent value.OneHotEncoderrecords which category values exist.SelectKBestcomputes a score per feature, using the labels.
A step that learns from data is a fitted model, even though it is small. If you fit it on rows that later end up in the test set, information about those rows flows into the training features. This is data leakage. The model's test score then measures something easier than real deployment, where new rows are never available when you compute these statistics.
The rule has two halves:
- Call
fitonly on training data. - Call
transformon training data and on any other data (validation, test, new production rows), using the statistics learned in step 1.
A leaky split and a correct one
The first example scales before splitting, then splits first and scales second.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
# Leaky: statistics from the test rows influence the training features.
X_scaled_leaky = StandardScaler().fit_transform(X)
X_train_l, X_test_l, y_train_l, y_test_l = train_test_split(
X_scaled_leaky, y, test_size=0.2, random_state=42
)
# Correct: split first, learn scaling statistics from the training set only.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)
print("Mean of first feature, train:", X_train_s[:, 0].mean().round(3))
print("Mean of first feature, test: ", X_test_s[:, 0].mean().round(3))The training mean is about 0 because the scaler was fit on it. The test mean is not exactly 0, and it should not be. The test rows are measured against the training statistics, as production rows would be. In the leaky version, both parts are centered using numbers that include the test rows.
Leakage here is usually small
With plain standardization on a few hundred rows, the score difference from this particular leak is often tiny. Do not take that as permission to skip the rule. Other steps leak badly:
| Preprocessing step | What it learns | How badly it can leak |
|---|---|---|
| Standard or min-max scaling | Means, ranges | Usually mild |
| Imputation with the mean or median | Column statistics | Usually mild |
| Target encoding | Label averages per category | Severe, because it uses the labels |
| Feature selection by label correlation | Which columns predict the label | Severe, especially with many features and few rows |
| Dimensionality reduction (PCA) | Directions of variance | Mild to moderate |
Feature selection is the classic failure. With thousands of random features and a few dozen rows, selecting the "best" features on all the data produces strong cross-validated scores on pure noise. The selection step has seen the labels of the rows you later evaluate on.
Leakage inside cross-validation
The same rule applies in every fold of cross-validation, and this is where mistakes are common. If you scale X_train once and then call cross_val_score, each validation fold was already used to compute the mean and standard deviation. The fold is no longer unseen.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
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, test_size=0.2, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# Leaky: the scaler has already seen every validation fold.
X_train_scaled = StandardScaler().fit_transform(X_train)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_train_scaled, y_train, cv=cv)
# Correct: the pipeline refits the scaler on the training folds in each round.
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
honest = cross_val_score(model, X_train, y_train, cv=cv)
print("Leaky CV accuracy: ", leaky.mean())
print("Honest CV accuracy:", honest.mean())
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))A Pipeline chains steps so that fit runs each step's fit_transform on the data it receives, and predict runs transform only. When cross_val_score clones the pipeline for each fold, the scaler is refit on that fold's training rows. The validation rows pass through transform only.
Notice that no arrow leads from the validation fold into the scaler fit. That missing arrow is the whole point.
Preprocessing mixed column types
Real tables mix numeric and categorical columns, and each needs its own steps. ColumnTransformer applies different transformers to different columns, and you place it as the first step of a pipeline.
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 train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, 32, 47, 51, np.nan, 38, 29, 60, 44, 35, 52, 41],
"income": [30, 45, 80, 90, 55, 62, 33, 95, 70, 48, 85, 66],
"city": ["A", "B", "A", "C", "B", "A", "C", "B", "A", "C", "B", "A"],
"bought": [0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0],
})
X = df.drop(columns="bought")
y = df["bought"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
preprocess = ColumnTransformer([
("num", numeric, ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression()),
])
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))Two details matter here. The imputer's median comes from the training rows only, so a missing age in the test set is filled with a training statistic. handle_unknown="ignore" lets the encoder accept a city that appeared only in the test set, encoding it as all zeros, instead of raising an error. This matches what production will do with a category you have never seen.
Common errors
- Fitting on the test set "to be consistent". Calling
scaler.fit_transform(X_test)gives the test data its own statistics. The model then sees features on a different scale than it was trained on, and the score is unreliable. - Fitting on train and validation combined. Do this only once, for the final model, after you have chosen settings. During model selection, the validation data must stay outside the fit.
- Doing feature selection or target encoding outside the pipeline. These use labels, so the leak can be large. Keep them inside the pipeline.
- Preprocessing the full dataset "just to look at it". Exploring is fine. Computing statistics that you then feed into a model is not.
- Forgetting the production path. Save the fitted pipeline as one object. If you save the model and re-create the scaler separately, the two can drift apart.
Stateless steps are safe
A step that learns nothing from the data cannot leak. Taking a logarithm, converting units, or parsing dates are row-by-row operations, so they can run before the split. If you are unsure, ask whether the step's output for one row depends on other rows. If it does, put it in the pipeline.
A checklist
- Split off the test set before any data-dependent step.
- Put every fitted step (imputation, scaling, encoding, selection, dimensionality reduction) in a
Pipeline. - Pass the pipeline, not preprocessed arrays, to
cross_val_scoreor a search object. - Use the test set once, with the final fitted pipeline.
- Persist the whole pipeline for deployment.
Exercise
A colleague standardizes all 1,000 rows, runs 5-fold cross-validation on the scaled data, and reports 0.91 accuracy. They say that no test set was touched, so nothing leaked. Explain what is wrong and how you would fix the code.
Show answer
Each validation fold was included when the scaler computed its mean and standard deviation, so information from the validation rows influenced the training features in every round. The cross-validation score is therefore slightly optimistic, and the effect is larger for steps like feature selection. To fix it, put the scaler and the model in a Pipeline (for example makepipeline(StandardScaler(), LogisticRegression())) and pass the unscaled data and the pipeline to crossval_score. The scaler is then refit on the training folds of each round and only applied to the validation fold.
Exercise
In the ColumnTransformer example, why is handle_unknown="ignore" set on the OneHotEncoder, and what happens to a city in the test set that never appeared in the training set?
Show answer
The encoder learns its list of categories from the training data only. A test row with an unseen city would raise an error by default. With handle_unknown="ignore", that row's city is encoded as all zeros, so the model still predicts and contributes nothing from that column. This mirrors how unseen categories would arrive in production.