Learning path: Explore a Dataset Before You Model · Step 6 of 6
Train-Test Split and Data Leakage: Split First, Learn After
Why the train-test split comes before everything else: an 80/20 split with stratify and random_state, a scaler that leaks test rows, and a column that secretly holds the answer. Shown on Rain in Australia.
What you will learn
- Split data 80/20 with train_test_split, using stratify and random_state
- Explain how fitting a scaler on all rows leaks the test data
- Apply the fit-on-train, transform-both rule to every preprocessing step
- Find a column that already holds the answer
Before you start
- Reading a CSV with pandas
- First Look at a Dataset
Imagine a teacher shows the students the exam paper while they revise. They learn the answers by heart and everyone scores 100%. A perfect score, and it means nothing.
Now the honest way: students revise from practice papers, then sit a new exam with questions they've never seen. The practice papers are your train rows. The exam is your test rows, and it has to be new to the model. If test rows leak into anything the model learns, the test score lies.
That gives the most important rule of the whole course: split first, and only then learn anything from the data. Let's see why, on Rain in Australia (will it rain tomorrow?).
Set up X and y
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv("weatherAUS.csv")
drop_cols = ["Date", "RISK_MM", "RainTomorrow"]
X = df.drop(columns=drop_cols)
y = df["RainTomorrow"]
print(X.shape, y.shape)
(142193, 21) (142193,)
X is every column we can use as input. We leave out the date, the answer (RainTomorrow) and a column called RISK_MM. You'll see why RISK_MM has to go at the end. Three columns out of 24, so 21 inputs remain.
Split first
train_test_split shuffles the rows at random and cuts them in two. test_size=0.2 makes it 80/20.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
(113754, 21) (28439, 21)
113,754 rows to train on, 28,439 locked away for the final exam. One cut, made once, before anything else touches the data.
stratify keeps the share of rainy days
Only some days are rainy. A small function measures the share:
def rain_share(s):
return round((s == "Yes").mean(), 4)
print("all rows ", rain_share(y))
print("plain test", rain_share(y_test))
all rows 0.2242
plain test 0.223
22.42% of all days are followed by rain. The plain split gave the test set 22.3%. Close, but not the same, and on a smaller dataset the gap can be much bigger.
Add stratify=y and the split cuts each class on its own: 80/20 of the dry days and 80/20 of the rainy days.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print("train", rain_share(y_train))
print("test ", rain_share(y_test))
train 0.2242
test 0.2242
Both parts now have exactly 22.42% rainy days. For classification, always stratify.
random_state makes it repeatable
This function returns the first three row numbers of the test set. We call it twice without a seed and twice with 42:
def first_rows(seed=None):
split = train_test_split(
X, y, test_size=0.2, random_state=seed)
return split[1].index[:3].tolist()
print(first_rows(), first_rows())
print(first_rows(42), first_rows(42))
[88765, 16169, 78411] [72154, 135649, 52660]
[56320, 124136, 117063] [56320, 124136, 117063]
Without a seed, every run picks different rows. With random_state=42, it's the same rows every time. That way two models can be compared on exactly the same test rows. In this course it's 42 everywhere.
Leakage: a scaler that sees the test rows
A StandardScaler learns the mean and spread of each column. Let's fit two: one on all rows, one on the train rows only.
num = X.select_dtypes(include="number").columns
leaky = StandardScaler().fit(X[num])
clean = StandardScaler().fit(X_train[num])
print(round(leaky.mean_[0], 3))
print(round(clean.mean_[0], 3))
12.186
12.173
Same first column (MinTemp), two different means. The test rows leaked into the first one. With over a hundred thousand rows the difference is tiny, but the habit is what matters: on small data it can be large.
The rule: fit on train, transform both
fit(), or a column already holds the answer, the test score is no longer honest.So any step that learns from the data learns from the train rows only:
- Fit on
X_train, and onlyX_train. - Transform the train rows with what it learned.
- Transform the test rows with the same mean and the same scale.
The test rows are only transformed, never fitted. This holds for every imputer, encoder, scaler and feature selector, and for the outlier fences from Finding Outliers.
The sneakiest leak: a column that knows the answer
Remember RISK_MM? Check it against the answer: its smallest value on rainy days and its largest on dry days.
rain = df.loc[y == "Yes", "RISK_MM"].min()
dry = df.loc[y == "No", "RISK_MM"].max()
print("rain days, smallest RISK_MM:", rain)
print("dry days, largest RISK_MM:", dry)
rain days, smallest RISK_MM: 1.1
dry days, largest RISK_MM: 1.0
Rainy days start at 1.1 and dry days stop at 1.0. RISK_MM is the amount of rain that falls tomorrow, something you'd never know at prediction time. Give a decision tree only this one column:
leak = df[["RISK_MM"]]
leak_train = leak.loc[X_train.index]
leak_test = leak.loc[X_test.index]
tree = DecisionTreeClassifier(random_state=42)
tree.fit(leak_train, y_train)
print(round(tree.score(leak_test, y_test), 3))
1.0
One cut, between 1.0 and 1.1, splits the days perfectly, and the test score is 1.0. Perfect, and too good to be true, because the column already holds the answer. That's why we dropped it from X at the start.
If a score looks too good, hunt for a leak. Ask of every column: would I really know this value at the moment I make the prediction?
Common mistakes
- Exploring or cleaning before the split. Every choice you make while looking is learned from what you see. (We said this in First Look at a Dataset too.)
- Calling
fitorfit_transformon the test rows. Test rows only gettransform. - Forgetting
stratifyon an imbalanced label. - No
random_state, so two models get tested on different rows. - Keeping a column from the future, like
RISK_MM.
Quick recap
| Rule | Code | Rain in Australia |
|---|---|---|
| Split first, 80/20 | test_size=0.2 | 113,754 train, 28,439 test |
| Keep class shares | stratify=y | 22.42% rain in both parts |
| Same split every run | random_state=42 | Same test rows each call |
| Fit on train only | StandardScaler().fit(X_train[num]) | Mean 12.173, not 12.186 |
| No future columns | drop RISK_MM | A tree on it alone scores 1.0 |
Try it yourself
Fit a StandardScaler on X_train[num] only, then transform the test rows. Print the first test row.
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)