Sub topic 9
Writing a custom transformer
This chapter assumes you can build a Pipeline and know the fit/transform split from earlier chapters. You also need basic NumPy. Built-in transformers cover most preprocessing. Sometimes you need a step they don't offer, such as a domain-specific feature or a log transform. A custom transformer lets that step sit inside a pipeline, so it is cross-validated, tuned, and saved like any other step.
What a pipeline requires from a step
Every step except the last needs two methods:
fit(X, y=None)learns anything it needs from the training data and returnsself.transform(X)returns the new feature array.
Inheriting TransformerMixin adds fit_transform for you. Inheriting BaseEstimator adds get_params and set_params, which GridSearchCV and clone rely on. List TransformerMixin first, as scikit-learn's own classes do.
A stateless transformer
Some steps learn nothing. The log transform below has no state, so fit only returns self.
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)
print(Log1pTransformer().fit_transform(np.array([[0.0, 1.0], [9.0, 99.0]])))fit still takes y=None because a pipeline calls fit(X, y) on every step.
A transformer that learns from data
A step that learns something must store it during fit. The next transformer clips each column to quantiles computed on the training data. If it computed quantiles inside transform, validation data would influence its own preprocessing, which is the leakage a pipeline exists to prevent.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
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.low_ = np.quantile(X, self.lower, axis=0)
self.high_ = np.quantile(X, self.upper, axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return np.clip(X, self.low_, self.high_)
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(QuantileClipper(), StandardScaler(), LogisticRegression(max_iter=1000))
print(cross_val_score(pipe, X, y, cv=5).mean())Three conventions matter here:
__init__only stores its arguments, under the same names, with no computation or validation.cloneandget_paramsdepend on this.- Learned values get a trailing underscore (
low_,high_).check_is_fitteduses that suffix to detect an unfitted estimator. check_arrayrejects NaN, infinity, and non-numeric input with a clear error, and converts DataFrames to arrays.
Tuning your own parameters
Because __init__ arguments are real parameters, the step__param naming works on them. make_pipeline names a step after its lowercased class, so the clipper is quantileclipper.
from sklearn.model_selection import GridSearchCV
grid = {"quantileclipper__upper": [0.95, 0.99, 1.0]}
search = GridSearchCV(pipe, grid, cv=5).fit(X, y)
print(search.best_params_)Common errors
| Symptom | Likely cause |
|---|---|
| `GridSearchCV` ignores or rejects your parameter | `__init__` argument name differs from the attribute name |
| `NotFittedError` on `transform` | `fit` didn't set any attribute ending in `_`, or it was never called |
| Cross-validation score looks too good | Statistics computed in `transform` or on the full dataset |
| Shape error at the next step | `transform` returned a different number of rows, or a 1-D array |
Exercise
Write a transformer AddRatio with parameters num_col and den_col (column indexes) that appends the ratio of those two columns as a new last column. Which method needs to know nothing about the training data, and why can this class use fit that only returns self?
Show answer
Implement __init__(self, num_col=0, den_col=1) storing both values, fit(self, X, y=None) returning self, and transform(self, X) returning np.column_stack([X, X[:, self.num_col] / X[:, self.den_col]]). The ratio is computed from each row alone, so nothing is learned from the training data. fit therefore has no state to store, and transform behaves the same on training and new data.