See leakage inflate a cross-validation score, then build a scikit-learn pipeline that prevents it: ColumnTransformer, custom transformers, safe target encoding, grouped and time-aware splits, and persisting the fitted pipeline.
Data leakage is the most common reason a model that looked excellent in cross-validation disappoints in production. It happens when information from the evaluation data reaches the training step, usually through preprocessing rather than through the model itself. This tutorial shows leakage happening on real numbers, then builds a scikit-learn pipeline that makes the correct order of operations the default: preprocessing, custom features, target encoding, hyperparameter search, group- and time-aware evaluation, and persisting the fitted result.
The examples were run on Python 3.13 with scikit-learn 1.9.1, pandas 3.1.2, numpy 2.5.5, joblib 1.6.0 and skops 0.16.0. All data is synthetic with fixed seeds, and every score shown is real output from those runs.
A cross-validation score estimates how a model performs on data it has never seen. That estimate is only valid if everything learned from data, not just the model weights, is learned from the training fold alone. Scalers learn means and standard deviations. Imputers learn medians. Feature selectors learn which columns correlate with the target. Encoders learn category frequencies or target means. If any of these is fitted on the full dataset before splitting, the validation fold has influenced the training process, and the score is biased upwards.
The bias ranges from negligible (a scaler on a large dataset) to dramatic (anything that looks at the target). Here is the dramatic case: 200 rows, 5,000 columns of pure noise and random labels. No model can do better than 50% accuracy on this data.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 5_000)) # pure noise
y = rng.integers(0, 2, size=200) # random labels: true accuracy is 50%
# Leaky: select features using all rows, then cross-validate
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_selected, y, cv=5)
# Correct: selection is refit inside every training fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=5)
print(f"leaky CV accuracy: {leaky.mean():.3f}")
print(f"honest CV accuracy: {honest.mean():.3f}")
leaky CV accuracy: 0.795
honest CV accuracy: 0.510
With 5,000 noise columns, some will correlate with the labels by chance. Selecting them on all 200 rows means the selector has already seen the validation rows' labels, so those 20 columns "predict" the validation folds too. Inside a pipeline, cross_val_score fits the selector on four folds only, and the score drops to chance, which is the truth.
The general rule follows directly: every step that calls fit belongs inside the object you cross-validate. A Pipeline is how you make that object.
The rest of the tutorial uses a synthetic churn dataset with the properties that make leakage likely in practice: several monthly snapshots per customer, a high-cardinality categorical column, missing values, a date column and an unobserved customer-specific habit that drives churn.
# data.py
import numpy as np
import pandas as pd
def make_churn(n_customers: int = 800, seed: int = 0) -> pd.DataFrame:
"""Monthly snapshots of customers; several rows per customer."""
rng = np.random.default_rng(seed)
cities = [f"city_{i:03d}" for i in range(250)]
city_effect = dict(zip(cities, rng.normal(0, 0.8, len(cities))))
rows = []
for cid in range(n_customers):
plan = rng.choice(["basic", "plus", "pro"], p=[0.5, 0.3, 0.2])
city = rng.choice(cities)
habit = rng.normal(0, 1.0) # unobserved, customer-specific
start = pd.Timestamp("2025-01-01") + pd.Timedelta(days=int(rng.integers(0, 300)))
for k in range(int(rng.integers(2, 9))):
tenure = k + 1
charges = {"basic": 20, "plus": 45, "pro": 80}[plan] + rng.normal(0, 5)
calls = rng.poisson(1.0 + max(habit, 0))
logit = (-1.0 + 0.6 * calls - 0.08 * tenure + city_effect[city]
+ 1.2 * habit + (0.5 if plan == "basic" else 0.0))
rows.append({
"customer_id": cid,
"snapshot": start + pd.DateOffset(months=k),
"plan": plan,
"city": city,
"tenure_months": tenure,
"monthly_charges": round(charges, 2),
"total_charges": round(charges * tenure, 2),
"support_calls": calls if rng.random() > 0.05 else np.nan,
"churned": int(rng.random() < 1 / (1 + np.exp(-logit))),
})
return pd.DataFrame(rows).sort_values("snapshot", ignore_index=True)
A Pipeline chains steps: every step but the last is a transformer, the last is the estimator. Calling fit fits each transformer on the training data and passes the transformed output on; calling predict only transforms. A ColumnTransformer applies different transformers to different columns and concatenates the results. Together they express the whole path from raw dataframe to prediction as one estimator.
Before building the pipeline we need two custom pieces. When a transformation learns something from data, write a class with TransformerMixin and BaseEstimator. The mixin gives you fit_transform and set_output support; BaseEstimator gives you get_params and set_params, which hyperparameter search and cloning rely on. The conventions matter: __init__ only stores its arguments unchanged, and everything learned in fit goes into attributes ending with an underscore.
When a transformation is stateless, a FunctionTransformer is enough.
# features.py
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import FunctionTransformer
class RatioFeatures(TransformerMixin, BaseEstimator):
"""Adds ratio columns; learns a clipping cap from the training data only."""
def __init__(self, pairs=(("total_charges", "tenure_months"),), quantile=0.99):
self.pairs = pairs
self.quantile = quantile
def fit(self, X, y=None):
ratios = self._ratios(X)
self.caps_ = ratios.quantile(self.quantile).to_dict()
self.feature_names_in_ = np.asarray(X.columns, dtype=object)
return self
def transform(self, X):
ratios = self._ratios(X)
return pd.concat([X, ratios.clip(upper=pd.Series(self.caps_), axis=1)], axis=1)
def get_feature_names_out(self, input_features=None):
return np.asarray(list(self.feature_names_in_)
+ [f"{a}_per_{b}" for a, b in self.pairs], dtype=object)
def _ratios(self, X):
return pd.DataFrame({f"{a}_per_{b}": X[a] / X[b].replace(0, np.nan)
for a, b in self.pairs}, index=X.index)
def _date_parts(X: pd.DataFrame) -> pd.DataFrame:
d = pd.to_datetime(X.iloc[:, 0])
return pd.DataFrame({"month": d.dt.month, "quarter": d.dt.quarter}, index=X.index)
def _date_part_names(transformer, input_features):
return ["month", "quarter"]
# Module-level functions, not lambdas: the fitted pipeline must be picklable.
date_parts = FunctionTransformer(_date_parts, feature_names_out=_date_part_names)
The clipping cap in RatioFeatures is a small example of a learned statistic. Computing the 99th percentile on the full dataset and clipping before the split would be leakage of exactly the same kind as the feature selection above, only smaller. Inside the class, the cap is learned per fold.
The comment on date_parts is not decoration. Our first version passed a lambda as feature_names_out; cross-validation worked, but saving the fitted pipeline later failed with PicklingError: Can't pickle <function <lambda> ...>: it's not found as features.<lambda>. Keep custom functions and classes at module level in an importable module, never in a notebook cell or in __main__.
# pipeline.py
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler, TargetEncoder
from features import RatioFeatures, date_parts
NUMERIC = ["tenure_months", "monthly_charges", "total_charges", "support_calls"]
def build_pipeline() -> Pipeline:
numeric = make_pipeline(
RatioFeatures(),
SimpleImputer(strategy="median", add_indicator=True),
StandardScaler(),
)
preprocess = ColumnTransformer(
[
("num", numeric, NUMERIC),
("plan", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["plan"]),
("city", TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=0)), ["city"]),
("date", make_pipeline(date_parts, OneHotEncoder(handle_unknown="ignore",
sparse_output=False)), ["snapshot"]),
],
remainder="drop",
verbose_feature_names_out=False,
)
return Pipeline([
("preprocess", preprocess),
("model", LogisticRegression(max_iter=1_000)),
]).set_output(transform="pandas")
Some details that prevent subtle bugs:
remainder="drop" is explicit. customer_id is not in any column list, so it never becomes a feature. Identifiers that leak into a model let it memorise entities instead of learning patterns.handle_unknown="ignore" makes the one-hot encoder output all zeros for a category not seen in training, instead of raising at prediction time.add_indicator=True appends a binary "was missing" column. Missingness is often informative, and the imputer only learns the median from the training fold.build_pipeline() returns a fresh, unfitted object each time, which keeps experiments independent.By default transformers return NumPy arrays and column names are lost. set_output(transform="pandas"), applied to the outer pipeline, propagates to every step, so intermediate results are dataframes with meaningful column names. That makes debugging and feature importance far easier, and it lets custom transformers such as RatioFeatures select columns by name.
from sklearn.model_selection import GroupKFold, cross_validate
from data import make_churn
from pipeline import build_pipeline
df = make_churn()
X, y, groups = df.drop(columns=["churned"]), df["churned"], df["customer_id"]
print(X.shape, f"churn rate {y.mean():.3f}")
pipe = build_pipeline()
scores = cross_validate(pipe, X, y, groups=groups, cv=GroupKFold(n_splits=5),
scoring="roc_auc")
print(f"GroupKFold ROC AUC: {scores['test_score'].mean():.3f} +/- {scores['test_score'].std():.3f}")
pipe.fit(X, y)
Xt = pipe[:-1].transform(X.head(3))
print(type(Xt).__name__, Xt.shape)
print(list(Xt.columns))
(3935, 8) churn rate 0.456
GroupKFold ROC AUC: 0.738 +/- 0.019
DataFrame (3, 26)
['tenure_months', 'monthly_charges', 'total_charges', 'support_calls', 'total_charges_per_tenure_months', 'missingindicator_support_calls', 'plan_basic', 'plan_plus', 'plan_pro', 'city', 'month_1', ..., 'quarter_4']
pipe[:-1] slices off the model and returns the fitted preprocessing as its own pipeline, which is the quickest way to inspect what the model actually sees.
High-cardinality categoricals such as city, product or postcode are awkward. One-hot encoding creates hundreds of sparse columns; ordinal encoding imposes a meaningless order. Target encoding replaces each category with the (smoothed) mean of the target for that category, which is compact and often strong. It is also the easiest way to leak the target into the features, because the encoding is computed from y.
The following experiment uses a postcode-like column with 1,500 levels, about two rows per level, and a target with no relation to it at all:
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import TargetEncoder
rng = np.random.default_rng(1)
n = 3_000
X = pd.DataFrame({"zip_code": rng.integers(0, 1_500, n).astype(str)}) # ~2 rows per level
y = rng.integers(0, 2, n) # no signal at all
cv = StratifiedKFold(5, shuffle=True, random_state=0)
# 1. Leaky: mean target per level computed on the full data set
means = pd.Series(y).groupby(X["zip_code"]).mean()
X_leaky = X["zip_code"].map(means).to_frame()
auc = cross_val_score(LogisticRegression(), X_leaky, y, cv=cv, scoring="roc_auc")
print(f"leaky mean encoding, CV AUC : {auc.mean():.3f}")
# 2. fit().transform() versus fit_transform() on the training rows
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
for name in ["fit().transform()", "fit_transform()"]:
enc = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=0))
Z_tr = enc.fit(X_tr, y_tr).transform(X_tr) if name == "fit().transform()" \
else enc.fit_transform(X_tr, y_tr)
clf = LogisticRegression().fit(Z_tr, y_tr)
train_auc = roc_auc_score(y_tr, clf.predict_proba(Z_tr)[:, 1])
test_auc = roc_auc_score(y_te, clf.predict_proba(enc.transform(X_te))[:, 1])
print(f"{name:18} train AUC {train_auc:.3f} test AUC {test_auc:.3f}")
# 3. Correct: TargetEncoder inside a pipeline, evaluated with CV
pipe = make_pipeline(TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=0)),
LogisticRegression())
auc = cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc")
print(f"pipeline TargetEncoder, CV AUC: {auc.mean():.3f}")
leaky mean encoding, CV AUC : 0.875
fit().transform() train AUC 0.907 test AUC 0.505
fit_transform() train AUC 0.505 test AUC 0.505
pipeline TargetEncoder, CV AUC: 0.494
Three lessons in four lines:
groupby().mean() on all data produces a cross-validated AUC of 0.875 on a target that is pure noise. Each row's own label is part of its encoding.TargetEncoder leaks if you call fit and then transform on the same rows. transform uses encodings learned from all training rows, so the model sees a feature that contains its own label and the training AUC is 0.907. The test AUC exposes it.fit_transform is different by design: it uses internal cross-fitting. The training rows are split into folds and each row is encoded with statistics from the other folds only. transform on new data uses the full-training-set encodings, which is correct because those rows were not part of the fit. A Pipeline calls fit_transform during fit, so placing the encoder inside the pipeline gives the right behaviour automatically.Two parameters deserve attention. smooth controls shrinkage towards the global mean; the default "auto" uses an empirical Bayes estimate, and it is worth tuning for categories with very few rows. cv controls the internal cross-fitting. In scikit-learn 1.9 the shuffle and random_state parameters of TargetEncoder are deprecated (removal is announced for 1.11); our first run emitted a FutureWarning saying so. Pass a splitter instead, as in the code above.
One caveat remains for grouped data. The internal cross-fitting splits rows, not customers, so within a training fold the encoding of a row can still use another snapshot of the same customer. With a handful of rows per customer and smoothing this effect is small, but if one entity dominates a category, consider aggregating to one row per entity before encoding.
Pipelines stop preprocessing leakage. They do nothing about the split itself. Our dataset has several rows per customer, and an unobserved habit makes rows from the same customer similar. With a shuffled KFold, snapshots of the same customer land in both training and validation folds, and the model is partly rewarded for recognising customers it has already seen. In production, it will mostly score customers or months it has not seen.
from sklearn.model_selection import GroupKFold, KFold, TimeSeriesSplit, cross_val_score
from data import make_churn
from pipeline import build_pipeline
df = make_churn() # sorted by snapshot date
X, y, groups = df.drop(columns=["churned"]), df["churned"], df["customer_id"]
pipe = build_pipeline()
splitters = {
"KFold(shuffle) ": (KFold(5, shuffle=True, random_state=0), None),
"GroupKFold ": (GroupKFold(5), groups),
"TimeSeriesSplit ": (TimeSeriesSplit(5), None),
}
for name, (cv, g) in splitters.items():
s = cross_val_score(pipe, X, y, groups=g, cv=cv, scoring="roc_auc")
print(f"{name} ROC AUC {s.mean():.3f}")
KFold(shuffle) ROC AUC 0.770
GroupKFold ROC AUC 0.738
TimeSeriesSplit ROC AUC 0.750
The shuffled split overstates performance by about 0.03 AUC here. In our runs the gap was similar with tree ensembles (0.733 versus 0.709 for histogram gradient boosting), so it is a property of the split, not of the model. On real data with stronger entity effects, such as patients, devices or stores, the gap is often much larger.
Choose the splitter by asking how the model will be used:
GroupKFold or StratifiedGroupKFold with the entity id as groups.TimeSeriesSplit on data sorted by time. It always validates on rows later than the training rows. Use its gap parameter when the label becomes known only after a delay, so the last rows before the gap cannot leak future information through lagged features.(train_idx, test_idx) pairs: split on time, then remove from each training set any entity that appears in its test set.Because the pipeline is a single estimator, a search object can tune preprocessing and model together, and every candidate is evaluated with preprocessing fitted inside the folds. Parameters are addressed with double underscores: step__substep__parameter. Whole steps can be replaced too, including with "drop" or "passthrough".
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, GroupKFold
from data import make_churn
from pipeline import build_pipeline
df = make_churn()
X, y, groups = df.drop(columns=["churned"]), df["churned"], df["customer_id"]
param_grid = [
{
"model": [LogisticRegression(max_iter=1_000)],
"model__C": [0.1, 1.0, 10.0],
"preprocess__num__simpleimputer__strategy": ["median", "mean"],
"preprocess__city__smooth": ["auto", 20.0],
},
{
"model": [HistGradientBoostingClassifier(random_state=0)],
"model__learning_rate": [0.05, 0.1],
"model__max_leaf_nodes": [15, 31],
"preprocess__date": ["drop"],
},
]
search = GridSearchCV(build_pipeline(), param_grid, cv=GroupKFold(5),
scoring="roc_auc", n_jobs=-1)
search.fit(X, y, groups=groups)
print(f"best CV ROC AUC: {search.best_score_:.3f}")
for k, v in search.best_params_.items():
print(f" {k} = {v}")
best CV ROC AUC: 0.743
model = LogisticRegression(max_iter=1000)
model__C = 1.0
preprocess__city__smooth = 20.0
preprocess__num__simpleimputer__strategy = median
A list of dictionaries defines separate sub-grids, so the gradient boosting candidates do not waste time on logistic regression parameters. The groups passed to fit are forwarded to GroupKFold.
best_score_ is itself slightly optimistic: it is the maximum over 16 noisy estimates, chosen using the same folds that produced them. To report a number for the whole procedure, wrap the search in an outer cross-validation (nested CV):
inner = GridSearchCV(build_pipeline(),
{"model__C": [0.01, 0.1, 1.0, 10.0],
"preprocess__city__smooth": ["auto", 5.0, 20.0, 100.0]},
cv=GroupKFold(3), scoring="roc_auc", n_jobs=-1)
outer = cross_val_score(inner, X, y, groups=groups, cv=GroupKFold(5),
scoring="roc_auc", params={"groups": groups})
print(f"nested CV ROC AUC: {outer.mean():.3f} +/- {outer.std():.3f}")
nested CV ROC AUC: 0.740 +/- 0.015
groups= drives the outer splitter; params={"groups": groups} passes the matching subset of group labels to the inner search's fit, so both levels split by customer. Here the difference is small, but with large grids and small datasets the optimism of best_score_ can be substantial.
The fitted pipeline, not the model alone, is the artefact to deploy. It contains the medians, scaling parameters, category lists and target encodings that the model was trained with. Saving only the model and rebuilding preprocessing at serving time is a classic source of training-serving skew.
import hashlib
import json
import platform
from datetime import datetime, timezone
from pathlib import Path
import joblib
import sklearn
from data import make_churn
from pipeline import build_pipeline
df = make_churn()
X, y = df.drop(columns=["churned"]), df["churned"]
pipe = build_pipeline().fit(X, y)
out = Path("artifacts/churn/1.4.0")
out.mkdir(parents=True, exist_ok=True)
joblib.dump(pipe, out / "model.joblib", compress=3)
meta = {
"model_version": "1.4.0",
"trained_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"sklearn": sklearn.__version__,
"python": platform.python_version(),
"training_rows": len(X),
"data_sha256": hashlib.sha256(
df.to_csv(index=False).encode()).hexdigest()[:16],
"features_in": list(pipe.feature_names_in_),
}
(out / "metadata.json").write_text(json.dumps(meta, indent=2))
loaded = joblib.load(out / "model.joblib")
print((loaded.predict_proba(X.head(5)) == pipe.predict_proba(X.head(5))).all())
print(json.dumps({k: meta[k] for k in ["model_version", "sklearn", "data_sha256"]}))
True
{"model_version": "1.4.0", "sklearn": "1.9.1", "data_sha256": "9f4550a9744e6f35"}
joblib uses pickle. Loading a pickle executes code, so only load files you produced yourself or received from a trusted source. Pickles are also tied to library versions: scikit-learn emits an InconsistentVersionWarning when it loads an estimator pickled with a different version, and the result is not guaranteed to work. Pin the training environment and record the versions next to the file, as above.
skops offers a format that does not execute arbitrary code on load. It refuses to construct any type that is not on its trusted list, and it tells you which types you would have to trust:
import skops.io as sio
sio.dump(pipe, "artifacts/churn/1.4.0/model.skops")
unknown = sio.get_untrusted_types(file="artifacts/churn/1.4.0/model.skops")
print(unknown)
# Review the list, then allow exactly those types and nothing else.
TRUSTED = [
"features.RatioFeatures", "features._date_parts", "features._date_part_names",
"numpy.dtype", "sklearn.model_selection._split.StratifiedKFold",
]
assert set(unknown) <= set(TRUSTED), set(unknown) - set(TRUSTED)
loaded = sio.load("artifacts/churn/1.4.0/model.skops", trusted=TRUSTED)
print(loaded.predict_proba(X.head(3)).round(3))
['features.RatioFeatures', 'features._date_part_names', 'features._date_parts', 'numpy.dtype', 'sklearn.model_selection._split.StratifiedKFold']
[[0.769 0.231]
[0.272 0.728]
[0.513 0.487]]
Our first attempt trusted only the three custom names, and the assertion failed on numpy.dtype and the StratifiedKFold stored inside the target encoder. That is the intended workflow: inspect the list, decide, and pin it in code. Never pass the output of get_untrusted_types straight into trusted without review, because that defeats the purpose.
Treat a fitted pipeline like a release:
features.RatioFeatures by import path; if that class changes or moves, old artefacts stop loading.SelectKBest in the first example with a StandardScaler fitted on all rows. Measure how much the leaky score differs from the honest one, and explain why it is so much smaller than for feature selection.("monthly_charges", "support_calls"), to RatioFeatures through the grid search parameter preprocess__num__ratiofeatures__pairs, and check that get_feature_names_out still matches the output columns.GroupKFold and TimeSeriesSplit.TargetEncoder for OneHotEncoder(min_frequency=10, handle_unknown="infrequent_if_exist") on the city column and compare grouped CV scores.features.py is not importable, and observe the error. Then decide where custom transformers should live in your own project so that serving can always import them.Found a mistake in this tutorial? Let us know and we will fix it.