Sub topic 15
Writing your own transformer
This chapter assumes you know Python classes, NumPy arrays, and the scikit-learn methods fit, transform, and fit_transform. You should also know how a Pipeline chains steps and how get_params and clone work.
Why write one
Built-in transformers cover most needs. Sometimes you need a step that scikit-learn does not provide, such as a domain-specific log transform. If your class follows the estimator API, it works inside a Pipeline, cross_val_score, and clone like any built-in step.
The minimal contract
A transformer needs three things:
- An
__init__that only stores its arguments, unchanged, under attributes of the same name. - A
fit(X, y=None)method that learns anything needed from the data and returnsself. - A
transform(X)method that returns the new data.
Two base classes supply the rest. BaseEstimator provides get_params and set_params. TransformerMixin provides fit_transform, which calls fit and then transform.
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]]))This transformer is stateless. It learns nothing in fit, so fit just returns self. The y=None argument keeps the signature compatible with pipelines, which pass y to every step.
Using it in a pipeline
Because the class follows the API, you can drop it into a pipeline and tune its constructor setting.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
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
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)
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(LogTransformer(offset=1.0), LogisticRegression(max_iter=200))
print(cross_val_score(pipe, X, y, cv=5).mean())
print(pipe.get_params()["logtransformer__offset"])The double-underscore name logtransformer__offset shows that get_params reaches into pipeline steps. That only works because BaseEstimator reads the __init__ signature.
Learning something in fit
If the transformer needs training data, compute it in fit and store it in an attribute ending in an underscore. Use it in transform. This keeps test data from influencing what is learned.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class MeanCenterer(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
self.mean_ = np.asarray(X).mean(axis=0)
return self
def transform(self, X):
return np.asarray(X) - self.mean_
train = [[1.0, 10.0], [3.0, 30.0]]
test = [[2.0, 20.0]]
centerer = MeanCenterer().fit(train)
print(centerer.mean_)
print(centerer.transform(test))Common errors
- Changing arguments in
__init__. Writingself.offset = float(offset)or computing a new value there breakscloneandset_params. Store the argument as given and handle conversions infitortransform. - Forgetting
return selfinfit. The pipeline then receivesNoneand fails with a confusing error. - Learning from data in
transform. Computing a mean there would use test data and cause leakage. Learn infitonly. - Setting fitted attributes in
__init__. Names ending in an underscore should exist only afterfit.
Exercise
Why does LogTransformer.__init__ store offset without modifying it, and why does fit return self?
Show answer
BaseEstimator.get_params and clone rebuild the estimator from the constructor arguments, so the stored attributes must match the arguments exactly. fit returns self so that fit_transform and pipelines can chain calls, such as LogTransformer().fit(X).transform(X).
Exercise
In MeanCenterer, which line would cause data leakage if you moved it from fit into transform, and why?
Show answer
The line computing the column means (self.mean_ = ...). Computed in transform, it would use the test data's own mean instead of the training mean, so information from the test set would influence preprocessing.