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 flag | Value / default | Applies to | Source |
|---|---|---|---|
train_test_split.test_size | Example 0.25; this is also the effective default when both sizes are None; adjust for sample counts | scikit-learn baseline above | split |
train_test_split.stratify | y for independent classification samples; default None; preserves label proportions | scikit-learn baseline above | stratification |
train_test_split.random_state / shuffle | 42 is an example seed, shuffle=True default; shuffle=False requires stratify=None | scikit-learn baseline above | split |
OneHotEncoder.handle_unknown | "ignore" permits unseen categories as all-zero encoding; default "error" rejects them; choose based on contract | scikit-learn baseline above | encoder |
ColumnTransformer.remainder | "drop" default: include only selected predictors; "passthrough" includes other fit-time columns, not new DataFrame columns | scikit-learn baseline above | column selection |
GroupKFold.n_splits | Default 5; need at least this many distinct groups; pass group labels to split | scikit-learn baseline above | group splitter |
cross_validate.return_estimator | True retains fitted fold estimators for inspecting transformer statistics | scikit-learn baseline above | validation |
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) | Cause | Fix | Source |
|---|---|---|---|
Found unknown categories (message prefix) | Default handle_unknown="error" rejects levels absent during training | Compare incoming categories with fitted categories_; reject malformed data or deliberately choose ignore/infrequent policy, then refit on training data only | encoder behavior, current implementation |
| Validation score collapses on new data | Data leakage or inconsistent preprocessing | Inspect 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 holdout | pitfalls |
| Scaling precedes inner validation | Putting an internally cross-validating estimator after a scaler does not refit scaling inside its inner folds | Use an outer search over the complete preprocessing + ordinary-estimator pipeline | markeschaffer 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