Sub topic 3
Splitting Data and Avoiding Leakage
This chapter assumes you know supervised learning basics, can use scikit-learn, and have met the idea of a metric. A baseline score only means something if the data behind it is split honestly. Leakage breaks that, and it makes both your baseline and your candidate model look better than they are.
What each split is for
Most projects use three subsets:
- Training set: the model fits its parameters here.
- Validation set: you compare models, tune settings, and pick a baseline here.
- Test set: you score the final choice once, at the end.
The test set only works if no decision was made by looking at it. Each time you adjust something because of a test score, the test set becomes a second validation set. Its score is then optimistic.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
X_train, X_temp, y_train, y_temp = train_test_split(
X, y, test_size=0.4, stratify=y, random_state=0
)
X_val, X_test, y_val, y_test = train_test_split(
X_temp, y_temp, test_size=0.5, stratify=y_temp, random_state=0
)
for name, labels in [("train", y_train), ("val", y_val), ("test", y_test)]:
print(name, len(labels), round(labels.mean(), 3))The code uses stratify so each subset keeps the same share of the rare class. It also fixes random_state, so every model you compare sees the same rows.
What leakage is
Leakage means information that would not exist at prediction time reaches the model during training or evaluation. The model then scores well on your split and poorly in production.
| Source | Example | Fix |
|---|---|---|
| Preprocessing on all data | Scaling or feature selection fitted before splitting | Fit inside a pipeline, on training folds only |
| Duplicate or related rows | Same customer in train and test | Split by group, not by row |
| Future information | Random split of a time series | Split by time |
| Target proxies | A column recorded after the outcome, such as "refund issued" | Remove features unavailable at prediction time |
Preprocessing leakage
This is the most common error. The example below uses features that are pure noise, so no honest model can beat 0.5 accuracy.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))
y = rng.integers(0, 2, size=100)
# Leaky: features are chosen using all labels, including the held-out folds.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5)
# Clean: selection is refitted on each training fold only.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
clean = cross_val_score(pipe, X, y, cv=5)
print("leaky accuracy:", leaky.mean())
print("clean accuracy:", clean.mean())The leaky score lands well above 0.5 on data that contains no signal. The clean score stays near 0.5. The pipeline is the fix, because it refits every step on the training portion of each fold.
Group and time leakage
Random row splits assume rows are independent. When they are not, related rows land on both sides of the split. The model memorizes them, and the score measures memory instead of generalization. Use GroupShuffleSplit or GroupKFold with a group column such as customer ID. For forecasting, train on earlier rows and evaluate on later ones, as production would.
Keep the baseline on the same footing
Fit baselines on the training set and score them on the same validation set as your candidate. If the baseline sees a different split, or preprocessing that the candidate does not, the comparison measures the split and not the models.
Exercise
A teammate standardizes all 5,000 rows with StandardScaler, then runs 5-fold cross-validation on the scaled data. Is this leakage, and how do you fix it?
Show answer
Yes, mildly. The mean and standard deviation were computed using the rows that later serve as held-out folds, so those folds influenced the transformation. Put the scaler and the model in one pipeline with makepipeline and pass the pipeline to crossval_score. The scaler is then refitted on each training fold only.