Sub topic 6
Building a custom transformer step by step
This chapter assumes you can write Python classes, use NumPy arrays, and have already called fit, transform and Pipeline on built-in scikit-learn objects. It also assumes you know the constructor and trailing-underscore conventions from the earlier chapters. Here you put them together into one working transformer and check it against the rules scikit-learn relies on.
The goal: a quantile clipper
Outliers can distort scalers and linear models. A common fix is to clip each column to bounds learned from the training data, for example its 1st and 99th percentiles. This is a good first custom transformer because:
- It has state. The bounds are learned in
fitand reused intransform. - It has hyperparameters (
lowerandupper) that you may want to tune. - It works column by column, so it is easy to reason about.
A transformer that only applies a fixed function, such as np.log1p, has no state. That case is better served by FunctionTransformer, covered in the next chapter.
The shape of the class
The diagram shows the separation the API depends on. Constructor arguments have no trailing underscore and are set in __init__. Learned values have a trailing underscore and are set in fit. transform only reads learned values and never changes them.
Step 1: inherit in the right order
from sklearn.base import BaseEstimator, TransformerMixin
class QuantileClipper(TransformerMixin, BaseEstimator):
...BaseEstimator supplies get_params, set_params, __repr__ and cloning support. It finds parameters by inspecting the signature of __init__. TransformerMixin supplies fit_transform, which calls fit(X, y).transform(X).
Put the mixin before BaseEstimator in the base-class list. Python resolves methods left to right, and scikit-learn's own estimators follow this order. Newer versions rely on it when they combine tags from the mixins and the base class.
Step 2: write a constructor that only stores
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upperThe rules for __init__ are strict:
- Every argument has a default value.
- Each argument is stored under an attribute of the same name, with no changes.
- Nothing else happens. There is no validation, no computation and no copying.
These rules exist because clone rebuilds an estimator by calling get_params() and passing the results back to the constructor. GridSearchCV clones the estimator for every candidate and every fold. It also uses set_params to change values after construction. If __init__ had changed lower, the stored value would no longer match what the user passed, and cloning would silently produce a different object. Any validation done in __init__ would also be skipped when set_params is called later.
Step 3: learn state in `fit`
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 selfSeveral details matter here:
check_arrayconverts lists and DataFrames to a 2-D float array. It rejects NaN and infinity by default and raises a clear error for 1-D input.y=Noneis required even though this transformer ignoresy. Pipelines callfit(X, y)on every step.axis=0computes one bound per column, solower_andupper_each have shape(n_features,).n_features_in_records the training width.transformuses it to catch column mismatches.fitreturnsself. Chaining such asclip.fit(X).transform(X)and the mixin'sfit_transformboth depend on this.
Step 4: apply state in `transform`
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but {self.__class__.__name__} "
f"is expecting {self.n_features_in_} features as input"
)
return np.clip(X, self.lower_, self.upper_)check_is_fitted(self) raises NotFittedError if no attribute ending in an underscore exists yet. This is why the learned attributes must follow the naming rule. The function uses that suffix to decide whether fit has run.
np.clip returns a new array, so the caller's data is not mutated. This matters because a transformer that edits its input in place changes the user's data without warning.
The complete class and a first run
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
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)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but {self.__class__.__name__} "
f"is expecting {self.n_features_in_} features as input"
)
return np.clip(X, self.lower_, self.upper_)
X_train = np.arange(100, dtype=float).reshape(-1, 1)
X_test = np.array([[-50.0], [40.0], [150.0]])
clip = QuantileClipper()
clip.fit(X_train)
print(np.round(clip.lower_, 2), np.round(clip.upper_, 2))
print(clip.transform(X_test).ravel())
print(clip.get_params())For training values 0 to 99, the 1st and 99th percentiles are 0.99 and 98.01. The test value -50 becomes 0.99, 40 is unchanged, and 150 becomes 98.01. The bounds come from the training data only, which is the point of separating fit from transform. get_params() returns {'lower': 0.01, 'upper': 0.99}, which is what clone and GridSearchCV use.
Where to validate hyperparameters
Suppose a user passes lower=0.9, upper=0.1. The bounds would cross and np.clip would give confusing results. The right place for the check is the start of fit:
def fit(self, X, y=None):
if not 0 <= self.lower <= self.upper <= 1:
raise ValueError(
"Need 0 <= lower <= upper <= 1, "
f"got lower={self.lower}, upper={self.upper}"
)
X = check_array(X)
...The check belongs in fit because parameters can change after construction through set_params, and a grid search does exactly that. A check in __init__ would run once at construction and miss every later change.
What mixins and base classes give you
| You write | You get for free |
|---|---|
| `__init__` with plain stored arguments | `get_params`, `set_params`, `clone`, readable `repr` |
| `fit` returning `self` | Chaining, `fit_transform` |
| `transform` | Use in `Pipeline`, `ColumnTransformer`, `FeatureUnion` |
| Attributes ending in `_` | `check_is_fitted` support |
Common mistakes in a first transformer
- Learning in
transform. Computing quantiles on whatever data arrives intransformleaks test information into the result and gives different bounds for each call. Compute them infitonly. - Forgetting
return self.fitreturnsNone, sofit_transformfails with anAttributeErroronNoneType. - Storing a modified argument. Writing
self.lower = float(lower)changes the value thatget_paramsreturns. Cloning then no longer reproduces the user's original argument. - Skipping the feature-count check. Without it, NumPy broadcasting can fail with an obscure shape error, or worse, succeed on the wrong columns.
Exercise
Your teammate's __init__ for a transformer is def __init__(self, quantiles=(0.01, 0.99)): self.lower, self.upper = quantiles. Why will clone fail or misbehave, and how would you fix it?
Show answer
BaseEstimator.get_params looks for an attribute named quantiles, which does not exist, so get_params raises an AttributeError and clone cannot copy the estimator. Cloning also needs the constructor argument stored unchanged under its own name. The fix is to store it as self.quantiles = quantiles in __init__ and unpack it into local variables inside fit, for example lower, upper = self.quantiles.
Exercise
What happens if you call QuantileClipper().transform(X_test) before any call to fit, and which line of the class produces that behaviour?
Show answer
scikit-learn raises NotFittedError. The check_is_fitted(self) call at the top of transform produces it, because the instance has no attributes ending in an underscore (lower_, upper_, n_features_in_) until fit runs.