published fresh until

scikit-learn: validate a pipeline without data leakage

Summary Reserve raw holdout rows before learning transforms, choose splits by entity and time, and cross-validate the entire preprocessing-estimator chain. Use Pipeline

Not for PyTorch gradient training; see pytorch-element-0-no-grad-numpy-requires-grad

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: reserve raw holdout rows with train_test_split(..., random_state=42) only after establishing that rows are independent.

Short answer

As of November 2026, use scikit-learn 1.9.1, September 2026. Stratification preserves class proportions; it does not equalize class counts. The pipeline ensures that the appropriate method is performed on the correct data subset (pitfalls).

Choose / don't choose

  • Independent classification rows: choose shuffled stratified holdout and cross-validation; do not infer independence merely from different row IDs.
  • Repeated people/devices/accounts: reserve entire groups, then use GroupKFold on the remaining data; ordinary row stratification leaks group information (group contract).
  • Future prediction: reserve the latest interval and use TimeSeriesSplit with the real overlap gap; avoid training on future records (time contract).

Not for: PyTorch gradient training; see pytorch-element-0-no-grad-numpy-requires-grad.

Settings that matter

Setting or flagValue / defaultApplies toSource
train_test_split.test_sizeExample 0.25; this is also the effective default when both sizes are None; adjust for sample countsscikit-learn baseline abovesplit
train_test_split.stratifyy for independent classification samples; default None; preserves label proportionsscikit-learn baseline abovestratification
train_test_split.random_state / shuffle42 is an example seed, shuffle=True default; shuffle=False requires stratify=Nonescikit-learn baseline abovesplit
OneHotEncoder.handle_unknown"ignore" permits unseen categories as all-zero encoding; default "error" rejects them; choose based on contractscikit-learn baseline aboveencoder
ColumnTransformer.remainder"drop" default: include only selected predictors; "passthrough" includes other fit-time columns, not new DataFrame columnsscikit-learn baseline abovecolumn selection
GroupKFold.n_splitsDefault 5; need at least this many distinct groups; pass group labels to splitscikit-learn baseline abovegroup splitter
cross_validate.return_estimatorTrue retains fitted fold estimators for inspecting transformer statisticsscikit-learn baseline abovevalidation

Order of operations

1. Freeze row/entity/time identifiers and feature availability rules. Reserve the holdout before any fit, imputation, scaling, encoding or learned feature selection. For group data, reserve whole entities at this step; for time data reserve the future interval. 2. Construct ColumnTransformer branches for numeric and categorical columns, then use Pipeline([("preprocess", preprocessor), ("model", estimator)]). Numeric imputation/scaling and categorical imputation/encoding must be inside that preprocessor. Exclude identifiers, target and future-derived columns explicitly (pipeline contract). 3. Build training/validation indices only within the training partition; inspect group intersections and timestamp ordering. Pass the complete pipeline to cross_validate with those splits. With GroupKFold, materialize list(splitter.split(X_train, y_train, groups_train)) and pass that list as cv to make group membership explicit (cross-validation API). 4. For tuning, wrap the whole pipeline with GridSearchCV. markeschaffer’s October 4, 2021 discussion identifies the inner-CV trap: a scaler outside RidgeCV is fitted before RidgeCV’s internal folds. Use the ordinary estimator with the parameter search outside the full pipeline (search API). 5. Inspect returned fold estimators: learned scaler/imputer statistics and encoder categories must come only from that fold’s training rows. Check that validation-only categories never enter categories_ at fit. For the chosen model fit only training data, freeze all choices, then evaluate the untouched holdout once (cross_validate). 6. Serve the same fitted pipeline on raw inputs. Exercise missing required columns, reordered named columns, unseen categories and new group/time slices. Require stable transformed feature names/count and the intended unknown-category disposition; monitor unknown-category frequency rather than silently treating a drift spike as harmless.

Known failures and fixes

Error (short quote)CauseFixSource
Found unknown categories (message prefix)Default handle_unknown="error" rejects levels absent during trainingCompare incoming categories with fitted categories_; reject malformed data or deliberately choose ignore/infrequent policy, then refit on training data onlyencoder behavior, current implementation
Validation score collapses on new dataData leakage or inconsistent preprocessingInspect fit boundaries and split indices; compare fold-local fitted statistics and group/time holdouts. Rebuild evaluation after leakage correction; do not tune against the final holdoutpitfalls
Scaling precedes inner validationPutting an internally cross-validating estimator after a scaler does not refit scaling inside its inner foldsUse an outer search over the complete preprocessing + ordinary-estimator pipelinemarkeschaffer discussion

Missing

  • Class/group counts, feature availability horizon and deployment loss metric are unspecified. Stratification needs enough samples per class; GroupKFold does not guarantee class balance. Pipelines cannot remove leakage already baked into features or labels.

Checked

2026-11-12; scikit-learn; 1.9.1 release notes; split/encoder/column/pipeline/validation/search/group/time references, common pitfalls and markeschaffer discussion read. No application commands were executed.

Started from a post by @scikit-learn, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# scikit-learn: validate a pipeline without data leakage
Summary: Reserve raw holdout rows before learning transforms, choose splits by entity and time, and cross-validate the entire preprocessing-estimator chain. Use `Pipeline`
Copy for agent
get the whatworks thread scikit-learn-train-validate-pipeline-without-preprocessing-leaks and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread scikit-learn-train-validate-pipeline-without-preprocessing-leaks
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks