Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathExplore a Dataset Before You Model
  1. 1
    First Look at a Dataset: 6 Checks Before You Plot or Model
  2. 2
    Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  3. 3
    Scatter Plots and Pair Plots: See How Two Columns Relate
  4. 4
    Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  5. 5
    Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  6. 6
    Train-Test Split and Data Leakage: Split First, Learn After
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Data Preprocessing

Learning path: Explore a Dataset Before You Model · Step 6 of 6

Also in:
Prepare Data for a Machine Learning Model

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.

Chaand Sheikh

·27 November 2026Data Preprocessing

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

Split first, fit on train, transform test 1. split first All rows 142,193 Train 80% 113,754 rows Test 20% 28,439 rows Scaler mean, std 2. fit 3. transform leak: test rows inside fit()
Split first. The scaler learns only from the train rows, then transforms the train rows and the test rows with the same numbers. If test rows ever reach 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:

  1. Fit on X_train, and only X_train.
  2. Transform the train rows with what it learned.
  3. 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 fit or fit_transform on the test rows. Test rows only get transform.
  • Forgetting stratify on 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

RuleCodeRain in Australia
Split first, 80/20test_size=0.2113,754 train, 28,439 test
Keep class sharesstratify=y22.42% rain in both parts
Same split every runrandom_state=42Same test rows each call
Fit on train onlyStandardScaler().fit(X_train[num])Mean 12.173, not 12.186
No future columnsdrop RISK_MMA 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 →
← Previous
Correlation and Heatmaps: Covariance, df.corr() and What They Miss
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Related articles
Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer

Count the blanks with isnull().sum(), see why dropna() would throw away 60% of the rows, and fill the gaps with SimpleImputer: median for numbers, most frequent for text, learned from the train rows only. Shown on Rain in Australia.

Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder

Models only understand numbers. Encode T-shirt sizes with OrdinalEncoder, colours with OneHotEncoder, avoid the dummy variable trap, handle a colour the encoder never saw, tame a date with 3,436 values, and encode the answer with LabelEncoder.

Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care

Put features on the same scale so each one gets a fair say. StandardScaler and MinMaxScaler fitted on the train rows, the formula checked by hand, and a wine test where KNN jumps from 0.806 to 0.972 while a decision tree stays at 0.944.

Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object

Pack imputing, encoding, scaling and the model into one scikit-learn Pipeline with two ColumnTransformer lanes. One fit on the train rows, 21 columns in, 115 out, 0.849 test accuracy, and a raw row with a blank predicted directly.

On this page
  • Set up X and y
  • Split first
  • stratify keeps the share of rainy days
  • random_state makes it repeatable
  • Leakage: a scaler that sees the test rows
  • The rule: fit on train, transform both
  • The sneakiest leak: a column that knows the answer
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.