Sub topic 2
BaseEstimator, TransformerMixin, ClassifierMixin and RegressorMixin
This chapter assumes you can write Python classes with inheritance, use NumPy arrays, and have called fit, predict and transform on built-in scikit-learn estimators. Here you will learn what each base class gives you for free, what it leaves for you to write, and why the order of the base classes matters.
Why scikit-learn uses base classes
Scikit-learn uses duck typing. Any object with the right methods can work in a Pipeline. In practice, though, tools such as clone, GridSearchCV and cross_val_score need more than fit and predict. They need to:
- read and set constructor parameters,
- print a readable representation,
- know whether the object is a classifier, a regressor or a transformer,
- compute a default
score.
The base class and the mixins supply these behaviors. You write the learning logic, and they supply the plumbing.
BaseEstimator
BaseEstimator is the root class for every estimator. It provides:
get_params(deep=True)andset_params(**params)- a readable
__repr__ - support for
clone, which builds a fresh, unfitted copy from the parameters - pickling support that records the scikit-learn version
- estimator tags (metadata about capabilities), in recent versions
get_params works by inspecting the signature of your __init__. It collects every named argument and reads the attribute with the same name. This is the reason for the constructor rule covered in the next chapter: each argument must be stored under the same name.
from sklearn.base import BaseEstimator
class Demo(BaseEstimator):
def __init__(self, alpha=1.0, mode="fast"):
self.alpha = alpha
self.mode = mode
d = Demo()
print(d)
print(d.get_params())
d.set_params(alpha=0.5)
print(d)This prints Demo(), then {'alpha': 1.0, 'mode': 'fast'}, then Demo(alpha=0.5). The default repr shows only parameters that differ from their defaults.
BaseEstimator does not define fit, predict or transform. It is not an estimator by itself, and it does not know what kind of estimator you are building.
The mixins
A mixin is a small class that adds one capability and is meant to be combined with others. Each mixin below adds a method and sets the estimator's kind.
| Mixin | Adds | Kind it declares | You still write |
|---|---|---|---|
| `TransformerMixin` | `fit_transform` | transformer | `fit`, `transform` |
| `ClassifierMixin` | `score` (mean accuracy) | classifier | `fit`, `predict` |
| `RegressorMixin` | `score` (R²) | regressor | `fit`, `predict` |
| `ClusterMixin` | `fit_predict` | clusterer | `fit` |
| `OutlierMixin` | `fit_predict` | outlier detector | `fit`, `predict` |
ClusterMixin and OutlierMixin are less common, so this tutorial does not cover them further.
TransformerMixin
TransformerMixin implements fit_transform(X, y=None, **fit_params). It calls self.fit(X, y, **fit_params).transform(X), or self.fit(X, **fit_params).transform(X) when y is None. If your fit and transform are correct, you get fit_transform without writing it.
The mixin also adds the set_output method when your class defines get_feature_names_out. That method is covered in a later chapter on feature names.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted
class Centerer(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
X = check_array(X)
self.mean_ = X.mean(axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return X - self.mean_
print(Centerer().fit_transform(np.array([[1.0, 2.0], [3.0, 4.0]])))The output is [[-1. -1.] [ 1. 1.]]. Centerer has no __init__, so it has no parameters and get_params() returns an empty dict. That is valid.
You can override fit_transform when computing both steps together is cheaper than running them separately. The result must equal fit(X).transform(X).
ClassifierMixin
ClassifierMixin provides score(X, y, sample_weight=None). It calls self.predict(X) and returns accuracy_score. It also marks the object as a classifier. That mark changes how other tools behave:
is_classifier(est)returnsTrue.cross_val_scoreandGridSearchCVuse stratified folds whencvis an integer and the estimator is a classifier.- Scorers that need class probabilities check for
predict_probaandclasses_.
The mixin does not give you predict_proba, decision_function or classes_. Your fit must set classes_ (see the classifier example in a later chapter).
RegressorMixin
RegressorMixin provides score as the coefficient of determination, R². The best value is 1.0. A model that always predicts the mean of the training targets scores about 0.0 on the training data.
import numpy as np
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
class MeanRegressor(RegressorMixin, BaseEstimator):
def fit(self, X, y):
X, y = check_X_y(X, y, y_numeric=True)
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.arange(10).reshape(-1, 1)
y = np.arange(10) * 2.0
print(MeanRegressor().fit(X, y).score(X, y))This prints 0.0, because the model predicts the mean everywhere. cross_val_score with this class uses R² by default, since it calls score.
Class diagram
The diagram shows where the pieces sit. Your class inherits from one or more mixins first and from BaseEstimator last.
Order of base classes
Put the mixins on the left and BaseEstimator on the right:
class MyTransformer(TransformerMixin, BaseEstimator):
...Python resolves attributes using the method resolution order (MRO), which reads base classes left to right. Recent scikit-learn versions build estimator tags by walking up the MRO, with each class adding its own tags and passing control to the next class. BaseEstimator sits at the end of that chain and supplies the defaults.
If you write class Bad(BaseEstimator, ClassifierMixin), the chain can stop at BaseEstimator before the mixin adds its tags. The object may then not be recognized as a classifier. The symptom is quiet. Nothing fails at definition time, but a built-in tool can treat your classifier as an unlabeled estimator, for example by skipping stratified folds. The convention is fixed: mixins first, BaseEstimator last.
You can combine mixins when it makes sense, such as ClassifierMixin with TransformerMixin for a model that also transforms data. Keep BaseEstimator last.
What the base classes do not do
The base classes do not check anything about your logic. They will not:
- validate input. You call
check_arrayorcheck_X_yyourself. - confirm the object is fitted. You call
check_is_fitted. - set
n_features_in_orclasses_. You set them infit. - return
selffromfit. You must writereturn self. - make
transformdeterministic or stateless. That is your responsibility.
The last point matters for pipelines. Pipeline.fit calls fit_transform on every step but the last, and the next step receives whatever you return. If fit returns None, fit_transform fails with an AttributeError on NoneType.
Checking what you inherited
You can inspect an estimator to confirm the mixins did their job:
from sklearn.base import is_classifier, is_regressor
print(is_regressor(MeanRegressor()))
print(is_classifier(MeanRegressor()))
print([m for m in MeanRegressor.__mro__ if m is not object])The first call prints True, the second False. The MRO lists MeanRegressor, RegressorMixin, then BaseEstimator, plus any helper classes that the installed scikit-learn version adds between them.
Exercise
You write class Scaler(BaseEstimator, TransformerMixin) with fit and transform but forget return self in fit. What happens when you call Scaler().fit_transform(X), and what two changes fix the class?
Show answer
fit_transform calls self.fit(X).transform(X). Since fit returns None, the call becomes None.transform(X) and raises an AttributeError. The fixes are to end fit with return self, and to reorder the bases to class Scaler(TransformerMixin, BaseEstimator) so the mixin comes first and tags resolve correctly.
Exercise
Which method does ClassifierMixin give you, what metric does it compute, and what must your own fit still set so that tools can map predictions to labels?
Show answer
It gives you score(X, y), which returns the mean accuracy of predict(X) against y. Your fit must set classes_, for example with np.unique(y), because the mixin does not create it.