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
ColumnTransformerwith declaredremainderbehavior. - 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
Read
In this order, only the parts listed
0 of 3 done
- 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 andClusterSimilarityon latitude and longitude; Transformation Pipelines withnum_pipeline,cat_pipelineusinghandle_unknown=ignore, and the fullColumnTransformerSkim the KNN-regressor transformer variant in Exercise 4; keep the
ClusterSimilaritypattern and the pipeline assembly. PipelineandColumnTransformercontractsscikit-learn - pipelines and composite estimators8.1.1
Pipelinefitandtransformchaining with the no-leakage rule and transformer caching; 8.1.4ColumnTransformerfor heterogeneous columns withremainderdropand fitted feature names- 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
SelectFromModelwiththreshold=0.005in the preparation pipeline; Model persistence using joblib with the production-script patternTreat the 0.005 threshold as a starting point, not an optimum: the notebook reports no gain there. Skip Exercises 1, 2 and 4 here.
Focus on
- Selection inside the pipeline is fit on training folds only. Selecting on all rows before cross-validation picks features with evaluation help.
ColumnTransformerdrops unlisted columns by default underremainder=drop. Name every kept column or setremainderexplicitly.ClusterSimilarityand 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_transformon the test set with the same pipeline object. It refits every statistic on evaluation data; calltransformonly. - Tuning the
SelectFromModelthreshold 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.
Try it yourself
Closed-book, before checking anything
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.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Where does
SelectFromModelsit relative to the cross-validation split, and what breaks if it sits outside?AnswerInside, fit on training folds only. Outside, the selector sees evaluation labels and the error estimate turns optimistic.
2.A new column appears in serving data. What does
ColumnTransformerdo with it?AnswerIt ignores it. The column list, including the
remainder, is fixed atfit, so the new column is dropped even underremainder=passthrough. That is silent, so add a schema test that fails on unexpected columns.3.A joblib reload matches old predictions, but new-category rows differ from training time. Is the artifact broken?Answer
Not necessarily.
handle_unknown=ignoremaps new categories to all zeros by design. The parity check is identical predictions on fixed rows plus the declared unknown policy.
Practice
- Hands-On Machine Learning Ch2 Exercise 3:
SelectFromModelpipelineExercise solutions, Exercise 3: add
SelectFromModelafter the preparation pipeline and evaluateSweep the threshold under cross-validation starting from 0.005, and keep the fitted pipeline plus the threshold in the saved artifact.
- Hands-On Machine Learning Ch2 Exercise 5: preparation search
Exercise solutions, Exercise 5: explore preparation options with
RandomizedSearchCVRun on a small subsample. Record which preparation choice moves the validation score and keep the search inside the training split.
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
- Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learningAurelien Geron (O'Reilly, 2025) · primary
Read Chapters 7 and 8 and run notebooks 07 and 08 for PCA, k-means, DBSCAN, agglomerative clustering, Gaussian mixtures and anomaly detection. Stop before extended semi-supervised and face-data projects.
- scikit-learn - pipelines and composite estimatorsscikit-learn · reference
Read 8.1.1
Pipelinechaining with the no-leakage rule and transformer caching, and 8.1.4ColumnTransformerfor heterogeneous columns withremainderand fitted-state behavior. Use it to assemble and serialize the feature-selection pipeline.
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=Falserule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding withhandle_unknown, infrequent andsparse_outputbehavior. Apply after the HOML notebook build works. - scikit-learn - imputation of missing valuesscikit-learn · reference
Read 8.4.2 univariate median and
most_frequentstrategies, 8.4.6 Marking imputed values withMissingIndicatororadd_indicator=Truefor missingness flags, and 8.4.7 estimators that acceptNaNdirectly. 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_transformsection and the Digitsfitandtransformsection, then read the parameters page for then_neighborslocal-global tradeoff andmin_distpacking. Stay in 2D exploratory views with fixed seeds.