Skip to content

Leakage-safe pipelines

Find the three common leaks, and keep every learned value inside the training rows of each fold.

Advanced ~12 min8 steps

You will be able to

  • Name three common sources of leakage
  • Explain why preprocessing belongs inside cross-validation
  • Use Predict and exported pipelines to keep folds clean

Read first

01

What leakage is

Read

LeakageData leakageInformation from the validation data or the future seeps into training, so scores look better than reality. is information reaching a model during training that it won't have when you use it. The result looks excellent until the model meets real data.

Three common sources:

  1. Target copies: a column derived from the outcome, such as refund_issued when predicting a return.
  2. Future information: a value recorded after the prediction moment.
  3. Preprocessing: a median, scale or vocabulary learned from rows that include your validation data.
02

Spot it

Explore

Choose a pipeline, then compare cross-validated accuracy with accuracy on new data. Try picking features on all rows, a column recorded after the outcome, and random splits when customers repeat. Then pick features inside each fold and see the gap close.

DExplorable · Leakage detective

Why does a model that scores brilliantly in testing fail on real data?

Read the pipeline on the left. Will its cross-validation score overstate real-world accuracy by more than 6 points?

How sure?

The pipeline

200
60
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Does scaling really leak?

Predict

Predict first

You standardize all rows before cross-validating. A validation row's value contributed to the mean and SD. How far does this inflate the score, compared with a feature selected on all rows?

A littleA lotNot at all
Reveal

The answer: A little

A little for scaling, which learns only two numbers. Selecting features on all rows, or target-encoding them, can inflate scores dramatically, because those steps learn from the outcome. Keep every one of them in the fold anyway: then you never have to judge.

04

How folds should run

Explore

For each fold, learn from the training rows, then apply what you learned to the validation rows. Change the scheme and see which rows each one holds out.

DExplorable · Cross-validation folds

Which rows should be held out so the score predicts real performance?

Each scheme has a tempting shortcut: training error, plain random folds, or the best score from a search. Will the shortcut here look better than the true error on new data?

How sure?

Scheme

5
40
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

The order is: split, then fit the preprocessing on training rows, then transform both, then fit the model.

05

Where CodeSplash does this

In the app

In Predict, these options are learned inside each fold: Impute missing numbers, Scale numbers and the indicator columns for categories. Resampling touches only training rows.

A recipe in Prepare learns once from all its input rows. So:

  • Use Prepare for facts about the data: fixing types, codes and impossible values.
  • Use the Model options, or an exported pipeline, for anything that learns from the data.

In Insights (⌘5), the ML engineer page flags possible leaks. The walkthrough below trains a first model that predicts {{target}}.

06

The pipeline, in code

Read

A recipe's Code panel exports the same idea as a scikit-learn Pipeline or a tidymodels recipe.

Python
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression())
scores = cross_val_score(model, X, y, cv=5)  # fits every step inside each fold
R
library(tidymodels)

rec <- recipe(churn ~ ., data = train) |>
  step_impute_median(all_numeric_predictors()) |>
  step_normalize(all_numeric_predictors())
wf <- workflow() |> add_recipe(rec) |> add_model(logistic_reg())
res <- fit_resamples(wf, vfold_cv(train, v = 5))  # prepped inside each fold
07

Check your understanding

Checkpoint

Check yourself

A churn model uses the column cancellation_reason. What's wrong?

Show the answer

Answer: a

The column exists because of the outcome. Ask when each feature becomes known.

Check yourself

Put the steps of one cross-validation fold in the right order.

  1. 1Split rows into training and validation
  2. 2Score the validation rows
  3. 3Apply them to both sets
  4. 4Fit the model on the training rows
  5. 5Learn the median and scale from the training rows

Show the answer

The order:

  1. Split rows into training and validation
  2. Learn the median and scale from the training rows
  3. Apply them to both sets
  4. Fit the model on the training rows
  5. Score the validation rows

Nothing learned may see the validation rows before they are scored.

Check yourself

For a model that predicts next week's demand, what is the right validation?

Show the answer

Answer: b

Random folds let the model train on the future of the rows it's validating on. The Time order role in Predict validates only on later rows.

08

Recap

Recap
  • Leaks come from target copies, the future and preprocessing on all rows.
  • Split first, then learn everything from training rows only.
  • Use Prepare for facts about the data, and Model options or pipelines for anything learned.

Concepts in this lesson