Sub topic 4
Learned attributes end with an underscore
This chapter assumes you know Python classes, the fit/transform pattern, and the constructor rule from the previous chapter: __init__ only stores its arguments.
Two kinds of attributes
An estimator holds two kinds of attributes. scikit-learn tells them apart by name.
| Kind | Example | Set in | Name ends with `_` |
|---|---|---|---|
| Constructor parameter | `with_mean`, `lower` | `__init__` | No |
| Learned attribute | `mean_`, `classes_`, `n_features_in_` | `fit` | Yes |
Parameters are what you chose. Learned attributes are what the estimator computed from the training data.
Why the underscore matters
Three pieces of scikit-learn machinery depend on this convention.
check_is_fittedlooks through the estimator's attributes for any name that ends with_and does not start with__. If it finds none, it raisesNotFittedError.get_paramsreads only the constructor arguments.cloneuses those parameters to build a new, unfitted copy, so learned attributes are never copied.- Calling
fitagain overwrites the learned attributes. The estimator never keeps state from an earlier fit.
Seeing it work
The transformer below learns one mean per column. Run it to watch each of the three behaviors.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn.exceptions import NotFittedError
from sklearn.utils.validation import check_array, check_is_fitted
class MeanCenterer(TransformerMixin, BaseEstimator):
def __init__(self, with_mean=True):
self.with_mean = with_mean
def fit(self, X, y=None):
X = check_array(X)
if self.with_mean:
self.mean_ = X.mean(axis=0)
else:
self.mean_ = np.zeros(X.shape[1])
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return X - self.mean_
X = np.array([[1.0, 2.0], [3.0, 6.0]])
centerer = MeanCenterer()
try:
centerer.transform(X)
except NotFittedError:
print("not fitted yet")
centerer.fit(X)
print(centerer.mean_)
copy = clone(centerer)
print(hasattr(copy, "mean_"))The output is not fitted yet, then [2. 4.], then False. The clone has the same with_mean setting but no mean_.
Rules to follow
- Create every learned attribute inside
fit, and give it a trailing underscore. - Do not set learned attributes in
__init__, even toNone. An attribute such asself.mean_ = Nonemakescheck_is_fittedtreat the object as fitted. - Do not modify learned attributes in
transformorpredict. Those methods should only read them, so repeated calls give the same result. - Record
n_features_in_infit. You can then compare it with the input intransformand raise a clear error when the column count changes. - A helper attribute with a leading underscore, such as
_cache, is allowed, but it does not count as fitted state.
Common errors
NotFittedErrorright after callingfit.fitprobably stored its results without a trailing underscore, for exampleself.mean. Rename the attribute.- A transformer that works only once. It probably changes its own state, or the input array, in
transform. Return a new array and leave the learned attributes alone. - Leaked state between folds. If
__init__creates a mutable learned structure, such asself.seen_ = [], cross-validation folds can share it.
Exercise
A colleague writes a transformer whose fit ends with self.scale = X.std(axis=0) and returns self. transform begins with check_is_fitted(self). What happens when transform is called after fit, and how do you fix it?
Show answer
check_is_fitted raises NotFittedError, because no attribute name ends with an underscore. Rename the attribute to scale_, and update transform to read self.scale_.