Sub topic 3
Splitting Data and Avoiding Leakage
This chapter assumes you can fit and score a scikit-learn model, you know what features and labels are, and you can read accuracy and standard deviation figures. The chapter covers three things. It explains what each data split is for. It lists the ways information leaks from the evaluation data into training. It shows how to build splits so that a baseline score, and any later model score, can be trusted.
What each split is for
A score only means something if the model has not seen the rows it is scored on. Three sets enforce this.
| Split | Used for | How often you look at it |
|---|---|---|
| Train | Fitting model parameters | Constantly |
| Validation | Choosing models, features and hyperparameters | Many times |
| Test | One final, unbiased estimate | Once, at the end |
Every time you pick the better of two models using the validation score, a little information about the validation set flows into your decisions. After many rounds, the validation score is optimistic. The test set exists to catch this, so it must stay untouched until you have chosen the final candidate. If you peek at it and then change the model, it has become a second validation set.
With little data, you can drop the fixed validation set and use cross-validation on the training portion instead. The test set stays separate either way. The next chapters cover cross-validation in detail.
A basic stratified three-way split
train_test_split splits once. Call it twice to get three sets. Use stratify so each set keeps the class proportions, which matters for the imbalanced data used throughout this tutorial.
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_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=0
)
print(len(X_train), len(X_val), len(X_test))
print(y_train.mean(), y_val.mean(), y_test.mean())The sizes are 1200, 400 and 400. The positive-class rate is about 5% in each set. Without stratify, a rare class can land unevenly. A test set with only a handful of positives gives a very noisy recall.
Always fix random_state. A baseline and a candidate model must be scored on the same split, or the difference between their scores mixes model quality with split luck.
What leakage is
Leakage is any path by which information from outside the training data, usually from the evaluation rows or from the future, influences the fitted model. The result is a score that looks good during development and collapses in production. Leakage is dangerous because nothing fails. The code runs, and the number is simply too high.
flowchart TDThe diagram below shows the safe order of operations.
The rule behind the diagram: split first, then fit anything that learns from data (scalers, imputers, encoders, feature selectors, the model) on the training portion only.
Common leakage patterns
Preprocessing fitted on all the data
Fitting a StandardScaler on the full dataset lets the mean and variance of the test rows shape the training features. For a scaler the effect is usually small. For feature selection it can be huge. The example below uses features that are pure noise and random labels, so no honest model can beat 50% 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, then cross-validated.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5)
# Correct: selection happens inside each training fold.
pipe = make_pipeline(
SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)
)
honest = cross_val_score(pipe, X, y, cv=5)
print("leaky accuracy: ", leaky.mean())
print("honest accuracy:", honest.mean())The leaky score is typically far above 0.5, even though the data contains no signal. The honest score stays near 0.5. The fix is a Pipeline. During cross-validation, scikit-learn refits every pipeline step on each training fold only. Put all learned preprocessing inside the pipeline as a habit.
Duplicates and near-duplicates
If the same row, or a lightly edited copy, appears in both train and test, the model is rewarded for memorizing. Check for exact duplicates before splitting, for example with pandas.DataFrame.duplicated. For text and images, also look for near-copies such as reposts, resized images or the same document in two versions.
Grouped data
Often several rows belong to one entity: many visits per patient, many photos per camera, many orders per customer. A random row-level split puts rows from the same entity on both sides. The model then learns entity-specific quirks and looks better than it will on new entities. Split by group instead.
import numpy as np
from sklearn.model_selection import GroupShuffleSplit
rng = np.random.default_rng(0)
groups = np.repeat(np.arange(100), 5) # 100 patients, 5 rows each
X = rng.normal(size=(500, 4))
y = rng.integers(0, 2, size=500)
splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
train_idx, test_idx = next(splitter.split(X, y, groups))
overlap = set(groups[train_idx]) & set(groups[test_idx])
print("rows:", len(train_idx), len(test_idx))
print("shared patients:", overlap)The overlap is an empty set. For cross-validation use GroupKFold or StratifiedGroupKFold, passing groups= to cross_val_score. Ask one question to decide if you need this: when the model is deployed, will it see new entities or known ones? Split so that the evaluation matches the answer.
Time
If the data has a time order and you predict the future, a random split lets the model train on rows that come after the test rows. Seasonal patterns and slow drift make that look easier than reality. Split chronologically: train on the past, evaluate on the future.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(-1, 1) # rows already in time order
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
print("train", train_idx.min(), "-", train_idx.max(),
"| test", test_idx.min(), "-", test_idx.max())Each test block comes strictly after its training block, and the training window grows. The data must be sorted by time first. TimeSeriesSplit trusts the row order and does not read a date column.
Target leakage
A feature may be computed from, or recorded after, the label. Examples are a "refund issued" flag when predicting fraud, or a "discharge medication" field when predicting a diagnosis. Such features score very well offline and are unavailable at prediction time. For each feature, ask: would I know this value at the moment I need the prediction? If not, remove it. A single feature that is suspiciously predictive on its own is a warning sign.
A leakage checklist
- Split before any step that learns from data. Fit it on train only.
- Put preprocessing in a
Pipeline, especially when using cross-validation. - Remove duplicates, or make sure duplicates stay together in one split.
- Split by group when rows share an entity.
- Split by time when predicting the future.
- Audit every feature for availability at prediction time.
- Choose models on validation, and use the test set once.
- Reuse the same split for the baseline and every candidate.
Splits and baselines
The baseline is only meaningful if it is scored on the same held-out data, with the same metric, as the candidate. Settle the splitting scheme first. It should reflect how the model will be used: new rows, new entities or future dates. Then every number in the rest of this tutorial, from the majority-class floor to the final candidate, comes from the same fair setup.
Exercise
A hospital dataset has 10 visits per patient, with a label for each visit. A teammate uses train_test_split on rows with a shuffle, gets 0.94 recall, and the model later gets 0.71 on new patients. What went wrong, and how do you fix the evaluation?
Show answer
Visits from the same patient appeared in both train and test, so the model could recognize patient-specific patterns. The test then measured performance on known patients, but deployment sees new patients. Split by patient with GroupShuffleSplit (or use GroupKFold in cross-validation), so that no patient appears on both sides, and rescore the baseline and the model on that split.
Exercise
You standardize all features with StandardScaler().fit_transform(X) and then call train_test_split. Why is this a leak, and what is the minimal fix?
Show answer
The scaler's mean and standard deviation were computed using the test rows, so test information shaped the training features. Split first, fit the scaler on X_train only, and apply transform to the validation and test sets. Better, wrap the scaler and model in a Pipeline.