7 routes42 sections324 units

Unit 4.1 · about 4 h

152 / 324

Numeric transforms and categorical encoding

Every estimator downstream sees the transformed geometry, not the raw table. A scaler fit on the wrong rows or an encoder that errors on new categories breaks serving before any model runs.

  • implement

You can now

  • Build a leakage-safe numeric and categorical preprocessing path with fitted state, unknown-category behavior and schema tests.
  • Choose scaling, clipping and imputation for skewed, heavy-tailed and missing features and state what each choice hides.
  • Keep sparse categorical output sparse through the pipeline and densify only where the estimator requires it.

Covers

  • Numeric transforms, scaling, clipping and missingness indicators
  • Categorical encoding, unknown categories and sparse features

Study, in this order

3 steps

  1. End-to-end preprocessing: cleaning, encoding and scaling
    Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning

    Book Chapter 2: Clean the Data, Handling Text and Categorical Attributes, and Feature Scaling and Transformation (printed pp. 70-81). Notebook 02 cells: Prepare the Data for Machine Learning Algorithms: Data Cleaning with SimpleImputer median and most_frequent; Handling Text and Categorical Attributes with OneHotEncoder and the sparse_output note; Feature Scaling with MinMaxScaler, StandardScaler, log transform and percentile flattening; outlier dropping with IsolationForest

    Depth · Stop before Custom Transformers. Ratio, RBF-similarity and cluster-similarity features belong to the next unit.

  2. Scaling, encoding and sparse behavior
    scikit-learn - preprocessing data

    8.3.1 standardization with the with_mean=False sparse rule and MaxAbsScaler; 8.3.1.3 RobustScaler for outlier-heavy features; 8.3.4 OneHotEncoder handle_unknown ignore versus error, infrequent handling and sparse_output

  3. Missing-value strategies and indicators
    scikit-learn - imputation of missing values

    8.4.2 univariate median and most_frequent strategies; 8.4.6 Marking imputed values: MissingIndicator, or add_indicator=True on the imputer, to keep a missingness flag beside the imputed value; 8.4.7 which estimators accept NaN directly

Focus on

  • Fit every statistic on training rows only, then transform the rest. Refitting on evaluation rows leaks their distribution into the features.
  • OneHotEncoder with handle_unknown=ignore writes a new category as all zeros; with handle_unknown=error it raises. Pick one before serving.
  • StandardScaler centers, so it densifies sparse input unless with_mean=False. MaxAbsScaler preserves sparsity.
  • A missingness indicator keeps the fact of missingness after imputation fills the value. Dropping the flag assumes missingness carries no signal.

Reproduce closed-book

Closed-book, build a two-column pipeline on five training rows: median-impute and standardize a numeric column, one-hot encode a categorical column with handle_unknown=ignore. Transform two new rows, one with an unseen category and one with a missing number, and write the exact output rows including the all-zeros encoding.

Traps

  • Fitting the imputer or scaler on the full data before splitting. Validation scores then reuse evaluation statistics.
  • Setting sparse_output=False on a high-cardinality encoder inside a pipeline. Memory grows with rows times categories; keep sparse until an estimator needs dense.
  • Reading the percentile-flattened income as deleting outliers. It remaps tails to fixed bins; the IsolationForest drop in the same notebook is a separate commented-out choice.

Practice

Hands-On Machine Learning Ch2 Exercise 6: `StandardScalerClone`

Exercise solutions, Exercise 6: re-implement StandardScalerClone with inverse_transform, feature_names_in_ and get_feature_names_out, then check_estimator

Implement in your own repository. check_estimator must pass and inverse_transform must round-trip within floating-point tolerance.

Self-test

  1. A scaler fit on all 10,000 rows gives mean 5.2; fit on the 8,000 training rows gives 5.0. Which one goes into the pipeline, and why?

  2. OneHotEncoder(handle_unknown=ignore) trained on [a, b] sees [c]. What row does it emit, and what does inverse_transform return for it?

  3. Why does StandardScaler on a CSR matrix raise unless with_mean=False?

  4. When does an imputed column need a companion indicator column?

Completion criterion

Stop when

Your clone passes check_estimator, round-trips five rows through fit_transform and inverse_transform, and your pipeline transforms unseen categories and missing values without refitting.

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

Leads to

Resources for this unit

  • Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning
    Aurelien Geron (O'Reilly, 2025)primarycourse
    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 - preprocessing data
    scikit-learnreferencereference
    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 values
    scikit-learnreferencereference
    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.

Also in this section

  • scikit-learn - decomposition, clustering and outlier detection
    scikit-learnreferencereference
    Check decomposition orientation and solver behavior, cluster API semantics, and the distinction between novelty and outlier detection after the independent tests pass.
  • ISLP - Unsupervised Learning
    James, Witten, Hastie, Tibshirani and Taylorrequiredtheory
    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 problems
    Deep-MLsupportpractice
    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 - pipelines and composite estimators
    scikit-learnreferencereference
    Read 8.1.1 Pipeline chaining with the no-leakage rule and transformer caching, and 8.1.4 ColumnTransformer for heterogeneous columns with remainder and fitted-state behavior. Use it to assemble and serialize the feature-selection pipeline.
  • UMAP - basic usage and parameters
    McInnes, Healy and the UMAP contributorsreferencereference
    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.

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