DSCI 571 Lecture 4: Preprocessing, Pipelines, and Column Transformers

Varada Kolhatkar

Focus on the breath!

Announcements

Supervised ML workflow

%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'sans-serif', 'fontSize': '32px', 'primaryColor': '#ffffff', 'primaryTextColor': '#17212b', 'primaryBorderColor': '#419599', 'lineColor': '#52616b'}}}%%
flowchart LR
    A["Define task<br/>Collect data"] --> B["Split data"]
    B --> C["Explore <br/> training data <br/> Prepare features"]
    C --> D["Compare <br>pipelines<br/>with CV"]
    D --> E["Refit <br/> chosen pipeline<br/>Evaluate once"]
    B -->|Reserve test set| E
    E --> F["Deploy<br/>Monitor"]
    style C fill:#d9eded,stroke:#287f83,stroke-width:3px

Next two lectures: how do we get data into a useful representation?

iClicker: where does the time go?

Take a guess: how much of an ML project’s time might go into data preparation and transformation?

  1. Less than 20%
  2. 20–40%
  3. More than 40%
  4. None; most time goes into model building

Often a substantial share: understanding, cleaning, and transforming data takes time. The exact proportion varies by project.

Inspired by Google’s ML Crash Course

Preprocessing motivation: example

Suppose we want to match a student with a compatible roommate using two features:

  • Preferred quiet hours per week.
  • Number of followers on social media.

For this example, we measure similarity using Euclidean distance.

Preprocessing motivation: example

  • Our student prefers 40 quiet hours per week and has 25,000 followers.
Candidate Quiet hours/week Followers Euclidean distance calculation Distance
A 35 40,000 \(\sqrt{5^2 + 15{,}000^2}\) 15,000.00
B 37 30,000 \(\sqrt{3^2 + 5{,}000^2}\) 5,000.00
C 40 50,000 \(\sqrt{0^2 + 25{,}000^2}\) 25,000.00
D 10 25,000 \(\sqrt{30^2 + 0^2}\) 30.00

Based on the distances, the two nearest neighbors (2-NN) are:

  • Candidate D (Distance: 30.00)
  • Candidate B (Distance: 5,000.00)

What’s the problem here?

Which models are affected?

In the age-and-followers example, which models are sensitive to the relative scales of the two features? Why?

  • Decision trees
  • \(k\)-NN
  • RBF SVM

\(k\)-NN and RBF SVM use distances, so feature scales affect their neighbours or similarities.

Decision trees split on one feature at a time; changing units allows an equivalent split threshold.

Why data representation matters

Models operate on the representation we give them.

  • Units: age in years \(\to\) months changes distances without changing the people.
  • Scales: ages might range from 18–60, but follower counts from 10 to millions. Differences in follower counts can dominate distances.
  • Missing entries: someone leaves their age blank (age = NaN). How do we calculate their distance?
  • Category codes: suppose we add a favourite hobby: hiking = 0, reading = 1, gaming = 2. Why should hiking be “closer” to reading than gaming?

Today’s big questions

  • What representation does the model need?
  • What do transformations learn, and which data may they learn from?
  • How do we combine preprocessing and prediction safely?
  • How does ColumnTransformer combine different feature groups?

Class demo: restaurant survey responses

Open the preprocessing demo

Task: infer a respondent’s like / dislike label from their completed survey.

As we work, watch for:

  1. What does each transformation change?
  2. What does fit learn?
  3. Which rows are allowed to influence that learning?

Recap: choosing transformations

Problem Demo features Transformation
Missing values price, food_type, noise_level Impute with a training median or most frequent value
Different scales age, n_people, price Standardize numeric features
Unordered categories food_type, north_america One-hot encode
Ordered categories noise_level Ordinally encode with an explicit order

Choose the representation to match the meaning of the feature.

Transformers and predictive estimators

Transformer Predictive estimator
Purpose Change feature representation Predict a target
Learn fit(X) fit(X, y)
Apply transform(X) predict(X)
Examples Imputer, scaler, encoder \(k\)-NN, SVC

Both are estimators: both implement fit.

fit_transform fits and transforms the same data. On unseen data, transform only.

A pipeline combines preprocessing and prediction

%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'sans-serif', 'fontSize': '32px', 'primaryColor': '#ffffff', 'primaryTextColor': '#17212b', 'primaryBorderColor': '#419599', 'lineColor': '#52616b'}}}%%
flowchart LR
    A["Raw numeric <br>features"] --> B["Imputer"] --> C["Scaler"] --> D["KNN"] --> E["Predictions"]
    style B fill:#d9eded,stroke:#287f83
    style C fill:#d9eded,stroke:#287f83

During training On unseen data
Imputer: fit and transform Imputer: transform
Scaler: fit and transform Scaler: transform
KNN: fit with labels KNN: predict

A sequence of preprocessing steps followed by a predictive estimator.

The golden rule in preprocessing

Never call fit on the validation portion for preprocessing or the model.

  • Learn medians, scales, and categories from that fold’s training rows.
  • Apply the fitted transformations to its validation rows.
  • Pass the whole pipeline and raw features to cross-validation.

