Sub topic 15
Writing your own transformer
This chapter assumes you can fit a Pipeline, you know that fit learns from training data and transform applies what was learned, and you are comfortable with Python classes. You will write transformers that follow scikit-learn's estimator conventions. Because they follow those conventions, they work inside Pipeline, cross_val_score, and clone like built-in transformers.
When to write a class
Before writing a class, check whether you need one.
| Situation | Use |
|---|---|
| A fixed function with nothing learned from data, such as `np.log1p` | `FunctionTransformer` |
| Values learned from training data, such as quantiles, category maps, or medians | A custom class |
| Logic that must be tuned with `GridSearchCV` | A custom class, with the settings as constructor arguments |
FunctionTransformer wraps a function and needs no class:
import numpy as np
from sklearn.preprocessing import FunctionTransformer
log_step = FunctionTransformer(np.log1p)
print(log_step.fit_transform([[0.0], [1.0], [9.0]]))Write a class when fit has something to learn.
The minimum contract
A transformer needs three methods: __init__, fit, and transform. Two base classes supply the rest.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class LogTransformer(BaseEstimator, TransformerMixin):
def __init__(self, offset=1.0):
self.offset = offset
def fit(self, X, y=None):
return self
def transform(self, X):
return np.log(np.asarray(X) + self.offset)
print(LogTransformer().fit_transform([[0.0], [1.0], [9.0]]))BaseEstimatorprovidesget_params,set_params, and a readablerepr. It builds them by inspecting the argument names of__init__.TransformerMixinprovidesfit_transform, which callsfit(X, y).transform(X).fitacceptsy=Noneeven though transformers usually ignore it. APipelinealways callsfit(X, y), so the signature must allow it.fitreturnsself. This is what makes chaining such asfit(X).transform(X)work.
Learning state in fit
A transformer that learns something stores it in attributes whose names end in an underscore. The next example clips each column to quantiles computed on the training data.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted
class QuantileClipper(BaseEstimator, TransformerMixin):
def __init__(self, lower=0.05, upper=0.95):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
X = check_array(X)
self.n_features_in_ = X.shape[1]
self.lower_ = np.quantile(X, self.lower, axis=0)
self.upper_ = np.quantile(X, self.upper, axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"Expected {self.n_features_in_} features, got {X.shape[1]}."
)
return np.clip(X, self.lower_, self.upper_)
X_train = np.array([[1.0], [2.0], [3.0], [4.0], [100.0]])
clipper = QuantileClipper().fit(X_train)
print(clipper.lower_, clipper.upper_) # [1.2] [80.8]
print(clipper.transform([[50.0], [-5.0]])) # 50.0 stays, -5.0 becomes 1.2The class uses four conventions:
- Hyperparameters (
lower,upper) are set in__init__. Learned values (lower_,upper_,n_features_in_) are set infit. check_arrayconverts the input to a validated 2D float array. It rejects NaN, infinity, and 1D input with a clear error. It also lets the class accept DataFrames and lists.check_is_fitted(self)raisesNotFittedErrorif no attribute ending in an underscore exists. Callingtransformbeforefitthen gives a useful message.n_features_in_records the training column count. The shape check intransformcatches a column mismatch before it silently produces wrong output.
Why `__init__` must stay plain
clone, set_params, and GridSearchCV all rely on one rule: __init__ stores each argument unchanged under an attribute with the same name. It does no validation and no conversion, and it computes nothing.
The reason is how clone works. It calls get_params(), builds a new object by passing those values to the constructor, and then checks that the new object holds the same values it was given. Suppose __init__ did self.columns = list(columns). A tuple passed in would come back as a list, the identity check would fail, and clone would raise a RuntimeError.
If you need to validate a parameter, do it at the start of fit:
def fit(self, X, y=None):
if not 0.0 <= self.lower < self.upper <= 1.0:
raise ValueError("Need 0 <= lower < upper <= 1.")
...This also works with set_params. A grid search can set lower after construction, and fit still checks the final value.
Using it in a pipeline
Because the class follows the contract, it works like any built-in step. The pipeline refits it on each training fold during cross-validation.
from sklearn.base import clone
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(
QuantileClipper(lower=0.01, upper=0.99),
StandardScaler(),
LogisticRegression(max_iter=200),
)
print(cross_val_score(pipe, X, y, cv=5).mean())
# Parameters are addressed as <step name>__<parameter name>.
print(pipe.get_params()["quantileclipper__upper"]) # 0.99
tuned = clone(pipe).set_params(quantileclipper__upper=0.9)
print(pipe.get_params()["quantileclipper__upper"], tuned.get_params()["quantileclipper__upper"])make_pipeline names each step with the lowercase class name, so the step is quantileclipper. The double underscore in quantileclipper__upper reaches into that step. clone(pipe) produces an unfitted copy of the whole pipeline, including every step.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| `fit` does not return `self` | `AttributeError: 'NoneType' object has no attribute 'transform'` inside a pipeline | End `fit` with `return self` |
| Learning values in `transform` | Test data influences its own preprocessing, which is leakage | Compute all statistics in `fit` |
| Converting or validating arguments in `__init__` | `clone` or `set_params` fails or behaves unexpectedly | Store arguments as given and validate in `fit` |
| Learned attributes without a trailing underscore | `check_is_fitted` cannot detect fitting, and the attribute looks like a hyperparameter | Name learned values `something_` |
| Changing `X` in place | The caller's array is modified | Return a new array, as `np.clip` does |
| `fit(self, X)` without `y=None` | `TypeError` when a pipeline passes `y` | Always accept `y=None` |
| Different column counts at fit and transform | Silent wrong output or a confusing broadcast error | Store `n_features_in_` and check it |
Optional extras
Two extras make a transformer fit better in larger workflows.
- Feature names.
get_feature_names_outlets the pipeline report output column names. When a transformer returns one output column per input column, inheritOneToOneFeatureMixinfromsklearn.base. Define the method yourself when the output columns differ from the input columns. - Pandas output. A class that defines
get_feature_names_outcan return a DataFrame after you call.set_output(transform="pandas").
Neither is needed for the transformer to work in a pipeline. Add them when you inspect or export column names.
Summary of the contract
- Inherit from
BaseEstimatorandTransformerMixin. - Store constructor arguments unchanged under the same names.
- Learn in
fit, store results in attributes ending in_, and returnself. - Make
transforma pure function of its input and the learned attributes. - Check fitted state and input shape in
transform.
Exercise
A colleague writes __init__(self, columns) with the line self.columns = list(columns). Calling clone on the transformer fails when the object was built with columns=("a", "b"). Why does it fail, and what is the fix?
Show answer
clone passes the values from getparams (the tuple) to a new constructor call, then checks that the new object stores the very same objects it was given. After list(columns), the stored value is a new list, not the tuple that was passed in, so the check fails with a RuntimeError. The fix is to store self.columns = columns unchanged in init_ and convert it to a list inside fit or transform when needed.
Exercise
You write a MedianFiller transformer that replaces NaN with the column median. Where should the medians be computed, in fit or in transform, and what should the attribute be called?
Show answer
Compute them in fit, using only the training data, and store them in an attribute with a trailing underscore such as medians. transform then fills NaN using medians. Computing medians in transform would let the test set influence its own preprocessing, which is data leakage.