Reading history

Scikit-learn Pipelines and ColumnTransformer for Mixed Data

6 min read 0 views

Learn scikit-learn Pipeline and ColumnTransformer: imputing missing values, one-hot encoding categories, scaling, avoiding data leakage and saving models.

Real data is messy: some columns are numbers, others are categories like city names, and some values are missing. Each kind needs different preparation before a model can use it. Scikit-learn’s Pipeline and ColumnTransformer package every preparation step and the model into one object. That object can be trained, cross-validated, tuned and saved as a unit, and it automatically prevents a subtle but common mistake called data leakage.

In this lesson you will learn

  • Chaining steps with Pipeline
  • Handling missing values with SimpleImputer
  • Encoding categories with OneHotEncoder
  • Applying different steps to different columns with ColumnTransformer
  • Avoiding data leakage and saving a model with joblib

This lesson builds on Feature Scaling and Data Preprocessing.

Mixed Data in One Pipeline

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

# Loan applications with numbers, categories and missing values
df = pd.DataFrame({
    "age":      [25, 40, None, 35, 52, 23, 44, 31, 60, 29],
    "income":   [30, 85, 40, None, 120, 22, 70, 45, 95, 33],
    "city":     ["Dhaka", "Chattogram", "Dhaka", "Sylhet", "Dhaka",
                 "Khulna", "Sylhet", "Dhaka", "Chattogram", None],
    "employed": ["yes", "yes", "no", "yes", "yes", "no", "yes", "yes", "yes", "no"],
    "approved": [0, 1, 0, 1, 1, 0, 1, 1, 1, 0],
})
X, y = df.drop(columns="approved"), df["approved"]

numeric = ["age", "income"]
categorical = ["city", "employed"]
preprocess = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                      ("scale", StandardScaler())]), numeric),
    ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                      ("onehot", OneHotEncoder(handle_unknown="ignore"))]), categorical),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
model.fit(X, y)

print("Features after preprocessing:")
print(list(model.named_steps["prep"].get_feature_names_out()))

new = pd.DataFrame({"age": [38], "income": [None], "city": ["Rajshahi"], "employed": ["yes"]})
print("New applicant approval probability:", round(model.predict_proba(new)[0, 1], 2))

Output

Features after preprocessing:
['num__age', 'num__income', 'cat__city_Chattogram', 'cat__city_Dhaka', 'cat__city_Khulna', 'cat__city_Sylhet', 'cat__employed_no', 'cat__employed_yes']
New applicant approval probability: 0.72
  • Numeric columns go through a small pipeline: missing values are filled with the column median, then scaled.
  • Categorical columns have missing values filled with the most frequent value, then one-hot encoding turns each category into its own 0/1 column, such as city_Dhaka.
  • ColumnTransformer sends each list of columns to its own pipeline and joins the results side by side. get_feature_names_out shows the 8 final features.
  • The new applicant has a missing income and a city never seen in training, Rajshahi. The imputer fills the income, and handle_unknown="ignore" encodes the unknown city as all zeros instead of crashing.
  • One fit call trains every step in order, and one predict_proba call applies every step to new data.

Preventing Data Leakage

import joblib
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

X, y = load_wine(return_X_y=True)

# WRONG: scaler sees ALL rows (including future test folds) before cross-validation
X_leaky = StandardScaler().fit_transform(X)
leaky = cross_val_score(KNeighborsClassifier(), X_leaky, y, cv=5).mean()

# RIGHT: the pipeline refits the scaler inside each training fold
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
clean = cross_val_score(pipe, X, y, cv=5).mean()
print(f"Scaled outside CV (leaky): {leaky:.3f}")
print(f"Scaled inside pipeline:    {clean:.3f}")

# A fitted pipeline saves and loads as one object
pipe.fit(X, y)
joblib.dump(pipe, "/tmp/wine_model.joblib")
loaded = joblib.load("/tmp/wine_model.joblib")
print("Loaded model predicts:", loaded.predict(X[:3]), "true:", y[:3])

Output

Scaled outside CV (leaky): 0.955
Scaled inside pipeline:    0.949
Loaded model predicts: [0 0 0] true: [0 0 0]
  • Data leakage happens when information from the test data influences training. Fitting the scaler on all rows before cross-validation lets every fold’s scaler see the means of its own test fold.
  • Here the leaky score is only slightly higher, but with steps such as feature selection, imputation or target encoding the gap can be large, giving a falsely optimistic result.
  • Inside a pipeline, cross_val_score refits the scaler on each training fold only, which matches what happens with genuinely new data.
  • joblib.dump saves the fitted pipeline, preprocessing included, in one file. Loading it gives a model ready to receive raw data.

Common Preprocessing Steps

ClassPurpose
SimpleImputerFill missing values (mean, median, most frequent, constant)
StandardScaler / MinMaxScalerPut numeric features on similar scales
OneHotEncoderOne 0/1 column per category (no order)
OrdinalEncoderCategories with a natural order, such as small < medium < large
FunctionTransformerApply your own function, such as a logarithm
make_pipeline / make_column_transformerShortcuts that name the steps automatically

Common Mistakes

  1. Preprocessing the whole dataset before splitting, which leaks test information.
  2. Using pd.get_dummies separately on train and test, which can produce different columns. OneHotEncoder remembers the training categories.
  3. Forgetting handle_unknown="ignore", so a new category crashes prediction.
  4. Saving only the model without its preprocessing, so predictions on raw data are wrong.

Practice Exercises

Exercise 1. Replace logistic regression in the loan pipeline with a random forest.

Show answer
from sklearn.ensemble import RandomForestClassifier
model = Pipeline([("prep", preprocess), ("clf", RandomForestClassifier(random_state=0))])
model.fit(X, y)

Only the last step changes; the preprocessing stays the same. (Trees do not need scaling, but it does no harm.)

Exercise 2. How would you tune the imputer strategy and the logistic regression C together?

Show answer
grid = {
    "prep__num__impute__strategy": ["mean", "median"],
    "clf__C": [0.1, 1, 10],
}
search = GridSearchCV(model, grid, cv=3).fit(X, y)

Nested step names are joined with double underscores.

Frequently Asked Questions

Do I always need a pipeline?

For quick experiments with clean numeric data, not strictly. But as soon as there is preprocessing, cross-validation or deployment, a pipeline prevents leakage and keeps everything together.

Can a pipeline keep pandas column names?

Yes. Call model.set_output(transform="pandas") to make the transformers return DataFrames with readable column names.

Summary

  • A pipeline chains preprocessing and a model into one estimator.
  • ColumnTransformer applies different steps to numeric and categorical columns.
  • Pipelines refit preprocessing inside each fold, preventing leakage.
  • Save the whole pipeline with joblib.

Next: Regression Metrics: MAE, MSE, RMSE and R².

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *