TGViewer
Data science/ML/AI Data science/ML/AI @datascience_bds · 14.1K subscribers
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.
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
More from @datascience_bds
  1. Oct 12, 2026Roadmap to Learn SQL
  2. Oct 11, 2026🧮 Why does NumPy let you add a number to an entire matrix? Look at this: import numpy as…
  3. Oct 10, 2026document post
  4. Oct 9, 20268 RAG architectures for AI Engineers, visually explained:
  5. Oct 8, 2026document post
  6. Oct 7, 2026🧮 NumPy: Why axis=0 and axis=1 Feel Backwards You've probably seen: np.mean(X, axis=0) an…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →