Sub topic 1
What Data Leakage Is and Why It Inflates Scores
Prerequisites
This chapter assumes you know features, labels, training and test sets, and the scikit-learn fit, transform, and predict pattern.
Leakage and Inflated Scores
Data leakage happens when information unavailable at prediction time influences model training or evaluation. The model then receives an unfair advantage. Its score looks strong, but production performance falls because the leaked information will not exist there.
A held-out score is useful only when the held-out data stays unknown during model building.
Splitting Data: Train, Validation, and Test
Use separate roles for separate decisions:
| Split | Purpose | Used to fit the model? |
|---|---|---|
| Training | Learn parameters | Yes |
| Validation | Choose models or settings | No |
| Test | Estimate final performance | No |
A common workflow uses training data for fitting, validation data for decisions, and test data once at the end. Cross-validation can replace a separate validation split, but the test set must remain untouched.
Target Leakage: Unavailable Features
Target leakage occurs when a feature contains the label, or information created after the event being predicted. For example, predicting whether a loan will default using a later “collections status” field gives the model information that would not exist when the loan is approved.
For every feature, ask: “Would this value be known at the exact prediction time?” Remove features whose answer is no. Also check whether a feature is a renamed, delayed, or indirectly computed version of the target.
Preprocessing Leakage: Learning from All Rows
Preprocessing leakage occurs when a transformation learns statistics from validation or test rows. Scaling is a common example. Fit the scaler on training rows, then apply that fitted scaler to other splits.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
scaler = StandardScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)Exercise
You calculate a feature's mean using the full dataset before splitting. Is this leakage?
Show answer
Yes. The mean includes held-out rows. Calculate it from the training rows only, then apply it to the other splits.