Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 108/ 160
06. Feature Engineering & Model Evaluation

Scikit-Learn Pipelines & ColumnTransformer

Compose leak-safe preprocessing + model steps with Pipelines and ColumnTransformer.

IntermediatePipeline · Columns · Leak-safe3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A pipeline bundles all the data-cleaning steps and the model into one package so the same steps run the same way on training and new data.

Think of it like…

An assembly line with stations for cleaning, sizing and packaging: every item goes through the same stations in the same order, the settings of each station are calibrated on the training batch, and the whole line ships as a single machine.

Where you’ve seen it

A churn dataset has numeric columns (tenure, monthly_charge, tickets), categoricals (plan, region) and an ID column. The ColumnTransformer imputes the median and scales the numeric columns, imputes the most frequent value and one-hot encodes the categoricals (handle_unknown="ignore"), and drops the ID (remainder="drop"). The final pipeline is Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))]). With 5-fold cross-validation the pipeline refits the imputer, scaler and encoder on each training fold (5 times) and transforms each validation fold with those parameters: AUC 0.781 ± 0.012. The earlier notebook that scaled and imputed on all data before cross-validation showed 0.793, a small inflation here but 6 points on a variant that also target-encoded region outside the loop. GridSearchCV tunes model__C and prep__num__imputer__strategy in one search, the best pipeline is saved with joblib.dump, and the API loads it and calls predict_proba on raw rows, so the serving code contains no preprocessing logic. set_output(transform="pandas") and get_feature_names_out() keep column names for debugging and SHAP.

Words you’ll hear

Pipeline
A sequence of transformers followed by an estimator, fitted as one unit.
ColumnTransformer
Applies different transformers to different columns and concatenates results.
Leak-safe
Preprocessing statistics are learned from training data only, per fold.
Parameter grid names
step__param naming to tune any step through the pipeline.

Visual diagram

Loading interactive diagram

Theory & deep dive

Building pipelines and column transformers

A Pipeline is a list of (name, estimator) pairs where all but the last implement fit and transform, and the last is the model. Calling pipe.fit(X, y) fits each step in order on the data transformed by the previous ones; pipe.predict(X_new) pushes new data through the already-fitted steps. make_pipeline(StandardScaler(), SVC()) auto-names steps. A ColumnTransformer takes (name, transformer, columns) triples; select columns by name, index, boolean mask or make_column_selector(dtype_include="number"); remainder controls unspecified columns ("drop" or "passthrough"). Nesting works: each branch can itself be a pipeline (impute then scale), which is the standard recipe for mixed-type tabular data.

Practical features: set_output(transform="pandas") returns DataFrames with column names; get_feature_names_out() lists the output features (essential for coefficients and SHAP); FunctionTransformer wraps custom functions (log1p, date parts); custom transformers subclass BaseEstimator and TransformerMixin with fit and transform; Pipeline(memory=...) caches expensive steps during searches; imblearn.pipeline.Pipeline allows resampling steps (SMOTE) that apply only during fit. Always set handle_unknown for encoders and think about column order and presence: the pipeline expects the same column names at prediction time, so validate the input schema in production.

A standard tabular pipeline

num = make_pipeline(SimpleImputer(strategy="median"), StandardScaler()); cat = make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore")); prep = ColumnTransformer([("num", num, num_cols), ("cat", cat, cat_cols)], remainder="drop"); pipe = Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))])

Key takeaway: Compose per-column preprocessing with ColumnTransformer, chain it with the model in a Pipeline and keep names and schemas explicit.

Leak-safe evaluation, tuning and deployment

Pass the whole pipeline to cross_val_score, cross_validate or GridSearchCV/RandomizedSearchCV: each fold fits the imputer, scaler and encoder on its own training rows (five times for five folds) and transforms the validation rows with those parameters, which is the definition of leak-safe. Tune preprocessing and model together using step-prefixed names: {"model__C": [0.1, 1, 10], "prep__num__imputer__strategy": ["mean", "median"]}; use passthrough or swap whole steps ("prep__num__scaler": [StandardScaler(), RobustScaler()]) to compare options. When a step uses the target (target encoding, supervised feature selection, SMOTE), keeping it inside the pipeline is the only way to evaluate honestly. Use GroupKFold or TimeSeriesSplit as the cv argument when data is grouped or time-ordered.

