Sub topic 3
Constructor rules: store parameters, do nothing else
This chapter assumes you can write Python classes with inheritance, use scikit-learn estimators with fit, predict and transform, and know what cross-validation does. It explains the rule for __init__ in a scikit-learn estimator, why the rule exists, and which errors appear when you break it.
The rule
An estimator's __init__ method does two things:
- It accepts hyperparameters as keyword arguments with default values.
- It stores each one, unchanged, in an attribute with the same name.
It does nothing else. It does not validate, convert, compute, copy, or look at data. Everything that depends on the values happens in fit.
class QuantileClipper(TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upperThis looks too simple to need a chapter. The reason is that scikit-learn never asks your class what its parameters are. It works them out from the constructor signature and then rebuilds your object from them.
Why the rule exists
BaseEstimator.get_params inspects the signature of __init__. For each argument name it calls getattr(self, name). set_params does the reverse: it calls setattr for each name you pass. Neither method runs your constructor body.
Three tools depend on these two methods:
clonebuilds a fresh, unfitted copy of an estimator. It readsget_params, copies the values, and calls the constructor with them. Then it checks that each stored value is the same object that was passed in.GridSearchCVandRandomizedSearchCVclone the estimator for every candidate and fold, then callset_paramswith the candidate values.PipelineandColumnTransformerexpose the parameters of their steps with thestep__paramsyntax, which is built onget_params(deep=True).
If the constructor changes a value, renames it, or skips it, this chain breaks. Failures are loud when you are lucky and silent when you are not.
A correct estimator in use
This version stores its parameters unchanged and validates them in fit.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn.utils.validation import check_array, check_is_fitted
class QuantileClipper(TransformerMixin, BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
if not 0 <= self.lower < self.upper <= 1:
raise ValueError(
"Need 0 <= lower < upper <= 1, "
f"got lower={self.lower}, upper={self.upper}"
)
X = check_array(X)
self.lower_ = np.quantile(X, self.lower, axis=0)
self.upper_ = np.quantile(X, self.upper, axis=0)
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
check_is_fitted(self)
X = check_array(X)
return np.clip(X, self.lower_, self.upper_)
clipper = QuantileClipper(lower=0.05)
print(clipper.get_params())
clipper.set_params(upper=0.95)
clipper.fit(np.arange(20.0).reshape(10, 2))
fresh = clone(clipper)
print(fresh)
print(fresh is clipper)
print(hasattr(clipper, "lower_"), hasattr(fresh, "lower_"))The output is:
{'lower': 0.05, 'upper': 0.99}
QuantileClipper(lower=0.05, upper=0.95)
False
True FalseThree things are visible here. get_params works with no code from you, because the argument names match the attribute names. clone keeps the hyperparameters but drops everything learned (lower_ is gone), so a clone is always unfitted. The printed representation shows only parameters that differ from their defaults.
What breaks when you do more
Converting or copying a value
from sklearn.base import BaseEstimator, TransformerMixin, clone
class BadSelector(TransformerMixin, BaseEstimator):
def __init__(self, columns=(0, 1)):
self.columns = list(columns) # converts the value
clone(BadSelector()) # raises RuntimeErrorclone passes the stored list back into the constructor. The constructor builds a new list from it, so the stored object is no longer the one that was passed in. clone detects this and raises a RuntimeError saying that the constructor either does not set or modifies a parameter. The fix is to store columns as given and call list(self.columns) in fit, saving the result as self.columns_.
Renaming a parameter
class BadScaler(BaseEstimator):
def __init__(self, factor=1.0):
self.scale = factor # attribute name differs from argument nameget_params looks for an attribute called factor and raises AttributeError. The argument name and the attribute name must be identical.
Validating in the constructor
class BadClipper(BaseEstimator):
def __init__(self, lower=0.01, upper=0.99):
if lower >= upper:
raise ValueError("lower must be below upper")
self.lower = lower
self.upper = upperThis looks careful, but set_params does not call __init__. The following code gets past the check:
clipper = BadClipper()
clipper.set_params(lower=5.0) # no error, now lower > upperGrid search sets parameters this way, so the invalid state reaches fit anyway. The constructor check protects only direct construction, which gives a false sense of safety. Validate in fit, where every path converges.
Mutable default arguments
class BadCollector(BaseEstimator):
def __init__(self, names=[]): # one list shared by every instance
self.names = namesA default list is created once and shared by all instances. If any method appends to self.names, every instance sees the change. Use None as the default and resolve it in fit:
class Collector(BaseEstimator):
def __init__(self, names=None):
self.names = names
def fit(self, X, y=None):
self.names_ = [] if self.names is None else list(self.names)
return selfImmutable defaults such as numbers, strings, None and tuples are safe.
Learning something in the constructor
class BadFitter(BaseEstimator):
def __init__(self, X_ref=None):
self.X_ref = X_ref
self.mean_ = X_ref.mean(axis=0) # computed from dataLearned values belong in fit. A constructor that computes from data also crashes when clone calls it with defaults, and it stores state that clone would silently discard.
Rules at a glance
| Rule | Reason | Where the work goes |
|---|---|---|
| Every argument has a default | `clone` and tools such as `check_estimator` build instances with no arguments | Constructor signature |
| Attribute name equals argument name | `get_params` uses `getattr(self, name)` | Constructor body |
| Store the value as passed | `clone` checks object identity | Constructor body |
| No validation | `set_params` bypasses `__init__` | Start of `fit` |
| No conversion or copying | The identity check fails | `fit`, stored in `name_` attributes |
| No `*args` or `**kwargs` | `get_params` needs a fixed list of names | Name every parameter |
| No data-dependent computation | Constructors run before any data exists | `fit` |
| Immutable defaults | Mutable defaults are shared between instances | Use `None`, resolve in `fit` |
Parameters that are estimators
A parameter can itself be an estimator, as in Pipeline or a bagging ensemble. The same rule applies: store the object unchanged. get_params(deep=True) then also reports the inner estimator's parameters as param__subparam, and set_params accepts those names.
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
class ScaleThenShift(TransformerMixin, BaseEstimator):
def __init__(self, scaler=None, shift=0.0):
self.scaler = scaler
self.shift = shift
def fit(self, X, y=None):
scaler = StandardScaler() if self.scaler is None else self.scaler
self.scaler_ = clone(scaler).fit(X)
return self
def transform(self, X):
return self.scaler_.transform(X) + self.shift
est = ScaleThenShift(scaler=StandardScaler(with_std=False))
print(est.get_params()["scaler__with_std"])
est.set_params(scaler__with_mean=False)
print(est.scaler.with_mean)The output is False and then False. Notice that fit clones the inner estimator into scaler_ and fits the clone. Fitting self.scaler directly would change a parameter object during fit. That would leak state between clones and between cross-validation folds, because clone of a parameter that is an estimator is a deep clone only when it goes through clone, and a direct fit on the shared object ignores that.
Practical checks
- After writing
__init__, callest.get_params()andclone(est)in a shell. Both fail quickly if the rule is broken. - Read the constructor and ask whether every line is a plain
self.x = x. If a line is anything else, move it. - Run
check_estimator(covered in a later chapter) to catch violations you did not think of.
Exercise
A colleague writes the class below. Name the two ways it breaks scikit-learn conventions, and say how to fix each. class Shrinker(TransformerMixin, BaseEstimator): def _init(self, strength=0.5): if strength < 0: raise ValueError("strength must be non-negative") self.shrinkstrength = strength
Show answer
First, the attribute is named shrinkstrength but the argument is strength, so getparams calls getattr(self, "strength") and raises AttributeError. Store it as self.strength = strength. Second, the check in _init is skipped by setparams, so grid search can set a negative strength without an error. Move the check to the start of fit, using self.strength.