Unit 6 of 8 · about 3 hours · implement
Training-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.
You'll be able to
- 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
Read
In this order, only the parts listed
0 of 4 done
- Inconsistent preprocessing and the
Pipelinefixscikit-learn - Common pitfalls and pipelines12.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) PipelineandColumnTransformerreferencescikit-learn - Common pitfalls and pipelines8.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.
Common mistakes · 3
- 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.
Try it yourself
Closed-book, before checking anything
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.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does the wrong 12.1 run give test MSE 62.80 while the right one gives 0.90?Answer
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 a
Pipeline, restores 0.90.2.Where must
SimpleImputerwith median strategy befit, and how do you check it?AnswerOn train numerics only. Check
imputer.statistics_against the train column medians, thentransformtrain and test with the same object.3.The notebook's test frame holds
<2H OCEAN, a misspelling of<1H OCEAN. What doeshandle_unknown=ignoreemit, and what does it hide?AnswerAn 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.
4.Your custom transformer takes
*argsfor flexibility. What breaks?AnswerGrid search and cloning: scikit-learn requires explicit
__init__parameters forget_paramsandset_params, socheck_estimatorfails.
Practice
- Hands-On ML Chapter 2, Exercise 6:
StandardScalerCloneExercise 6 under Exercise solutions: reimplement
StandardScalerClonewithinverse_transformand feature-name support; oracles arecheck_estimatorplus the fourallcloseand name assertionsImplement from a blank file in your own repository, then wrap it in a
ColumnTransformerand confirmget_feature_names_outflows through.
You're done 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.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 4 more in the section
- Hands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2Aurelien Geron (O'Reilly, 2025) · primary
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 pipelinesscikit-learn · required
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 splittersscikit-learn · support
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 controlsGoogle for Developers · support
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 DatasetUCI Machine Learning Repository · support
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 problemGoogle for Developers · support
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.