For deployment, persist the fitted pipeline (joblib.dump(pipe, "model.joblib"), with pinned library versions) and load it in the service: the API passes raw rows (a DataFrame with the expected columns) and gets predictions, so training and serving can't drift apart. Add input validation (schema, dtypes, ranges), version the pipeline with the data and code that produced it, and monitor input distributions. Common mistakes: calling fit_transform on the test set; fitting a transformer outside the pipeline and then cross-validating; using ColumnTransformer with wrong column names after renaming; forgetting handle_unknown; hard-coding column positions that change; and ignoring that some steps (SMOTE) shouldn't run at prediction time. Pipelines solve these by construction when used consistently.

Tuning across steps

GridSearchCV(pipe, {"model__C": [0.1, 1, 10], "prep__num__scaler": [StandardScaler(), RobustScaler()]}, cv=5, scoring="roc_auc") evaluates 3 × 2 = 6 configurations with 5 folds each (30 pipeline fits), refitting preprocessing inside every fold.

Key takeaway: Cross-validate and tune the whole pipeline, save one artifact for serving and validate the input schema.

How it works, step by step

Step 1 of 4
Analyst

1. Separate columns by type

Define numeric, categorical, date and drop lists, or use make_column_selector.

3 numeric · 2 categorical · 1 ID
Key numbers at this step
Names
as the source of truth

When to use it & trade-offs

What it is

A scikit-learn Pipeline chains preprocessing steps and a final estimator into one object with fit, predict and transform methods, so every step is fitted on the training data only and applied consistently to new data. A ColumnTransformer applies different transformers to different columns (impute and scale numeric columns, impute and one-hot encode categoricals, pass through or drop the rest) and concatenates the outputs. Together they give a leak-safe, reproducible, deployable workflow: cross-validation and hyperparameter search treat the whole chain as the model, you tune preprocessing parameters with the same API (model__C, prep__num__imputer__strategy) and a single saved object contains everything production needs.

Why it matters: Most evaluation errors in tabular ML come from preprocessing done outside the validation loop (scaling or imputing on all data, encoding with the target, selecting features before splitting) and most production bugs from mismatched preprocessing between training and serving. Pipelines make the right thing the default: one object, one fit, one predict, no manual state to forget. They also make experiments cleaner (change a step, rerun) and code reviewable.

When to reach for it

  • Any tabular modelling project
  • Hyperparameter searches that include preprocessing choices
  • Deploying models with consistent preprocessing

When to avoid or be careful

  • Fitting transformers on all data before cross-validation
  • Calling fit_transform on test data
  • Serving code that re-implements preprocessing by hand

Preprocessing workflows

Pipeline plus ColumnTransformer
Best for: Mixed-type tabular data and leak-safe evaluation

Strengths: Single object; refits per fold; deployable.

Watch out: Slight learning curve; naming conventions.

Manual preprocessing in notebooks
Best for: Quick exploration only

Strengths: Flexible and fast to write.

Watch out: Leakage and training-serving mismatch risks.

Feature store or SQL transformations
Best for: Shared features across many models

Strengths: Consistent and reusable at scale.

Watch out: Infrastructure effort; still needs model-side pipeline.

Interview signals & numbers to know

When this topic comes up

  • “Different results in production”
  • ColumnTransformer
  • make_pipeline
  • model__C naming
  • joblib persistence

Benchmarks & rules of thumb

5 -
times the preprocessing is refit in 5-fold CV
3 × 2 × 5 = 30 -
fits for a 6-configuration grid with 5 folds
0.793 vs 0.781 -
AUC with preprocessing outside versus inside the CV loop

Common mistakes & follow-ups

Common interview mistakes

  • Defining transformers outside the pipeline and reusing a fitted one in each fold.
  • Forgetting handle_unknown on one-hot encoding.
  • Renaming columns after fitting and breaking the transformer.

Likely interviewer follow-ups

  • Why use a Pipeline for cross-validation?
  • How does ColumnTransformer handle different column types?
  • How do you tune preprocessing parameters?
Interview tip: Say "the whole pipeline is the model". It captures leak-safe evaluation and deployment in one sentence.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Scikit-Learn Pipelines & ColumnTransformer with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Feature Selection (Filter, Wrapper, Embedded)
Next topic
Handling Imbalanced Datasets (SMOTE, Class Weights)