Sub topic 7
How Information Leaks from Test Data into Training
This chapter assumes you can read basic scikit-learn code (fit, predict, train_test_split) and know why a test set exists. You should also recall that the project split the California housing data 80/20 with random_state=42. Here you learn what data leakage is, the forms it takes, and how to spot it. The next chapter shows the structural fix, the pipeline.
What leakage means
Data leakage happens when information from outside the training data influences how the model is built. The most common source is information from the test set, or from a validation fold. The model then looks better in evaluation than it will on genuinely new data.
The test set is only useful if it stands in for the future. The model must know nothing about it when it is built. Any step that lets test rows influence the fitted model breaks that rule, even slightly.
Leakage is dangerous because nothing fails. The code runs and the score looks good. You find the problem only after deployment, when real performance disappoints.
Where leakage comes from
Leakage in a project like this one usually comes from one of four places.
| Source | How it leaks | Example in this project |
|---|---|---|
| Preprocessing fitted on all data | Statistics from test rows shape the transformation of training rows | Calling `StandardScaler().fit(X)` before splitting |
| Preprocessing fitted on validation folds | The same problem inside cross-validation | Scaling `X_train` once, then running `cross_val_score` |
| Repeated peeking at the test set | Your decisions adapt to the test score | Trying five models and keeping the one with the best test MAE |
| Features that encode the target | A column carries the answer or a proxy for it | A column computed from `MedHouseVal` |
The first two are mechanical and easy to introduce by accident. The third is behavioral. The fourth depends on the data, and no tool can detect it for you.
The splitting order matters
The split must come first. Anything that learns from data, such as a scaler, an imputer, a feature selector or a model, must see only training rows. Test rows may only be transformed with what the training rows taught.
Seeing the leak in the housing data
Scaling before splitting is the textbook mistake. The leak is small for the scaler on this dataset, but you can still measure it. The code below fits one scaler on all rows and one on the training rows, then compares what each learned.
import pandas as pd
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)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
leaky = StandardScaler().fit(X)
honest = StandardScaler().fit(X_train)
comparison = pd.DataFrame(
{
"mean_all_rows": leaky.mean_,
"mean_train_only": honest.mean_,
"std_all_rows": leaky.scale_,
"std_train_only": honest.scale_,
},
index=X.columns,
)
print(comparison.round(4))The two columns differ, especially in the standard deviation of features with extreme outliers such as AveRooms and AveOccup. In the leaky version, the test rows helped decide what "one standard deviation" means for every training row. The model was built on a world that included the exam questions.
For a scaler, the effect on the final score is usually tiny. Do not take that as permission. The habit matters because other steps leak far more.
A leak with a large effect
Feature selection shows how bad leakage can get. The experiment below builds a dataset where the features have no relationship to the target. It then selects the ten features that correlate best with the target. If the selection happens outside cross-validation, the model appears to learn something real.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X_noise = rng.normal(size=(100, 1000))
y_noise = rng.normal(size=100)
# Leaky: select features using every row, then cross-validate.
selector = SelectKBest(f_regression, k=10).fit(X_noise, y_noise)
X_selected = selector.transform(X_noise)
leaky_scores = cross_val_score(
LinearRegression(), X_selected, y_noise, cv=5, scoring="r2"
)
# Correct: selection happens inside each training fold.
pipe = make_pipeline(SelectKBest(f_regression, k=10), LinearRegression())
honest_scores = cross_val_score(pipe, X_noise, y_noise, cv=5, scoring="r2")
print("Leaky R2: ", leaky_scores.mean())
print("Honest R2:", honest_scores.mean())The target here is pure noise, so the true R² is zero or below. The leaky number comes out clearly above zero, because the selector saw the validation rows and picked features that happen to correlate with their targets. The honest number sits at or below zero, which is the right answer. Exact values depend on the random seed, but the gap does not.
Across 1,000 candidate features, some will correlate with any target by chance. Selecting them with all the labels in view builds the answer into the features.
Leakage inside cross-validation
Cross-validation repeats the train and validate split several times. Each fold's validation rows are meant to be unseen by that fold's model. The rule from the test set therefore applies to every fold.
This code looks harmless and is leaky:
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
X_train_scaled = StandardScaler().fit_transform(X_train)
scores = cross_val_score(
Ridge(alpha=1.0), X_train_scaled, y_train, cv=5,
scoring="neg_mean_absolute_error",
)The scaler was fitted on all of X_train. In each fold, the validation rows have already shaped the scaling of the fold's training rows. The test set is still clean, but the cross-validation score is slightly optimistic. If you later use that score to choose between models or hyperparameters, the choice is biased.
The fix is to put the scaler and the model in a single estimator. Then cross_val_score refits the scaler on each training fold only. The next chapter builds this.
Peeking at the test set
The other major leak requires no code mistake. It happens when you use the test score to make a decision.
Suppose you evaluate a Ridge model on the test set, then try gradient boosting and evaluate it too. You then change a hyperparameter and look again. Each look gives you information about the test rows. After enough rounds, you have effectively tuned the model to the test set. Its score then overstates how the model will do on new data, because the test set is no longer new to your process.
The discipline is simple:
- Make every modeling decision (model family, features, hyperparameters) using the training data and cross-validation.
- Score the test set once, at the end.
- If the test result is disappointing, accept it. If you change the model and test again, that second score is no longer a clean estimate.
Target leakage
Some features are not available at prediction time, or are derived from the target. A model trained with them can be accurate in testing and useless in practice.
The California housing columns are safe in this respect. They are census-block summaries such as median income, house age and location. But consider a variation. If you added a column called "price per room" computed from MedHouseVal, the model would reconstruct the target from it. Test scores would look excellent, and you could not use the model when the price is unknown.
Ask of every feature: would I have this value at the moment I need a prediction? If not, remove it.
Other data-specific leaks are worth checking in future projects:
- Duplicate rows that land on both sides of the split.
- Rows from the same entity, such as the same house sold twice, split across train and test.
- Time series split randomly, so the model trains on the future and predicts the past.
This dataset has no timeline and is a snapshot of census blocks, so a random split is appropriate here.
Warning signs
Leakage usually shows up as results that are too good.
- A test score far better than any reasonable model should achieve.
- A very simple model that nearly matches a complex one.
- One feature with overwhelming importance.
- A large gap between the cross-validation score and the performance on later data.
When you see these, trace the order of operations. Ask what was fitted, on which rows, and in what sequence.
Exercise
A colleague writes X_scaled = StandardScaler().fit_transform(X), then calls train_test_split(X_scaled, y) and reports test MAE. Which rows influenced the scaler, why is the evaluation not fully honest, and how would you reorder the steps?
Show answer
The scaler was fitted on every row, including those that later became the test set. The test rows therefore influenced the means and standard deviations applied to the training rows, so the test set is no longer fully unseen and the MAE is slightly optimistic. The fix is to split first, fit the scaler on X_train only, and transform X_test with that fitted scaler. Wrapping the scaler and model in a pipeline makes this automatic.
Exercise
You tried three models and a few hyperparameter values, and each time you checked the test MAE before deciding what to try next. What is wrong with reporting the final test MAE as your estimate of future performance, and what should you have used instead?
Show answer
Each check let the test score guide your choices, so the test set became part of model selection and the final score is biased toward looking better than real performance. You should have compared models and hyperparameters with cross-validation on the training data only, and looked at the test set once, after the final model was chosen.