Custom transformer contracts
Quick answer
A custom transformer implements the estimator protocol so it can be composed, cloned and fitted inside pipelines. A small center-only transformer learns one mean per training column and subtracts it from new rows. The example targets scikit-learn 1.8 and accepts dense finite numerical input. All library examples are standalone local Python examples tested with scikit-learn 1.8.0; ByteMind package execution is not verified.
Implement a fitted center-only transformer
from sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.utils.validation import validate_data, check_is_fittedfrom sklearn.utils import get_tagsclass CenterColumns(TransformerMixin, BaseEstimator): def __init__(self, offset=0.0): self.offset = offset def fit(self, X, y=None): X = validate_data(self, X, reset=True, dtype=float) self.mean_ = X.mean(axis=0) return self def transform(self, X): check_is_fitted(self, 'mean_') X = validate_data(self, X, reset=False, dtype=float) return X - self.mean_ + self.offsetc = CenterColumns(offset=1).fit([[2, 4], [6, 8]])print(c.mean_.tolist())print(c.transform([[10, 2]]).tolist())print(get_tags(c).requires_fit)Expected output:
[4.0, 6.0][[7.0, -3.0]]TrueThe learned means are fixed; the optional offset is a constructor parameter.
How it works
Inherit TransformerMixin before BaseEstimator so the mixin methods and tags resolve correctly. Declare explicit constructor parameters and assign them unchanged; defer data-dependent work to fit. Include y=None for a transformer that does not need labels, and return self from fit. validate_data(self, X, reset=True) records the number of features and, when applicable, feature names; transform calls it with reset=False to enforce the fitted input contract. check_is_fitted guards transform before learning. Learned state belongs in attributes such as mean_. The subtraction returns a fresh array instead of mutating the caller’s data. TransformerMixin provides fit_transform. The public get_tags API describes capabilities; it does not certify correctness. This example accepts dense finite numeric inputs, does not promise sparse or missing-value support, and does not implement feature-name output. To expose feature names or set_output support, implement the appropriate additional contract and test it. Run check_estimator in a local environment, then add domain-specific tests for data leakage and schema; generic checks cannot prove business validity.
Reject unfitted and incompatible input
from sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.utils.validation import validate_data, check_is_fittedfrom sklearn.utils import get_tagsclass CenterColumns(TransformerMixin, BaseEstimator): def __init__(self, offset=0.0): self.offset = offset def fit(self, X, y=None): X = validate_data(self, X, reset=True, dtype=float) self.mean_ = X.mean(axis=0) return self def transform(self, X): check_is_fitted(self, 'mean_') X = validate_data(self, X, reset=False, dtype=float) return X - self.mean_ + self.offsetfrom sklearn.exceptions import NotFittedErrorfrom sklearn.base import clonec = CenterColumns()try: c.transform([[1]])except NotFittedError: print('not fitted')c.fit([[1, 2], [3, 4]])try: c.transform([[1]])except ValueError: print('wrong width')print(hasattr(clone(c), 'mean_'))Expected output:
not fittedwrong widthFalseBoth invalid calls fail and the ordinary clone is unfitted.
Common mistakes
Avoid computing a training mean in init, storing X as a mutable constructor parameter, learning inside transform, or calling validate_data(reset=True) during inference. The latter can overwrite the expected feature count and hide schema drift. Do not claim full compatibility with every estimator or output container from one working pipeline example.
Practice
Extend the transformer with a documented offset and check that cloning discards mean_, transforming before fit fails, wrong-width rows fail, the training array is unchanged and an independent mean subtraction agrees. Run check_estimator separately; if it reports failure, do not suppress it without investigation.
Reference candidate: concept-custom-transformer-contracts. Review the associated knowledge check. Native estimator tasks require a local scientific Python environment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Custom transformer contracts — knowledge check
Apply estimator contracts and leakage-resistant pipelines to small fixtures.
Where should learned column means be computed?
Which validation setting should transform use?
What should fit return?
What does check_is_fitted protect against?
What does passing generic estimator checks establish?