Sub topic 9
Using your estimator in Pipeline and ColumnTransformer
This chapter assumes you can write a transformer with BaseEstimator and TransformerMixin. It also assumes you know the fit, transform and predict methods, and that you have used Pipeline before. Here you will plug the QuantileClipper from the previous chapters into both containers.
What Pipeline requires
A Pipeline chains steps and calls them in a fixed order.
- Every step except the last must implement
fitandtransform.TransformerMixinsuppliesfit_transform, which the pipeline calls duringfit. - The last step needs only
fit. It can be a transformer, a classifier or a regressor. - At prediction time, the pipeline calls
transformon each intermediate step. It never callsfitagain, so test data cannot change learned values.
If your estimator follows the conventions, no extra code is needed.
What ColumnTransformer adds
ColumnTransformer applies different transformers to different columns and concatenates the results side by side. It clones each transformer you give it, fits the clones, and stores them in transformers_. Your original objects stay unfitted. This is why the constructor rules matter: clone rebuilds your estimator from get_params().
A complete example
QuantileClipper uses check_array, which rejects strings. So it must receive only the numeric columns.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
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_)
df = pd.DataFrame({
"age": [22, 35, 58, 41, 29, 63, 47, 31],
"income": [28, 52, 90, 61, 39, 300, 72, 45],
"city": ["a", "b", "a", "c", "b", "c", "a", "b"],
})
y = [0, 1, 1, 1, 0, 1, 1, 0]
prep = ColumnTransformer([
("num", QuantileClipper(lower=0.05, upper=0.95), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
pipe = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
pipe.fit(df, y)
print(pipe.score(df, y))
print(pipe.named_steps["prep"].named_transformers_["num"].upper_)The last line reads the learned upper_ bounds from the fitted clone. The QuantileClipper(...) object you built is still unfitted.
Nested parameter names
Parameters are addressed with double underscores, one pair per level of nesting. For the example above, the clipper's upper quantile is prep__num__upper. You can use that name in set_params or in a GridSearchCV grid.
pipe.set_params(prep__num__upper=0.9)Common errors
| Symptom | Likely cause |
|---|---|
| `could not convert string to float` | A string column was routed to a transformer that calls `check_array`. |
| `X has 3 features, but ... is expecting 2` | The columns selected at `fit` differ from those at `transform`. |
| `NotFittedError` on a step | You called `transform` on an unfitted clone. Fit the pipeline, not the original object. |
| Dropped columns | `ColumnTransformer` drops unlisted columns by default. Set `remainder="passthrough"` to keep them. |
Exercise
In the example, how would you pass the income column through unchanged while still clipping only age?
Show answer
Change the "num" entry to select only ["age"], and add a ("raw", "passthrough", ["income"]) entry to the ColumnTransformer list. As an alternative, keep the "num" entry as it is and add a separate "passthrough" entry only if you want an unclipped copy of income as an extra feature.