Sub topic 3
Inspecting and Extending scikit-learn Pipelines
Assume you know Python, pandas, NumPy, train/test splits, and the fit and predict methods. This chapter focuses on inspecting a fitted workflow, adding reusable transformations, and controlling repeated computation.
Inspecting fitted steps and feature names
A fitted Pipeline stores its trained steps in named_steps. Use the step name as a dictionary key:
scaler = model.named_steps["prep"]
classifier = model.named_steps["clf"]If preprocessing is a ColumnTransformer, inspect its output names after fitting:
feature_names = model[:-1].get_feature_names_out()
print(feature_names)The slice model[:-1] selects every step except the final estimator. This is useful because classifiers usually do not provide transformed feature names.
Writing a custom transformer
A custom transformer follows the estimator API. Its fit method learns values from training data and returns self. Its transform method applies the learned operation. TransformerMixin supplies fit_transform.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class Log1pTransformer(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
return self
def transform(self, X):
return np.log1p(X)Keep learned statistics in fit, not in transform. This allows cross-validation to fit the transformer separately in each fold.
Saving and loading a fitted pipeline
Save the complete fitted pipeline so prediction uses the same preprocessing:
import joblib
joblib.dump(model, "model.joblib")
loaded_model = joblib.load("model.joblib")
predictions = loaded_model.predict(X_test)Treat model files as executable content. Load only files you created or trust.
Combining feature sets with FeatureUnion
FeatureUnion runs several transformers on the same input and joins their outputs side by side. It is useful when different transformations create separate feature views.
from sklearn.pipeline import FeatureUnion, Pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
features = FeatureUnion([
("scaled", StandardScaler()),
("squares", PolynomialFeatures(degree=2, include_bias=False)),
])Use ColumnTransformer when branches select different columns. Use FeatureUnion when branches generally consume the same input.
Caching fitted steps during tuning
Repeated searches can refit identical early steps. Give a Pipeline a Memory cache:
from joblib import Memory
from sklearn.pipeline import Pipeline
memory = Memory("pipeline-cache", verbose=0)
cached_pipe = Pipeline([
("features", features),
("model", classifier),
], memory=memory)Caching can speed up tuning, but it uses disk space and may preserve stale results if inputs or code change. Delete the cache when changing transformer implementation.
Exercise
Where should a custom transformer calculate a statistic such as a median?
Show answer
In fit, using only the data provided for that training split. Transform should reuse that fitted statistic.