Unit 1 of 8 · about 4 hours · implement

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.

You'll be able to

  • 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 indicatorsCategorical encoding, unknown categories and sparse features
1

Read

In this order, only the parts listed

0 of 3 done

  1. End-to-end preprocessing: cleaning, encoding and scalingHands-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

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

  2. Scaling, encoding and sparse behaviorscikit-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 indicatorsscikit-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

2

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.
Common mistakes · 3
  • 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.
3

Try it yourself

Closed-book, before checking anything

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

Quiz yourself

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

0 got · 0 missed

  1. 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?Answer

    The training-only 5.0. The full-data mean carries evaluation rows into every transformed training value.

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

    It emits [0, 0]. inverse_transform maps all zeros back to None when no category was dropped. Verified with scikit-learn 1.9.

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

    Centering subtracts the mean from every entry including stored zeros, which would densify the matrix. With with_mean=False only scaling applies and sparsity survives.

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

    When missingness itself predicts the target, for example sensors that fail under load. The indicator keeps that signal after the value is filled.

5

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.

You're done 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.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 5 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 - 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.

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 - pipelines and composite estimatorsscikit-learn · reference

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