Unit 2 of 8 · about 4 hours · implement

Interactions, feature selection and fit-state serialization

Features built outside the pipeline leak across splits and drift from serving code. One saved fitted object is the only representation that both training and serving run.

You'll be able to

  • Assemble numeric, categorical and interaction features in one ColumnTransformer with declared remainder behavior.
  • Run feature selection inside the split boundary and report the threshold with its validation effect.
  • Serialize the fitted pipeline with joblib and reload it to identical predictions, including unknown categories.

Covers

Interactions and feature selection inside the split boundaryFit-state serialization and sparse-to-dense hazards
1

Read

In this order, only the parts listed

0 of 3 done

  1. Interactions, custom transformers and pipelinesHands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning

    Book Chapter 2: Experiment with Attribute Combinations (printed pp. 68-69), then Custom Transformers and Transformation Pipelines (pp. 81-90). Notebook 02 cells: Experimenting with Attribute Combinations for ratio features; Custom Transformers with StandardScalerClone, RBF similarity and ClusterSimilarity on latitude and longitude; Transformation Pipelines with num_pipeline, cat_pipeline using handle_unknown=ignore, and the full ColumnTransformer

    Skim the KNN-regressor transformer variant in Exercise 4; keep the ClusterSimilarity pattern and the pipeline assembly.

  2. Pipeline and ColumnTransformer contractsscikit-learn - pipelines and composite estimators

    8.1.1 Pipeline fit and transform chaining with the no-leakage rule and transformer caching; 8.1.4 ColumnTransformer for heterogeneous columns with remainder drop and fitted feature names

  3. Selection and persistenceHands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning

    Book Chapter 2: saving the model with joblib in Launch, Monitor, and Maintain Your System (printed pp. 100-101) and Exercise 3 (p. 104). Notebook 02 cells: Exercise 3 SelectFromModel with threshold=0.005 in the preparation pipeline; Model persistence using joblib with the production-script pattern

    Treat the 0.005 threshold as a starting point, not an optimum: the notebook reports no gain there. Skip Exercises 1, 2 and 4 here.

2

Focus on

  • Selection inside the pipeline is fit on training folds only. Selecting on all rows before cross-validation picks features with evaluation help.
  • ColumnTransformer drops unlisted columns by default under remainder=drop. Name every kept column or set remainder explicitly.
  • ClusterSimilarity and ratio features are fit state too: their centers and medians come from training rows and must serialize with the pipeline.
  • joblib saves the fitted object, not the build script. Reload in a fresh process and compare predictions before trusting the artifact.
Common mistakes · 3
  • Calling fit_transform on the test set with the same pipeline object. It refits every statistic on evaluation data; call transform only.
  • Tuning the SelectFromModel threshold on the test score. The notebook run at 0.005 shows no gain; tune it under cross-validation or hold it fixed.
  • Saving the model but rebuilding preprocessing by hand in serving. Any median, category list or cluster center that differs silently shifts every prediction.
3

Try it yourself

Closed-book, before checking anything

Closed-book, sketch a ColumnTransformer with a median-plus-scaler numeric path and a most-frequent-plus-one-hot categorical path, state the remainder behavior, and write the three-line joblib save, load and predict-parity check.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Where does SelectFromModel sit relative to the cross-validation split, and what breaks if it sits outside?Answer

    Inside, fit on training folds only. Outside, the selector sees evaluation labels and the error estimate turns optimistic.

  2. 2.A new column appears in serving data. What does ColumnTransformer do with it?Answer

    It ignores it. The column list, including the remainder, is fixed at fit, so the new column is dropped even under remainder=passthrough. That is silent, so add a schema test that fails on unexpected columns.

  3. 3.A joblib reload matches old predictions, but new-category rows differ from training time. Is the artifact broken?Answer

    Not necessarily. handle_unknown=ignore maps new categories to all zeros by design. The parity check is identical predictions on fixed rows plus the declared unknown policy.

5

Practice

You're done when

A fresh process loads your joblib pipeline, reproduces training predictions exactly, transforms unseen categories without refitting, and your threshold choice cites a cross-validated number.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 6 more in the section

Also in this section

  • scikit-learn - decomposition, clustering and outlier detectionscikit-learn · reference

    Check decomposition orientation and solver behavior, cluster API semantics, and the distinction between novelty and outlier detection after the independent tests pass.

  • ISLP - Unsupervised LearningJames, Witten, Hastie, Tibshirani and Taylor · required

    Use Chapter 12 and its Python lab for the PCA derivations (12.2, including the low-rank approximation view and proportion of variance explained) and k-means (12.4.1), plus stability and interpretation limits, beside the notebook route.

  • Deep-ML - unsupervised problemsDeep-ML · support

    Use 17 K-Means Clustering, 19 PCA, 341 Gaussian Mixture Model with EM, 259 DBSCAN and 367 Isolation Forest as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin, including the 367 path-length convention.

  • scikit-learn - preprocessing datascikit-learn · reference

    Read 8.3.1 standardization with the sparse with_mean=False rule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding with handle_unknown, infrequent and sparse_output behavior. Apply after the HOML notebook build works.

  • scikit-learn - imputation of missing valuesscikit-learn · reference

    Read 8.4.2 univariate median and most_frequent strategies, 8.4.6 Marking imputed values with MissingIndicator or add_indicator=True for missingness flags, and 8.4.7 estimators that accept NaN directly. Decide impute-only versus impute-plus-indicator per column.

  • UMAP - basic usage and parametersMcInnes, Healy and the UMAP contributors · reference

    Work the Penguin scaling and fit_transform section and the Digits fit and transform section, then read the parameters page for the n_neighbors local-global tradeoff and min_dist packing. Stay in 2D exploratory views with fixed seeds.