Sub topic 4
Learned attributes end with an underscore
This chapter assumes you can write a Python class with __init__ and methods, and that you have used fit, transform and predict on built-in scikit-learn estimators. It also assumes you have read the earlier chapters on the estimator contract and on constructor rules. Here you will see how an estimator keeps what it learned, and why the naming of that state matters to scikit-learn.
Two kinds of state
A scikit-learn estimator holds two kinds of state, and the library keeps them strictly separate.
- Hyperparameters are the settings you choose before training, such as
lower=0.01inQuantileClipper. They are set in__init__, stored under the same name as the argument, and never changed by the estimator. - Learned attributes are the values computed from data inside
fit, such as the clipping bounds. They are created only infit, and their names end with a single underscore.
| Kind | Example | Created in | Name rule | Survives `clone`? |
|---|---|---|---|---|
| Hyperparameter | `self.lower` | `__init__` | Same as the argument name | Yes |
| Learned attribute | `self.lower_` | `fit` | Ends with `_` | No |
| Input-derived metadata | `self.n_features_in_` | `fit` | Ends with `_` | No |
Reading lower and lower_ side by side shows the split. lower is the quantile level you asked for. lower_ is the number the estimator computed from the training data using that level.
Why scikit-learn depends on the underscore
The suffix is a convention, but several parts of the library rely on it.
check_is_fitteddecides whether an estimator is fitted by looking at the instance's attributes. If it finds any whose name ends with_and does not start with__, the estimator counts as fitted. Otherwise it raisesNotFittedError.clonebuilds a new, unfitted estimator by reading the constructor parameters withget_paramsand passing them to the class. Anything not in the constructor signature is not copied, so learned attributes disappear.get_paramsreads the names in the__init__signature. A learned attribute is never reported as a parameter, and a parameter never ends with an underscore.- Users and tools inspect fitted models by convention. When someone sees
coef_orclasses_, they know it is the result of training.
The following diagram shows the lifecycle of an estimator.
A worked example
The estimator below centers each column and optionally divides by its standard deviation. It has one hyperparameter, with_std, and three learned attributes.
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_std=False):
self.with_std = with_std
def fit(self, X, y=None):
X = check_array(X)
self.mean_ = X.mean(axis=0)
if self.with_std:
scale = X.std(axis=0)
scale[scale == 0] = 1.0
self.scale_ = scale
else:
self.scale_ = np.ones(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_) / self.scale_
X = np.array([[1.0, 10.0], [3.0, 30.0]])
centerer = MeanCenterer(with_std=True)
try:
centerer.transform(X)
except NotFittedError:
print("not fitted yet")
centerer.fit(X)
print(centerer.mean_)
print([name for name in vars(centerer) if name.endswith("_")])
fresh = clone(centerer)
print(fresh.get_params())
print(hasattr(fresh, "mean_"))Running it prints the following.
not fitted yet
[ 2. 20.]
['mean_', 'scale_', 'n_features_in_']
{'with_std': True}
FalseFour things happen here.
- Before
fit, the object has no attribute ending in_, socheck_is_fittedraisesNotFittedError. - After
fit, three attributes exist, and the estimator counts as fitted without any extra bookkeeping. - The clone keeps
with_std=Truebecause that is a constructor parameter. - The clone has no
mean_. This is whyGridSearchCVandcross_val_scorecan fit many copies without them sharing state.
Notice that fit does not write to self.with_std. The derived scale_ is stored separately, so the parameter still holds exactly what the user passed.
The standard learned attributes
Some learned attributes have agreed names. Use them so that your estimator behaves like the built-in ones.
n_features_in_is the number of columns seen duringfit.transformandpredictcompare against it to catch a mismatch.feature_names_in_holds column names whenfitreceives a DataFrame with string column names. Scikit-learn's validation helpers set it for you. If you only callcheck_array, it is not set.classes_is the sorted array of labels in a classifier.MeanCentroidClassifierfrom the previous chapter builds it withnp.unique.coef_,intercept_,feature_importances_and similar names are used by linear and tree models. Reuse them when your attribute means the same thing, and choose a distinct name when it does not.
For your own attributes, name what the value is, not how you got it. centroids_ is clearer than tmp_.
Rules for writing `fit`
Create learned attributes only in fit
Do not set self.mean_ = None in __init__ as a placeholder. A placeholder ending in an underscore makes check_is_fitted report the estimator as fitted. Calling transform on it would then fail later with a confusing error instead of a clear NotFittedError. The same rule applies to __init__ setting a parameter and then rewriting it, for example self.lower = lower or 0.01. Do not do either.
Make fit replace state, not add to it
Calling fit a second time must give the same result as calling it once on a fresh object. Scikit-learn tools rely on this, and so do users who refit in a notebook. The class below breaks that rule.
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_array
class BadCounter(BaseEstimator):
def fit(self, X, y=None):
X = check_array(X)
if not hasattr(self, "n_seen_"):
self.n_seen_ = 0
self.n_seen_ += X.shape[0]
return self
X = np.zeros((3, 2))
counter = BadCounter().fit(X).fit(X)
print(counter.n_seen_)It prints 6, although the last training set had three rows. The fix is to assign, not accumulate: self.n_seen_ = X.shape[0]. If you really need incremental learning, that is a separate method called partial_fit, and it has its own rules.
Return self
fit must return self. fit_transform from TransformerMixin, Pipeline and the est.fit(X).predict(X) idiom all depend on it.
Do not mutate the input or the parameters
Compute new arrays instead of changing X in place. If fit stores a reference to a mutable parameter, such as a list, and later modifies it, then every clone that shares the same list object sees the change. Copy first, and put the copy in a learned attribute.
Keep learned values consistent
If fit stores several attributes that depend on each other, such as mean_ and scale_, set them all in the same call. A half-fitted object, which can occur when an exception is raised midway, will pass check_is_fitted once the first attribute exists. Validate the input before assigning anything, as the examples do by calling check_array first.
Private and derived values
Sometimes you want to store a helper that users should not rely on, such as a cached lookup table. Give it a leading underscore, for example _lookup, and still set it in fit. A name starting with one underscore and not ending with one is ignored by check_is_fitted, so make sure at least one public learned attribute with a trailing underscore is also set. Do not use a double leading underscore to hide a value. check_is_fitted skips those names, and Python rewrites them in ways that interact badly with clone.
If a value can be computed cheaply from learned attributes, consider a property instead of another stored attribute. A property cannot go out of sync with the data it derives from.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Setting `self.mean_` in `__init__` | `transform` before `fit` fails with an `AttributeError` or wrong numbers, not `NotFittedError` | Assign only in `fit` |
| Learned attribute without underscore, such as `self.mean` | `check_is_fitted` raises `NotFittedError` after `fit`, and `check_estimator` complains | Rename to `mean_` |
| Overwriting a parameter in `fit` | `clone` and `set_params` give different results from the original | Store the derived value in a new `name_` attribute |
| Accumulating state across `fit` calls | Results change on refit | Assign fresh values every time |
| Forgetting `n_features_in_` | Wrong column counts pass silently | Set it in `fit` and compare in `transform` |
Exercise
A teammate writes __init__(self, threshold=0.5) and then, in fit, runs self.threshold = np.median(X) when threshold is None. Name two problems this causes, and show the corrected lines.
Show answer
First, fit changes a constructor parameter, so get_params now returns the median instead of the value the user passed, and a clone built from it is configured differently from the original. Second, the learned value has no trailing underscore, so the estimator can look unfitted to check_is_fitted or conventions checks. Corrected: in fit, write self.threshold_ = np.median(X) if self.threshold is None else self.threshold, and use self.threshold_ in transform.
Exercise
You call check_is_fitted(est) on a new MeanCenterer(with_std=True) and it raises NotFittedError. After est.fit(X) it passes. Then you run clone(est) and call check_is_fitted on the result. What happens, and why?
Show answer
It raises NotFittedError again. clone creates a new object from get_params(), which contains only with_std. The attributes mean_, scale_ and n_features_in_ are not constructor parameters, so they are not copied, and the clone has no attribute ending in an underscore.
Exercise
Why does BadCounter print 6, and what single-line change makes it print 3?
Show answer
fit only creates n_seen_ when it does not exist, then adds the row count to it, so the second fit call adds to the value left by the first. Replace the three lines with self.n_seen_ = X.shape[0], which assigns a fresh value on every call.