🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Data Leakage and Saving Your Model

Data leakage is test information that sneaks into training. A leak makes the score look better than the model really is.

The whole-table mean knows the test rows

The whole-table means come from all 891 rows. The train means come from 178 rows only.

import seaborn as sns
from sklearn.model_selection import train_test_split
df = sns.load_dataset("titanic")
train, test = train_test_split(df, test_size=0.8, random_state=42)
print("Whole mean age:", round(float(df["age"].mean()), 2))
print("Train mean age:", round(float(train["age"].mean()), 2))
print("Whole mean fare:", round(float(df["fare"].mean()), 2))
print("Train mean fare:", round(float(train["fare"].mean()), 2))

Save a model, load it back

joblib.dump writes the fitted pipeline to a file. joblib.load reads it back, ready to predict.

import joblib
import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = sns.load_dataset("titanic")
numbers = ["age", "fare", "pclass"]
words = ["sex", "embarked"]
cleaner = ColumnTransformer([("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numbers), ("cat", Pipeline([("fill", SimpleImputer(strategy="constant", fill_value="missing")), ("code", OneHotEncoder(handle_unknown="ignore"))]), words)])
pipe = Pipeline([("clean", cleaner), ("model", LogisticRegression(max_iter=1000, random_state=42))])
X = df[numbers + words]
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
pipe.fit(X_train, y_train)
joblib.dump(pipe, "model.joblib")
loaded = joblib.load("model.joblib")
print([int(p) for p in loaded.predict(X_test[:3])])

A loaded model predicts the same

The predictions before saving and after loading match on every test row. Saving loses nothing.

import joblib
import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = sns.load_dataset("titanic")
numbers = ["age", "fare", "pclass"]
words = ["sex", "embarked"]
cleaner = ColumnTransformer([("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numbers), ("cat", Pipeline([("fill", SimpleImputer(strategy="constant", fill_value="missing")), ("code", OneHotEncoder(handle_unknown="ignore"))]), words)])
pipe = Pipeline([("clean", cleaner), ("model", LogisticRegression(max_iter=1000, random_state=42))])
X = df[numbers + words]
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
pipe.fit(X_train, y_train)
before = pipe.predict(X_test)
joblib.dump(pipe, "model.joblib")
loaded = joblib.load("model.joblib")
after = loaded.predict(X_test)
print("Same predictions:", bool((before == after).all()))

Example

import joblib
import numpy as np
import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = sns.load_dataset("titanic")
numbers = ["age", "fare", "pclass"]
words = ["sex", "embarked"]
X = df[numbers + words]
y = df["survived"]
# A small training set on purpose: 178 rows train, 713 rows test.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)

# THE LEAK: the filler, the scaler, and the encoder learn from ALL rows.
num_filled = SimpleImputer(strategy="median").fit_transform(X[numbers])
num_scaled = StandardScaler().fit_transform(num_filled)
word_filled = SimpleImputer(strategy="constant", fill_value="missing").fit_transform(X[words])
word_coded = OneHotEncoder(sparse_output=False, handle_unknown="ignore").fit_transform(word_filled)
X_leaky = np.hstack([num_scaled, word_coded])
Xl_train, Xl_test, yl_train, yl_test = train_test_split(X_leaky, y, test_size=0.8, random_state=42)
leaky = KNeighborsClassifier()
leaky.fit(Xl_train, yl_train)
leaky_score = accuracy_score(yl_test, leaky.predict(Xl_test))

# HONEST: the same steps learn from the training rows only.
cleaner = ColumnTransformer([("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numbers), ("cat", Pipeline([("fill", SimpleImputer(strategy="constant", fill_value="missing")), ("code", OneHotEncoder(handle_unknown="ignore"))]), words)])
honest = Pipeline([("clean", cleaner), ("model", KNeighborsClassifier())])
honest.fit(X_train, y_train)
honest_score = accuracy_score(y_test, honest.predict(X_test))

# Save the honest model, load it back, and predict with it.
joblib.dump(honest, "titanic_model.joblib")
loaded = joblib.load("titanic_model.joblib")
loaded_score = accuracy_score(y_test, loaded.predict(X_test))

print("Leaky score:", round(leaky_score, 4))
print("Honest score:", round(honest_score, 4))
print("Loaded model score:", round(loaded_score, 4))
print("Loaded predictions:", [int(p) for p in loaded.predict(X_test[:5])])

Key points

  • Data leakage: test information that sneaks into training before scoring
  • Use fit on the training rows only, then transform the test rows after that
  • A scaler fit on the whole table has seen the test rows, so its score is inflated
  • joblib: a tool that saves a fitted model to a file
  • Use joblib.dump to save a model, and use joblib.load to bring it back
  • A saved model predicts without refitting

In this example, the training set is small on purpose, with 178 rows for training and 713 rows for testing. The leaky path fits the filler, the scaler, and the encoder on all 891 rows before the split, so the test rows shape the cleaning. The honest path fits the same steps inside a pipeline, so they learn from the 178 training rows only. The leaky score is higher than the honest score. The gap is small, but a leak can still mislead, because a small gap can pick the wrong model. The honest model is then saved with joblib, loaded back, and it scores the same without refitting.

Note

A leak hides in any step that learns from data, so scaling, filling, and encoding all count.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

You fit a scaler on the whole dataset, then split into train and test. What went wrong?