Keeping the final test set separate is necessary, but does not prevent leakage between CV folds.

Back to the full workflow

%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'sans-serif', 'fontSize': '32px', 'primaryColor': '#ffffff', 'primaryTextColor': '#17212b', 'primaryBorderColor': '#419599', 'lineColor': '#52616b'}}}%%
flowchart LR
    A["Define task<br/>Collect data"] --> B["Split data"]
    B --> C["Explore <br/> training data <br/> Prepare features"]
    C --> D["Compare <br>pipelines<br/>with CV"]
    D --> E["Refit <br/> chosen pipeline<br/>Evaluate once"]
    B -->|Reserve test set| E
    E --> F["Deploy<br/>Monitor"]
    style C fill:#d9eded,stroke:#287f83,stroke-width:3px

Inside each CV fold: raw features \(\to\) fitted preprocessing \(\to\) fitted classifier.

Cross-validate the whole pipeline: each fold fits preprocessing and the model using only its training rows. This keeps validation data out of fit and preserves the golden rule.

Why ColumnTransformer?

In the demo, we trained on feature groups separately:

  • Numeric: impute \(\to\) scale
  • Categorical: impute \(\to\) one-hot encode
  • Ordinal: impute \(\to\) encode with a specified order

How do we combine these transformed columns for one classifier?

ColumnTransformer applies different transformations to selected columns and joins the results into one feature matrix.

Different columns need different transformations

Feature group Columns Preprocessing
Numeric age, n_people, price Impute \(\to\) scale
Unordered categories food_type, north_america Impute \(\to\) one-hot encode
Ordered category noise_level Impute \(\to\) ordinal encode

How do we combine these into one feature matrix?

ColumnTransformer combines feature groups

Different columns \(\to\) their own transformations \(\to\) one feature matrix.

Build the numeric and categorical branches

from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder

numeric_pipe = make_pipeline(
    SimpleImputer(strategy="median"),
    StandardScaler(),
)

categorical_pipe = make_pipeline(
    SimpleImputer(strategy="most_frequent"),
    OneHotEncoder(handle_unknown="ignore"),
)

Each branch is a sequence of transformations for one feature group.

Build the ordinal branch

from sklearn.preprocessing import OrdinalEncoder

noise_order = ["no music", "low", "medium", "high", "crazy loud"]

ordinal_pipe = make_pipeline(
    SimpleImputer(strategy="most_frequent"),
    OrdinalEncoder(categories=[noise_order]),
)

We supply the meaningful order of noise levels.

ColumnTransformer syntax

from sklearn.compose import ColumnTransformer

preprocessor = ColumnTransformer([
    ("num", numeric_pipe, ["age", "n_people", "price"]),
    ("cat", categorical_pipe, ["food_type", "north_america"]),
    ("ord", ordinal_pipe, ["noise_level"]),
], remainder="drop")

Each tuple contains (name, transformer, columns).

  • Name: a label for the branch.
  • Transformer: one transformer or a preprocessing pipeline.
  • Columns: the input columns for that branch.

The shortcut: make_column_transformer

from sklearn.compose import make_column_transformer

preprocessor = make_column_transformer(
    (numeric_pipe, ["age", "n_people", "price"]),
    (categorical_pipe, ["food_type", "north_america"]),
    (ordinal_pipe, ["noise_level"]),
    remainder="drop",
)

Each tuple contains (transformer, columns); names are generated for you.

We’ll primarily use this constructor.

What comes out of a column transformer?

  • Same rows: each output row corresponds to the same input respondent.
  • Output order: numeric block, categorical block, then ordinal block in our example.
  • Feature count: may change; one-hot encoding can add columns.
  • Unlisted columns: dropped by default (remainder="drop").
  • Output format: may be dense or sparse, depending on the transformations and sparsity.

After fitting, inspect the output names with:

preprocessor.fit(X_train, y_train)
preprocessor.get_feature_names_out()

Put preprocessing inside the prediction pipeline

from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score

pipe = make_pipeline(
    preprocessor, # column transformer object
    KNeighborsClassifier(),
)

scores = cross_val_score(pipe, X_train, y_train, cv=5)

Raw survey columns \(\to\) column transformer \(\to\) KNN \(\to\) predictions

Cross-validation fits every branch and the classifier within each fold.

Class demo: combine the survey features

Open the preprocessing demo

Task: infer a respondent’s like / dislike label from their completed survey.

As we build the column transformer:

  1. Trace which columns enter each branch.
  2. Inspect the transformed feature names and shape.
  3. Cross-validate the complete prediction pipeline.

Summary

  • Representation: handle missing values, feature scales, and categories according to what the features mean.

  • Learning: fit transformations using only the available training rows, including within each CV fold.

  • Combination: a pipeline keeps preprocessing and prediction together; cross-validate the whole procedure.

  • Feature groups: use ColumnTransformer to apply different transformations to different columns.

Next lecture: more preprocessing choices and text features.

DSCI 571 course notes

Exit question

A colleague imputes and scales all training rows, then cross-validates a KNN classifier on the transformed matrix.

“The test set is untouched, so there’s no leakage.”

Do you agree? What would you change?