Sub topic 9
Using your estimator in Pipeline and ColumnTransformer
This chapter assumes you can write a class with BaseEstimator and TransformerMixin. It also assumes your estimators store constructor arguments unchanged, end learned attributes with _, and validate input with check_array and check_is_fitted. You should have used Pipeline and ColumnTransformer with built-in estimators.
A custom estimator is useful once it fits into a larger workflow. Pipeline and ColumnTransformer call your methods in a fixed order and pass data in specific shapes. Knowing those calls explains most integration errors.
What Pipeline calls on your steps
A Pipeline is a list of (name, estimator) pairs. All steps except the last must be transformers. The last step can be anything, and it is usually a predictor.
The calls are:
pipe.fit(X, y)callsfit_transform(X, y)on each intermediate step, in order. The output of one step is the input of the next. The final step getsfit(X_transformed, y).pipe.predict(X)callstransform(X)on each intermediate step, thenpredicton the final step.pipe.score(X, y)transforms the same way, then calls the final step'sscore.
Three consequences follow for your transformer.
fitmust accepty. The pipeline always passesy, so use the signaturefit(self, X, y=None)even if you ignore it.fit_transformcomes from the mixin.TransformerMixindefines it asfit(X, y).transform(X). Override it only when training-time output must differ fromtransformoutput. Target encoders are the usual case, because they need out-of-fold values to avoid leakage.transformmust return a 2D array with the same number of rows as its input. Pipelines cannot drop or add samples. Returning a 1D array is a frequent mistake and fails at the next step.
A first pipeline
This example defines a compact QuantileClipper, as in the earlier chapters. The pipeline clips outliers, scales the result, and classifies.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.utils.validation import check_array, check_is_fitted
class QuantileClipper(TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
X = check_array(X)
self.lower_ = np.quantile(X, self.lower, axis=0)
self.upper_ = np.quantile(X, self.upper, axis=0)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return np.clip(X, self.lower_, self.upper_)
X, y = make_classification(n_samples=200, n_features=4, random_state=0)
pipe = Pipeline([
("clip", QuantileClipper(lower=0.05, upper=0.95)),
("scale", StandardScaler()),
("clf", LogisticRegression()),
])
pipe.fit(X, y)
print(pipe.score(X, y))
print(pipe.named_steps["clip"].lower_)pipe.named_steps["clip"] returns the fitted step, so lower_ is available after fit. make_pipeline(QuantileClipper(), StandardScaler(), LogisticRegression()) builds the same pipeline and names each step with the lowercased class name, here quantileclipper. Use explicit names when you plan to tune parameters, because the names appear in the parameter paths.
Reaching parameters through the pipeline
Parameters of a step are addressed as stepname__param. This works because BaseEstimator.get_params(deep=True) collects the parameters of nested estimators. That is also why constructor arguments must be stored unchanged. A renamed or transformed attribute would not appear in get_params.
print(sorted(pipe.get_params().keys())[:6])
pipe.set_params(clip__lower=0.0, clip__upper=1.0)
pipe.fit(X, y)Setting clip__lower=0.0 and clip__upper=1.0 makes the clipper act as the identity, because those are the minimum and maximum of each column. You can also replace a whole step with pipe.set_params(clip="passthrough"), which skips it. This is a convenient way to test whether a step helps.
ColumnTransformer: different steps for different columns
ColumnTransformer applies separate transformers to separate column subsets and concatenates the outputs side by side. Each entry is (name, transformer, columns).
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
rng = np.random.default_rng(0)
df = pd.DataFrame({
"age": rng.normal(40, 10, 200),
"income": rng.lognormal(10, 1, 200),
"city": rng.choice(["a", "b", "c"], 200),
})
target = (df["age"] + rng.normal(0, 5, 200) > 40).astype(int)
pre = ColumnTransformer([
("num", Pipeline([
("clip", QuantileClipper(0.05, 0.95)),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = Pipeline([("pre", pre), ("clf", LogisticRegression())])
model.fit(df, target)
print(model.score(df, target))
print(model.named_steps["pre"].transform(df).shape)The second print shows (200, 5): two numeric columns plus three one-hot columns. Several details matter for custom estimators.
- Your transformer receives a subset of the input. With column names, it gets a DataFrame containing only those columns.
check_arrayconverts it to a NumPy array. The column names are then lost unless you handle them, which a later chapter covers. - Column order is fixed at fit time.
ColumnTransformerrecords the columns it selected. At predict time it selects the same columns by name, so the order of columns in the new DataFrame does not matter. With integer indices or NumPy input, position is what counts. - Fitted copies live elsewhere.
ColumnTransformerclones each transformer before fitting. Your original object stays unfitted. Read the fitted version fromtransformers_ornamed_transformers_. - Unlisted columns are dropped by default (
remainder="drop"). Setremainder="passthrough"to keep them unchanged.
fitted_num = model.named_steps["pre"].named_transformers_["num"]
print(fitted_num.named_steps["clip"].upper_)Nested parameter paths grow by one segment for each nesting level.
| Object being tuned | Parameter path |
|---|---|
| Clipper in a flat pipeline | `clip__lower` |
| Clipper inside the `num` pipeline inside `pre` | `pre__num__clip__lower` |
| Encoder option inside `pre` | `pre__cat__handle_unknown` |
| Classifier regularization | `clf__C` |
model.set_params(pre__num__clip__lower=0.0)Edge cases and failure modes
- Wrong number of rows. A transformer that removes outlier rows breaks
Pipeline, becauseyno longer lines up withX. Clip or flag values instead. If you must resample, do it outside the pipeline. - Feature count mismatch. If
transformreceives a different number of columns thanfit, raise aValueError. Without that check, NumPy may broadcast silently and give wrong output. - Fitting on all the data. Inside a pipeline passed to
cross_val_scoreorGridSearchCV, each fold fits the transformer only on that fold's training part. Do not fit it before the split. If you callclipper.fit(X)on the full dataset and then cross-validate, the clipping bounds include the validation data. That is data leakage. - State shared between calls. Do not store results from
transformonself.transformshould not change the estimator, because the same fitted object may be reused for many inputs. - Sparse input.
check_arrayrejects sparse matrices by default. If a step upstream, such asOneHotEncoder, produces sparse output, passaccept_sparse=Trueand handle it, or place your transformer before that step.
Inspecting and reusing parts of a pipeline
Slicing returns a sub-pipeline: model[:-1] is every step except the classifier, and model[:-1].transform(df) gives the processed features. This is useful for debugging a custom step in context. For example, you can compare model[:1].transform(df) against the raw data to confirm that clipping changed only extreme values.
Exercise
A colleague writes a transformer whose transform method calls np.quantile on the input it receives and clips to those values. It works in a pipeline, but accuracy on a single new row is strangely bad. What is wrong, and where should the quantiles be computed?
Show answer
The quantiles are recomputed from each batch passed to transform, so the result depends on the batch. With a single row, every quantile equals that row's values, and the clipping does nothing useful. The quantiles must be computed once in fit from the training data and stored in attributes such as lower_ and upper_. transform should only apply those stored values.
Exercise
Given the model pipeline above, write the call that sets the clipper's upper quantile to 0.9 and replaces the one-hot encoder with "passthrough". Why will the second change likely fail at fit time here?
Show answer
model.set_params(pre__num__clip__upper=0.9, pre__cat="passthrough"). The city column contains strings, and LogisticRegression cannot convert them to numbers. Without the encoder, the final array has string values and the classifier raises an error at fit time. "passthrough" is only safe for columns that are already numeric.