Sub topic 9
Writing a custom transformer
Built-in transformers cover scaling, imputing, and encoding. Sooner or later you need a step they don't offer: a domain-specific ratio, a clipping rule, or a log transform. This chapter shows how to write that step so it works inside a Pipeline, a ColumnTransformer, and GridSearchCV like any built-in class.
It assumes you know the fit/transform contract, can build a Pipeline, and know the step__parameter naming convention from earlier chapters. You also need basic Python classes and NumPy.
What a pipeline expects from a step
Every step except the last must provide fit and transform. The last step needs fit and usually predict. A pipeline also needs three other things, which scikit-learn's base classes supply:
get_paramsandset_params, soGridSearchCVcan change settings andclonecan build fresh copies.BaseEstimatorprovides them by reading the arguments of your__init__.fit_transform, whichPipelinecalls on each intermediate step during fitting.TransformerMixinprovides it asfit(X, y).transform(X).set_outputsupport, which lets users request DataFrame output.TransformerMixinadds it automatically when your class definesget_feature_names_out.
List TransformerMixin before BaseEstimator in the class bases. The scikit-learn documentation uses this order, and it keeps the method resolution order predictable.
The smallest useful transformer
A stateless transformer learns nothing from the data. Its 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]])))This prints approximately:
[[0. 0.69314718]
[2.30258509 4.60517019]]Two details matter here. fit accepts y=None because pipelines call fit(X, y) on every step, even when the step ignores the labels. And fit returns self, because fit_transform and method chaining depend on it.
The class has no __init__, so it has no parameters. That is valid, and get_params() returns an empty dictionary.
A transformer that learns from data
Most useful transformers compute something in fit and apply it in transform. A scaler learns means and variances. The next example learns per-column quantile bounds and clips values to them. This limits the effect of outliers.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, OneToOneFeatureMixin
from sklearn.utils.validation import check_array, check_is_fitted
class QuantileClipper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
if not 0 <= self.lower < self.upper <= 1:
raise ValueError("Need 0 <= lower < upper <= 1.")
X = check_array(X)
self.n_features_in_ = X.shape[1]
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)
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.low_, self.high_)
X = np.array([[1.0, 10.0], [2.0, 20.0], [3.0, 30.0], [100.0, 40.0]])
clipper = QuantileClipper(lower=0.0, upper=0.75).fit(X)
print(clipper.high_)
print(clipper.transform(X))The class follows a set of conventions that scikit-learn relies on.
Constructor rules
__init__ only stores its arguments, each under an attribute with the same name. It does no validation, no computation, and no conversion. The reason is clone. It calls get_params, builds a new object from those values, and checks that the new object holds the same values. If __init__ changed a value, say by rounding lower, the clone would differ from the original, and GridSearchCV or set_params could behave wrongly. Validation belongs in fit, as the check on lower and upper above shows.
Fitted attribute rules
Anything learned from data is stored with a trailing underscore: low_, high_, n_features_in_. check_is_fitted(self) looks for attributes ending in an underscore. If none exist, it raises NotFittedError. This is why a transformer used before fit fails with a clear message instead of an AttributeError.
Constructor parameters have no underscore and fitted state does. This split lets you see at a glance which values you chose and which the data determined.
Input validation
check_array converts input to a 2-D float array and rejects NaN and infinity by default. It turns a pandas DataFrame into a NumPy array, so column names are lost inside this step. Comparing X.shape[1] against n_features_in_ in transform catches a common error. It happens when the columns at prediction time differ from those at training time.
Recent scikit-learn versions also offer validate_data in sklearn.utils.validation. It does the same checking and also records feature_names_in_. Older versions use the private method self._validate_data. Because the public name depends on your version, this chapter sticks to check_array, which works in all of them.
Feature names
OneToOneFeatureMixin supplies get_feature_names_out for transformers that return one output column per input column. Because the method exists, set_output(transform="pandas") works on the class. For a transformer that changes the number of columns, write get_feature_names_out(self, input_features=None) yourself and return an array of strings.
What the pipeline does with your class
The next diagram shows the calls during pipe.fit(X_train, y_train). Your transformer only needs to respond to fit_transform here, and TransformerMixin provides that.
Bounds are learned only from training data and then reused on new data. That is the same leakage protection the built-in transformers give you.
Using the transformer in a search
Because QuantileClipper follows the parameter conventions, its settings can be tuned like any other step. This block reuses the class defined above, so run both blocks in the same session.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
pipe = Pipeline([
("clip", QuantileClipper()),
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
param_grid = {
"clip__lower": [0.0, 0.05],
"clip__upper": [0.95, 0.99, 1.0],
}
search = GridSearchCV(pipe, param_grid, cv=5)
search.fit(X_train, y_train)
print(search.best_params_)
print(search.score(X_test, y_test))For each candidate and each fold, GridSearchCV clones the pipeline, which clones QuantileClipper through get_params, then calls set_params(clip__lower=...). If your __init__ broke the naming rule, this is where it would fail. Preprocessing choices such as the clipping range are hyperparameters, and this lets you tune them with cross-validation.
When a function is enough
If the transform is stateless and a single function expresses it, FunctionTransformer wraps it without a new class. A class is better when the step learns from data or has parameters you want to tune.
import numpy as np
from sklearn.preprocessing import FunctionTransformer
log_step = FunctionTransformer(
np.log1p,
inverse_func=np.expm1,
feature_names_out="one-to-one",
)
print(log_step.fit_transform(np.array([[0.0, 1.0], [9.0, 99.0]])))| Situation | Use |
|---|---|
| Stateless function of the input, such as log or square root | `FunctionTransformer` |
| Parameters to tune, but nothing learned from data | Custom class, or `FunctionTransformer` with `kw_args` |
| Statistics learned from training data in `fit` | Custom class |
| Output column count differs from input | Custom class with `get_feature_names_out` |
One limit of FunctionTransformer: a lambda cannot be pickled, so a pipeline containing one cannot be saved with joblib. Use a named, module-level function instead.
Common errors and edge cases
- Doing work in
__init__. A line such asself.lower = max(lower, 0)breaksclone. Store the raw value and handle it infit. - Forgetting
return selfinfit.fit_transformthen calls.transformonNone, which raisesAttributeError: 'NoneType' object has no attribute 'transform'. - Mutating the input in
transform. WritingX[:, 0] = ...on the caller's array changes their data and can corrupt later folds. Work on a copy (X = X.copy()) or return a new array.np.clipreturns a new array, which is why the example is safe. - Learning from test data. Computing anything from
Xinsidetransformmakes the result depend on the batch you pass in. A single-row prediction would then differ from the same row predicted inside a large batch. Learn infit, apply intransform. - Relying on column order without checking. If your step uses column positions, record
n_features_in_and validate it, as the example does. - Unpicklable state. Storing lambdas or open files as attributes breaks
joblib.dump. Keep fitted state to arrays, numbers, and strings.
To find contract violations early, run check_estimator from sklearn.utils.estimator_checks on an instance of your class. It runs the same checks scikit-learn applies to its own estimators. Some checks are strict and may flag choices that are acceptable for private use, so read each failure before deciding whether to fix it.
Exercises
Exercise
A colleague writes __init__(self, scale=1.0) and inside it sets self.scale = float(scale) and self.cache_ = {}. Name two problems this causes in a pipeline context and give the fix for each.
Show answer
First, the constructor converts the value, so a clone built from get_params can differ from the original (for example an integer becomes a float), and scikit-learn's clone check can fail. Store self.scale = scale and convert in fit or transform. Second, cache_ ends in an underscore, which marks fitted state, but it exists before fit runs, so check_is_fitted would wrongly pass on an unfitted object. Create it in fit instead.
Exercise
Write a transformer RatioFeature that takes two column indices as constructor parameters num and den and appends a new column equal to X[:, num] / X[:, den]. Which methods and attributes does it need, and does it need to learn anything in fit?
Show answer
It needs __init__(self, num=0, den=1) that only stores the two arguments, a fit(self, X, y=None) that calls check_array, stores self.n_features_in_ = X.shape[1], and returns self, and a transform that calls check_is_fitted, validates the input, and returns np.column_stack([X, X[:, self.num] / X[:, self.den]]). It learns nothing from the data, so fit only records the feature count. Because it adds one column, it should also define get_feature_names_out returning the input names plus a name such as "ratio". Handle zeros in the denominator explicitly, for example with np.divide(..., where=...).
Exercise
Why can GridSearchCV tune clip__upper for QuantileClipper without any extra code in the class?
Show answer
BaseEstimator.get_params and set_params read the __init__ signature, and the pipeline exposes each step's parameters under stepname__param. Since upper is an __init__ argument stored unchanged as self.upper, the search can set it on a clone for each candidate.