Sub topic 6
Building a custom transformer step by step
This chapter assumes you know Python classes, NumPy indexing, and the fit/transform pattern from built-in scikit-learn transformers. It also assumes you have read the earlier chapters on BaseEstimator, constructor rules, and learned attributes. Here you put those rules together in one working class.
The goal
You will build QuantileClipper. During fit, it learns the lower and upper quantile of each column. During transform, it clips every value into that range. This tames outliers, and it needs state learned from the training data, so a plain function is not enough.
The three pieces
A transformer needs three parts:
__init__stores the hyperparameters and does nothing else.fitvalidates the input, learns attributes ending in_, and returnsself.transformchecks that the estimator is fitted, validates the input, and returns a new array.
TransformerMixin adds fit_transform for free. It calls fit(X, y).transform(X).
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_)Walking through the choices
The class lists TransformerMixin before BaseEstimator. Python resolves methods left to right, and scikit-learn recommends this order so mixin behavior takes precedence.
__init__ only assigns self.lower = lower and self.upper = upper. The names match the arguments exactly. That is what lets get_params and clone rebuild the object, and it is why validation of the quantile values does not belong here. Do it in fit instead.
fit takes y=None even though it ignores y. Pipelines call fit(X, y) on every step, so the signature must accept it.
check_array converts lists and DataFrames to a 2D float array and rejects NaN and infinity by default. It also returns a new object, so your code does not modify the caller's data.
The learned values lower_, upper_, and n_features_in_ end in an underscore. check_is_fitted looks for attributes like these. If none exist, it raises NotFittedError.
transform repeats the validation and compares the column count against the one seen in fit. np.clip returns a new array, so the input stays unchanged.
Trying it
import numpy as np
rng = np.random.default_rng(0)
X_train = rng.normal(size=(200, 3))
clipper = QuantileClipper(lower=0.05, upper=0.95)
X_clipped = clipper.fit_transform(X_train)
print(clipper.lower_.shape)
print(np.all(X_clipped >= clipper.lower_))
X_new = np.array([[100.0, -100.0, 0.0]])
out = clipper.transform(X_new)
print(np.isclose(out[0, 0], clipper.upper_[0]))
print(np.isclose(out[0, 1], clipper.lower_[1]))This prints (3,), then True three times. The extreme new values are pulled back to the bounds learned from the training data. The new data does not change the bounds.
Common errors
| Symptom | Likely cause |
|---|---|
| `NotFittedError` in `transform` | `fit` was not called, or it set no attribute ending in `_` |
| `clone` or `get_params` fails | An `__init__` argument is not stored under the same name |
| Pipeline raises a `TypeError` about `fit` arguments | `fit` does not accept `y=None` |
| Results change after `set_params` | `__init__` computed something from the arguments instead of storing them |
Exercise
Why does QuantileClipper.fit return self, and why does transform call check_is_fitted before anything else?
Show answer
Returning self lets TransformerMixin.fit_transform and pipelines chain calls such as fit(X, y).transform(X). check_is_fitted stops an unfitted estimator early with a clear NotFittedError. Without it, the code would fail later with a confusing AttributeError on lower_.