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

Training-only imputation, scaling, encoding and learned state
1

Read

In this order, only the parts listed

0 of 4 done

  1. 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_pipeline fix; 12.2.1 How to avoid data leakage (split first, fit and fit_transform on train only, transform on both)

  2. 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.4 ColumnTransformer for heterogeneous data (why preprocess inside scikit-learn: no test statistics in the preprocessors, and preprocessing parameters in the search; per-column transforms; remainder handling)

  3. 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_pipeline with SimpleImputer median plus StandardScaler, ColumnTransformer with num and cat pipelines, make_column_selector variant, get_feature_names_out); Handling Text and Categorical Attributes (OrdinalEncoder versus OneHotEncoder, sparse_output flag, get_dummies mismatch, handle_unknown ignore mapping the unseen <2H OCEAN to an all-zero row); Feature Scaling (MinMaxScaler, StandardScaler)

  4. 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: StandardScalerClone from scratch with inverse_transform and feature-name support, checked by check_estimator plus the allclose assertions (centered, uncentered with_mean False, round trip) and feature-name assertions

2

Focus on

  • Fit learns state from train only: imputer statistics_, scaler mean_ and scale_, encoder categories_. 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 ColumnTransformer routing per dtype.
  • Unknown categories are a serving fact, not an exception. Default OneHotEncoder raises a ValueError on an unseen value such as <2H OCEAN; handle_unknown=ignore emits an all-zero row, and get_feature_names_out carries the schema into the model.
  • Custom transformers must honor the estimator contract: explicit __init__ parameters, fit accepting y, learned state in trailing-underscore attributes, feature names tracked. check_estimator is the conformance oracle.
Common mistakes · 3
  • Calling fit_transform on the full frame before splitting. The convenience call is the classic leak; split first, then fit_transform on train and transform on test.
  • Assuming get_dummies generalizes. It silently builds disjoint columns on new categories; only a fitted encoder with a declared unknown policy survives serving.
  • Forgetting the sparse default. OneHotEncoder returns sparse output by default (sparse_output True in 1.9); downstream code expecting dense breaks or densifies huge matrices, so declare the flag explicitly.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write a 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.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 2.Where must SimpleImputer with median strategy be fit, and how do you check it?Answer

    On train numerics only. Check imputer.statistics_ against the train column medians, then transform train and test with the same object.

  3. 3.The notebook's test frame holds <2H OCEAN, a misspelling of <1H OCEAN. What does handle_unknown=ignore emit, and what does it hide?Answer

    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.

  4. 4.Your custom transformer takes *args for flexibility. What breaks?Answer

    Grid search and cloning: scikit-learn requires explicit __init__ parameters for get_params and set_params, so check_estimator fails.

5

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.

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.