Sub topic 1
What scikit-learn expects from an estimator
Prerequisites
This chapter assumes Python classes and inheritance, NumPy arrays, and basic use of scikit-learn’s fit, transform, and predict methods. You should also know why training data must be kept separate from test data.
The estimator contract
An estimator is a Python object that follows scikit-learn’s common interface. The main methods are:
fit(X, y)learns from training data and returnsself.transform(X)changes feature data, usually using information learned byfit.predict(X)produces target predictions from learned information.
Transformers implement fit and transform. Predictors implement fit and predict. A classifier predicts categories, while a regressor predicts numeric values.
Base classes and mixins
BaseEstimator provides standard parameter handling through get_params and set_params. These methods allow pipelines and hyperparameter searches to inspect and configure your estimator.
TransformerMixin provides fit_transform, which normally calls fit followed by transform. ClassifierMixin provides a classification-oriented score method. RegressorMixin provides a regression-oriented score method.
A custom transformer commonly starts like this:
from sklearn.base import BaseEstimator, TransformerMixin
class AddConstant(TransformerMixin, BaseEstimator):
def __init__(self, constant=1.0):
self.constant = constant
def fit(self, X, y=None):
return self
def transform(self, X):
return X + self.constantConstructor rules
The constructor should only assign its arguments to attributes with the same names. It should not inspect data, validate arrays, or learn values. Scikit-learn clones estimators by reconstructing them from these parameters, so changing or hiding them breaks composition.
Put data-dependent validation and learning in fit. Put data-dependent checks and conversion in transform or predict.
> Do not store a mutable default such as options={} in a constructor. Prefer options=None, then create a new dictionary when needed.
Learned attributes use an underscore
Attributes created during fit should end in _, such as mean_, classes_, or n_features_in_. This convention separates configuration from fitted state. It also makes it clear which attributes are unavailable before fitting.
A method that needs learned state should check that state exists and raise a useful error when the estimator is unfitted.
Exercise
Why should a constructor avoid calculating a mean from training data?
Show answer
The constructor has no training data and must remain reproducible for cloning. Learning belongs in fit.