Sub topic 7
How Information Leaks from Test Data into Training
This chapter assumes you can run the earlier steps: you have loaded the California housing data and split it with train_test_split. It also assumes you know what a feature and a target are.
What leakage is
Data leakage happens when information from outside the training data influences how a model is built. The model then looks better during evaluation than it will on truly new houses. Leakage does not raise an error. It only makes your score untrustworthy.
The test set exists to imitate future data. If any step uses test rows to make a decision, the test set no longer imitates the future.
Common ways it happens
- Fitting a preprocessing step on all the data. A scaler computes a mean and a standard deviation. If you compute them on the full dataset, the test rows have shaped the training features.
- Tuning on the test set. If you try several models and keep the one with the best test score, you have picked the model that happens to fit those test rows.
- Leaking through the target. A feature that is computed from the target, or only known after the target, gives the model the answer.
- Cross-validation with a shared scaler. If you scale before cross-validation, each validation fold has already influenced the scaling used on its training folds.
A leaky version
This code scales the full dataset before splitting.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
# Leaky: the scaler sees every row, including future test rows
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42
)The scaler learned its mean and spread from all 20,640 rows. For plain scaling the numerical effect is small, but the habit is wrong. With steps that learn more from the data, such as feature selection or imputation, the effect can be large.
The safe order
Split first. Then fit every learned step on the training data only. Apply the fitted step to the test data without refitting it.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
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) # learns from training rows only
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test) # reuses training mean and spread
print(X_train_s.mean(axis=0).round(2))
print(X_test_s.mean(axis=0).round(2))The training means print as 0.0. The test means are close to zero but not exactly zero. That small difference is correct, because the test rows were not used to center the data.
Leakage inside cross-validation
Cross-validation splits the training set again, into folds. Every fold plays the validation role once. If you scale the whole training set first and then call cross_val_score, each validation fold has influenced the scaler. The fix is a pipeline, which the next chapter builds. A pipeline refits the scaler inside each fold on that fold's training part only.
A quick check
Ask one question about each step: "Does this step learn anything from the data?" If yes, it must be fitted after the split and only on training rows. Scalers, imputers, encoders, feature selectors and the models themselves all learn.
Exercise
You compute the median of each column on the whole dataset to fill missing values, then split into train and test. Why is this leakage, and how do you fix it?
Show answer
The medians were computed using test rows, so test data influenced the training features. Split first, fit the imputer (for example SimpleImputer) on the training rows only, and use transform on both the training and test rows. Putting the imputer in a pipeline does this automatically during cross-validation.