Pipelines, ColumnTransformer and FunctionTransformer
Every technique in this course is a fitted step: it learns something from the training data (medians, means, categories, selected columns, components) and then applies it to new data. Chaining them by hand, fit_transform here, transform there, for training, validation, test and production separately, is where leaks and mismatches creep in. A scikit-learn pipeline turns the whole chain into one object with one fit and one predict. That object is what you cross-validate, tune, save and deploy. The first steps with Pipeline and ColumnTransformer are in ML Pipelines and ML ColumnTransformer; this lesson puts the whole toolkit together.
A pipeline from scratch
The idea is small enough to write in a few lines: fit calls fit_transform on every step except the last, passing the result on; predict calls only transform on them.
import numpy as np
class MiniPipeline:
def __init__(self, steps):
self.steps = steps
def fit(self, X, y):
for _, step in self.steps[:-1]:
X = step.fit(X, y).transform(X) # learn on training data, then apply
self.steps[-1][1].fit(X, y)
return self
def predict(self, X):
for _, step in self.steps[:-1]:
X = step.transform(X) # only apply: nothing is learned here
return self.steps[-1][1].predict(X)
class Standardise:
def fit(self, X, y=None):
self.mean_, self.std_ = X.mean(0), X.std(0)
return self
def transform(self, X):
return (X - self.mean_) / self.std_
class NearestCentroid:
def fit(self, X, y):
self.classes_ = np.unique(y)
self.centroids_ = np.array([X[y == c].mean(0) for c in self.classes_])
return self
def predict(self, X):
d = ((X[:, None, :] - self.centroids_[None]) ** 2).sum(-1)
return self.classes_[d.argmin(1)]
rng = np.random.default_rng(0)
X_tr = np.column_stack([rng.normal(50, 10, 40), rng.normal(0.5, 0.1, 40)])
y_tr = (X_tr[:, 1] > 0.5).astype(int)
X_new = np.array([[48.0, 0.62], [55.0, 0.38]])
pipe = MiniPipeline([("scale", Standardise()), ("model", NearestCentroid())]).fit(X_tr, y_tr)
print("means learned on training data:", np.round(pipe.steps[0][1].mean_, 3).tolist())
print("predictions for new rows:", pipe.predict(X_new).tolist())means learned on training data: [49.396, 0.53]
predictions for new rows: [1, 0]
scikit-learn's Pipeline does the same, plus parameter access by name, cloning for cross-validation, feature names and caching.
ColumnTransformer: different steps for different columns
Real tables mix numbers, categories and text, and each kind needs its own preparation. A ColumnTransformer sends each group of columns through its own pipeline and glues the results side by side:
FunctionTransformer wraps a plain function as a step. A stateless function such as np.log1p learns nothing, so it is safe anywhere; wrapping it keeps the whole recipe inside the pipeline, so production applies exactly the same transformation. Here is the diagram as code, on a small messy customer table:
import numpy as np
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, make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 400
df = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(45_000, 15_000, n).round(-2),
"city": rng.choice(["Hanoi", "Hue", "Da Nang", "Can Tho"], n),
"plan": rng.choice(["basic", "plus", "pro"], n, p=[0.6, 0.3, 0.1]),
"spend": rng.lognormal(4, 1.2, n).round(2),
})
df.loc[rng.choice(n, 30, replace=False), "income"] = np.nan
df.loc[rng.choice(n, 20, replace=False), "city"] = np.nan
y = ((df["plan"] != "basic") & (df["spend"] > 60) | (df["age"] < 25)).astype(int).to_numpy()
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", make_pipeline(SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore", sparse_output=False)), ["city", "plan"]),
("log", make_pipeline(FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
StandardScaler()), ["spend"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression(max_iter=1000))])
model.fit(df, y)
names = model[:-1].get_feature_names_out()
print(len(names), "features:", names.tolist())
print("training accuracy:", round(model.score(df, y), 3))
new = pd.DataFrame({"age": [22.0], "income": [np.nan], "city": ["Vinh"], "plan": ["pro"], "spend": [120.0]})
print("new customer (unseen city, missing income):", model.predict(new).tolist())10 features: ['num__age', 'num__income', 'cat__city_Can Tho', 'cat__city_Da Nang', 'cat__city_Hanoi', 'cat__city_Hue', 'cat__plan_basic', 'cat__plan_plus', 'cat__plan_pro', 'log__spend']
training accuracy: 0.85
new customer (unseen city, missing income): [1]
The five raw columns become 10 features: two scaled numbers, four city columns, three plan columns and the scaled log of spend, each named after the branch that produced it. The 0.85 is training accuracy, printed only to show that the pipeline fits; an honest estimate needs cross-validation, below. The new customer comes from a city never seen in training and has no income: the imputer fills the income with the training median, the encoder turns "Vinh" into all-zero city columns, and the pipeline still predicts. One fit, one predict, no step forgotten.
Readable output with set_output
By default transformers return NumPy arrays, and column names are lost. set_output(transform="pandas") makes every step return a DataFrame with the names from get_feature_names_out, which makes debugging much easier:
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import make_pipeline
train = pd.DataFrame({"size": [50.0, 80.0, np.nan, 120.0], "kind": ["flat", "house", "flat", "house"]})
test = pd.DataFrame({"size": [np.nan, 65.0], "kind": ["house", "studio"]})
ct = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["size"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["kind"]),
]).set_output(transform="pandas")
print(ct.fit_transform(train).round(3))
print(ct.transform(test).round(3))
print("median learned on training rows only:", ct.named_transformers_["num"][0].statistics_.tolist()) num__size cat__kind_flat cat__kind_house
0 -1.307 1.0 0.0
1 -0.101 0.0 1.0
2 -0.101 1.0 0.0
3 1.508 0.0 1.0
num__size cat__kind_flat cat__kind_house
0 -0.101 0.0 1.0
1 -0.704 0.0 0.0
median learned on training rows only: [80.0]
The training sizes 50, 80 and 120 have median 80, which fills the missing size in both tables; scaled, it becomes -0.101 in each, because the mean and standard deviation also come from training. The test house is encoded like any house, and the unknown "studio" gets zeros in both kind columns instead of an error.
Cross-validating and tuning the whole pipeline
Because the pipeline is one estimator, cross_val_score refits every step in every fold, and GridSearchCV can tune preprocessing choices and model hyperparameters together. Parameters are addressed by step names joined with double underscores: prep__num__simpleimputer__strategy is the strategy of the simpleimputer step inside the num pipeline of the prep ColumnTransformer.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 400
df = pd.DataFrame({"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(45_000, 15_000, n).round(-2),
"plan": rng.choice(["basic", "plus", "pro"], n, p=[0.6, 0.3, 0.1])})
y = ((df["plan"] != "basic") & (df["income"] > 40_000) | (df["age"] < 25)).astype(int).to_numpy()
df.loc[rng.choice(n, 40, replace=False), "income"] = np.nan
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"])])
pipe = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
cv = StratifiedKFold(5, shuffle=True, random_state=0)
print("parameter names:", [k for k in pipe.get_params() if k.endswith("strategy") or k == "clf__C"])
print(f"5-fold CV accuracy, defaults: {cross_val_score(pipe, df, y, cv=cv).mean():.3f}")
grid = {"prep__num__simpleimputer__strategy": ["mean", "median"], "clf__C": [0.1, 1, 10]}
search = GridSearchCV(pipe, grid, cv=cv).fit(df, y)
print("best:", search.best_params_, f"CV {search.best_score_:.3f}")parameter names: ['prep__num__simpleimputer__strategy', 'clf__C']
5-fold CV accuracy, defaults: 0.793
best: {'clf__C': 0.1, 'prep__num__simpleimputer__strategy': 'mean'} CV 0.800
With default settings the pipeline scores 0.793 in 5-fold stratified cross-validation (400 rows); the search over two imputation strategies and three values of C picks mean imputation with C = 0.1 at 0.800. Here the choices barely matter, which is itself useful to know. Remember from Nested Cross-Validation that best_score_ is slightly optimistic; for a final number, score the chosen pipeline on a held-out test set or nest the search. The fitted search.best_estimator_ is the complete recipe, preprocessing included: saving it with joblib.dump and loading it in production guarantees that new data goes through exactly the same steps (Saving & Loading Models).
Pitfalls
- Preprocessing outside the pipeline "just for convenience": every fitted step belongs inside, or cross-validation leaks.
handle_unknown="error"(the default) in production: a new category crashes the service. Use"ignore"or"infrequent_if_exist".- Stateful logic in a FunctionTransformer: a function that computes a mean from its input learns from whatever data it is given, test data included. Write a proper transformer class with
fitandtransforminstead. - Column order assumptions: select columns by name in the ColumnTransformer, and keep
remainder="drop"(the default) so unexpected new columns are ignored rather than passed to the model.
Practice
- Why is
FunctionTransformer(np.log1p)safe to fit on any data, butFunctionTransformer(lambda X: X / X.max(axis=0))is not?
Answer
np.log1p is applied row by row with no information from other rows. The lambda divides by the column maximum of whatever data it receives, so at test time it uses the test maximum (a leak and a mismatch: the same value gets a different feature depending on the batch). Use MaxAbsScaler or MinMaxScaler, which learn the maximum during fit on training data.
- Write the parameter name that sets the
Cof anSVCstep namedsvmand then_componentsof aPCAstep namedpcainPipeline([("prep", ...), ("pca", PCA()), ("svm", SVC())]).
Answer
svm__C and pca__n_components.
Test yourself
What does a pipeline do with its preprocessing steps when you call predict?
- Refits them on the new data
- Applies them with
transformonly, using what was learned infit - Skips them
- Fits them on the training data again
Which tool applies different preprocessing to different columns?
- FunctionTransformer
- ColumnTransformer
- make_pipeline
- GridSearchCV
What does set_output(transform="pandas") change?
- The model's accuracy
- Transformers return DataFrames with feature names instead of arrays
- It saves the pipeline to disk
- It enables GPU training
Why cross-validate the whole pipeline rather than the model alone?
- It is faster
- Every fitted preprocessing step is then refitted on each training fold, so nothing leaks
- Pipelines cannot be fitted otherwise
- It increases the training data