Data science and machine learning hub
Python, SQL, stats, ML, deep learning, projects, PDFs, roadmaps and AI resources.
For beginners, data scientists and ML engineers
๐ https://rebrand.ly/bigdatachannels
DMCA: @disclosure_bds
Contact: @mldatascientist
Post #1162
2.34K
๐งช Data Leakage Through Preprocessing
Your model is cheatingโฆ and you donโt even see it.
๐ง Whatโs actually happening
You already know leakage from obvious features.
But the dangerous version happens during preprocessing.
Example mistake:
You scale your entire dataset before splitting.
Why is this wrong?
Because the scaler learns:
๐ mean
๐ standard deviation
โฆfrom the entire dataset, including test data.
๐ฏ Why this breaks everything
Your model now has indirect knowledge of the test set distribution.
Even though you didnโt touch labels, you leaked statistical information.
This leads to:
๐ overly optimistic accuracy
โ poor real-world performance
โ The Correct Way
Always split first:
๐ Any operation that โlearns from dataโ must only see training data.
Your model is cheatingโฆ and you donโt even see it.
๐ง Whatโs actually happening
You already know leakage from obvious features.
But the dangerous version happens during preprocessing.
Example mistake:
You scale your entire dataset before splitting.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) # โ WRONG
Why is this wrong?
Because the scaler learns:
๐ mean
๐ standard deviation
โฆfrom the entire dataset, including test data.
๐ฏ Why this breaks everything
Your model now has indirect knowledge of the test set distribution.
Even though you didnโt touch labels, you leaked statistical information.
This leads to:
๐ overly optimistic accuracy
โ poor real-world performance
โ The Correct Way
Always split first:
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)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test) # โ only transform
๐ Any operation that โlearns from dataโ must only see training data.
- โค 9

