Unit 1.6 · about 3 h
133 / 324Training-only imputation, scaling, encoding and learned state
Preprocessing is where most silent leakage lives. One fitted pipeline object removes the whole class of fit-on-everything bugs.
- implement
You can now
- Identify which preprocessing statistics may be fit on which partition, and prove point-in-time availability for each feature.
- Build a leakage-safe numeric and categorical pipeline with fitted state, unknown-category behavior, schema tests, and serialization.
- Explain why preprocessing must live inside the split procedure rather than before it.
Covers
- Training-only imputation, scaling, encoding and learned state
Study, in this order
4 steps
- Inconsistent preprocessing and the `Pipeline` fixscikit-learn - Common pitfalls and pipelines
12.1 Inconsistent preprocessing with the untransformed-test MSE of 62.80 versus 0.90 after transforming, and the
make_pipelinefix; 12.2.1 How to avoid data leakage (split first,fitandfit_transformon train only,transformon both) - `Pipeline` and `ColumnTransformer` referencescikit-learn - Common pitfalls and pipelines
8.1.1
Pipeline: chaining estimators (convenience, joint parameter selection, safety: same samples train transformers and predictors) with 8.1.1.1 Usage (build, access steps, nested parameters); 8.1.4ColumnTransformerfor heterogeneous data (why preprocess inside scikit-learn: no test statistics in the preprocessors, and preprocessing parameters in the search; per-column transforms; remainder handling) - Numeric and categorical pipelines in the housing notebookHands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2
Book Chapter 2: Handling Text and Categorical Attributes and Feature Scaling and Transformation (printed pp. 73-81), then Transformation Pipelines (pp. 86-90). Notebook 02: Transformation Pipelines (
num_pipelinewithSimpleImputermedian plusStandardScaler,ColumnTransformerwithnumandcatpipelines,make_column_selectorvariant,get_feature_names_out); Handling Text and Categorical Attributes (OrdinalEncoderversusOneHotEncoder,sparse_outputflag,get_dummiesmismatch,handle_unknownignoremapping the unseen<2H OCEANto an all-zero row); Feature Scaling (MinMaxScaler,StandardScaler) - Custom transformer exercise with an estimator oracleHands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2
Book Chapter 2: Custom Transformers (printed pp. 81-86) and Exercise 6 (p. 104). Notebook 02: Exercise 6:
StandardScalerClonefrom scratch withinverse_transformand feature-name support, checked bycheck_estimatorplus theallcloseassertions (centered, uncenteredwith_meanFalse, round trip) and feature-name assertions
Focus on
- Fit learns state from train only: imputer
statistics_, scalermean_andscale_, encodercategories_. Transform applies it everywhere. Section 12.1 prices forgetting the second half: test MSE 62.80 versus 0.90. - Pipelines make the order mechanical: impute, then scale, then encode inside one object fitted once on train, with nested-parameter access for later tuning and
ColumnTransformerrouting per dtype. - Unknown categories are a serving fact, not an exception. Default
OneHotEncoderraises aValueErroron an unseen value such as<2H OCEAN;handle_unknown=ignoreemits an all-zero row, andget_feature_names_outcarries the schema into the model. - Custom transformers must honor the estimator contract: explicit
__init__parameters,fitacceptingy, learned state in trailing-underscore attributes, feature names tracked.check_estimatoris the conformance oracle.
Reproduce closed-book
ColumnTransformer pipeline (median-impute plus standardize numerics, most-frequent-impute plus one-hot-ignore-unknowns for categoricals), fit on train only, and state the two oracle numbers from the pitfalls synthetic set: test MSE 62.80 untransformed versus 0.90 transformed.Traps
- Calling
fit_transformon the full frame before splitting. The convenience call is the classic leak; split first, thenfit_transformon train andtransformon test. - Assuming
get_dummiesgeneralizes. It silently builds disjoint columns on new categories; only a fitted encoder with a declared unknown policy survives serving. - Forgetting the sparse default.
OneHotEncoderreturns sparse output by default (sparse_outputTruein 1.9); downstream code expecting dense breaks or densifies huge matrices, so declare the flag explicitly.
Practice
Hands-On ML Chapter 2, Exercise 6: `StandardScalerClone`
Exercise 6 under Exercise solutions: reimplement StandardScalerClone with inverse_transform and feature-name support; oracles are check_estimator plus the four allclose and name assertions
Implement from a blank file in your own repository, then wrap it in a ColumnTransformer and confirm get_feature_names_out flows through.
Self-test
-
Why does the wrong 12.1 run give test MSE 62.80 while the right one gives 0.90?
The model trains on scaled features but predicts on unscaled test rows, so it sees a different feature space. Transforming test with the same fitted scaler, or using aPipeline, restores 0.90. -
Where must
SimpleImputerwith median strategy befit, and how do you check it?On train numerics only. Checkimputer.statistics_against the train column medians, thentransformtrain and test with the same object. -
The notebook's test frame holds
<2H OCEAN, a misspelling of<1H OCEAN. What doeshandle_unknown=ignoreemit, and what does it hide?An all-zero row: none of the known categories. Serving survives, but a data-entry error passes silently, so count unknowns per batch and alert when the rate rises. -
Your custom transformer takes
*argsfor flexibility. What breaks?Grid search and cloning: scikit-learn requires explicit__init__parameters forget_paramsandset_params, socheck_estimatorfails.
Completion criterion
Stop when
check_estimator passes on your transformer and your pipeline reproduces the 62.80 and 0.90 pair, plus all-zero rows for unknown categories.
Leads to
- 1.7 Baselines: constant, frequency, heuristic, last-value and simple learned Run every baseline through the same fitted pipeline.
- 1.8 Snapshots, lineage, pipeline serialization and serving parity Serialize the fitted pipeline and prove serving parity.
Comes after
- 1.3 Split design, nested selection and test isolationFit every learned preprocessing state inside the split built here.
- 1.4 Leakage: target, future, entity, duplicate, preprocessing and feedbackPut the preprocessing repair inside a pipeline.
- 1.5 Schema, provenance, missingness, duplicate and availability auditsFeed audited columns into train-only transformers with an unknown-category policy.
- 4.1 Numeric transforms and categorical encodingApply the training-only fitting rule to imputation, scaling and encoding.
Resources for this unit
- Hands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2 Read Chapters 1 and 2 of the book, then run notebooks 01 and 02 and use ml-project-checklist.md for framing, data inspection, test-set creation, preprocessing pipelines, cross-validation, error analysis and persistence. Rebuild the workflow on UCI Bike Sharing with a chronological split and prohibit casual and registered when predicting cnt.
- scikit-learn - Common pitfalls and pipelines Read Common Pitfalls sections on inconsistent preprocessing and leakage, then Pipeline and ColumnTransformer. Seed global scaling, a target-derived feature and a partition duplicate, and make tests reject each defect.
Also in this section
- scikit-learn - Cross-validation splitters Use the group-aware and time-aware splitter sections plus GroupKFold and TimeSeriesSplit. Choose from the dependence structure and assert that no prohibited group or future timestamp crosses the boundary.
- Rules of Machine Learning - first controls Read Rules 1-5 and 8-9. Turn the existing heuristic into a baseline and test the feature path independently of the learner.
- UCI Bike Sharing Dataset Use hour.csv as the compact integrated dataset. Preserve a raw snapshot and data dictionary, split chronologically, and document why casual and registered are target proxies for cnt.
- Google ML Problem Framing - framing an ML problem Read Identify the output you need through Proxy labels and Define the success metrics, including the video-caching threshold analysis, the proxy-issue table, and both Check Your Understanding boxes.