Leakage-safe pipelines
Find the three common leaks, and keep every learned value inside the training rows of each fold.
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
What leakage is
ReadLeakageData 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:
- Target copies: a column derived from the outcome, such as
refund_issuedwhen predicting a return. - Future information: a value recorded after the prediction moment.
- Preprocessing: a median, scale or vocabulary learned from rows that include your validation data.
Spot it
ExploreChoose 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?
The pipeline
Commit your prediction above to see the result
Make your prediction to see the result.
Does scaling really leak?
PredictPredict 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?
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.
How folds should run
ExploreFor 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?
Scheme
Commit your prediction above to see the result
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.
Where CodeSplash does this
In the appIn 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}}.
The pipeline, in code
ReadA recipe's Code panel exports the same idea as a scikit-learn Pipeline or a tidymodels recipe.
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 foldlibrary(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 foldCheck your understanding
CheckpointCheck 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.
Show the answer
The order:
- Split rows into training and validation
- Learn the median and scale from the training rows
- Apply them to both sets
- Fit the model on the training rows
- 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.
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