Sub topic 2
BaseEstimator, TransformerMixin, ClassifierMixin and RegressorMixin
This chapter assumes you can write Python classes with inheritance, and that you have used fit, transform and predict on built-in scikit-learn estimators. It covers which base classes to inherit from, what each one gives you, and what you still have to write yourself.
What each class provides
scikit-learn does not require inheritance. Any object with the right methods works. In practice you inherit from these classes because they supply the boilerplate that cloning, grid search and pipelines depend on.
| Class | Gives you | You must still write |
|---|---|---|
| `BaseEstimator` | `get_params`, `set_params`, a readable `repr`, support for `clone` | `__init__` and `fit` |
| `TransformerMixin` | `fit_transform`, plus `set_output` support once you define `get_feature_names_out` | `fit` and `transform` |
| `ClassifierMixin` | `score` (mean accuracy) and the "classifier" tag | `fit` and `predict` |
| `RegressorMixin` | `score` (R²) and the "regressor" tag | `fit` and `predict` |
Mixins come first
List the mixins before BaseEstimator:
class MyTransformer(TransformerMixin, BaseEstimator):
...Python resolves methods left to right. Recent scikit-learn versions also build estimator tags through this inheritance order, so the wrong order can silently lose tag information.
How BaseEstimator finds parameters
BaseEstimator.get_params reads the signature of your __init__ and, for each argument name, looks up an attribute of the same name. This is why the constructor must store each argument unchanged under its own name. The next chapter covers that rule in detail.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
class Scale(TransformerMixin, BaseEstimator):
def __init__(self, factor=2.0):
self.factor = factor
def fit(self, X, y=None):
X = check_array(X)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
return check_array(X) * self.factor
scaler = Scale()
print(scaler.get_params()) # {'factor': 2.0}
scaler.set_params(factor=3.0)
print(clone(scaler).factor) # 3.0
print(scaler.fit_transform([[1.0, 2.0]])) # [[3. 6.]]fit_transform comes from TransformerMixin. It calls fit(X, y).transform(X). If you can compute the result faster in one step, override it.
A regressor with RegressorMixin
class MeanRegressor(RegressorMixin, BaseEstimator):
def fit(self, X, y):
X, y = check_X_y(X, y)
self.mean_ = y.mean()
self.n_features_in_ = X.shape[1]
return self
def predict(self, X):
check_is_fitted(self)
X = check_array(X)
return np.full(X.shape[0], self.mean_)
X = np.array([[1.0], [2.0], [3.0]])
y = np.array([1.0, 2.0, 3.0])
model = MeanRegressor().fit(X, y)
print(model.predict(X)) # [2. 2. 2.]
print(model.score(X, y)) # 0.0You never wrote score. RegressorMixin computes R² from your predict. A model that always predicts the mean scores 0.0, as expected. ClassifierMixin works the same way but returns accuracy.
Common errors
- Putting
BaseEstimatorbefore the mixins. - Forgetting
return selfinfit. Chained calls such asfit(X).transform(X)then fail with anAttributeErroronNone. - Defining
fit(self, X)withouty=Noneon a transformer.Pipelinepassesyto every step. - Inheriting from
ClassifierMixinbut returning probabilities frompredict.scorecomparespredictoutput to labels, sopredictmust return labels.
Exercise
Why does score work on MeanRegressor even though the class never defines it, and which method must predict return values for so that score is meaningful?
Show answer
score is inherited from RegressorMixin, which calls self.predict(X) and computes R² against y. So predict must return one numeric target value per row of X.