Split first: the train/test split comes before every statistic
What it is
The very first operation on a dataset is holding rows out. Only then may anything be computed from the data — a mean, a standard deviation, a category list, a quantile, a correlation used to choose features.
Why it matters
Any number computed before the split has seen the held-out rows, so the held-out score is no longer an estimate of performance on unseen data. It is the one error that makes every subsequent measurement in the project untrustworthy.
In the real world: Computing average income on all customers before splitting lets test data leak into training and makes a credit model look better than it is.
Visual example
LeakageThe mean used to transform the test rows must come from train rows only — and it is a different number.
Where the two means come from
all five rows: (10+20+30+40+20)/5 = 24 <- leaked
train rows only: (10+20+30)/3 = 20 <- correct
e0 centred: 40-24 = 16 (leaked) vs 40-20 = 20 (correct)
Why this matters
It shows leakage as a concrete numerical difference rather than a rule to obey. The test rows influenced their own transformation, which production data can never do.
Common misconception
Wrong idea: scaling is harmless preprocessing, so the order does not matter.
Correct idea: a scaler is fitted: it has learned parameters. Learning them from all the data is training on the test set, exactly as much as fitting the model on it would be.
Same data, same transformer, different parameters — because the left-hand mean was allowed to see e0 and e1.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
scaler = StandardScaler().fit(X_train) # statistics from train rows only
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test) # transform, never fit_transformX_scaled = StandardScaler().fit_transform(X) followed by a split. It looks tidier and it is the most common leak in real notebooks: the mean and standard deviation used on the test rows were computed partly from the test rows.
Practise it: A Split That Does Not Leak Across Groups