7 routes42 sections324 units

Unit 1.6 · about 3 h

133 / 324

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.

  • 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

  1. Inconsistent preprocessing and the `Pipeline` fix
    scikit-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` reference
    scikit-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 notebook
    Hands-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 oracle
    Hands-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

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.

Reproduce closed-book

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.

Traps

  • 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.

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

  1. Why does the wrong 12.1 run give test MSE 62.80 while the right one gives 0.90?

  2. Where must SimpleImputer with median strategy be fit, and how do you check it?

  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?

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

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.

Mark passed, then open 1.7 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • Hands-On Machine Learning with Scikit-Learn and PyTorch - Chapters 1 and 2
    Aurelien Geron (O'Reilly, 2025)primarycourse
    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
    scikit-learnrequiredreference
    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
    scikit-learnsupportreference
    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
    Google for Developerssupportapplication
    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
    UCI Machine Learning Repositorysupportpractice
    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
    Google for Developerssupportapplication
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels