Sub topic 3
Constructor rules: store parameters, do nothing else
This chapter assumes you know Python classes and inheritance. It also assumes you have used fit, transform and GridSearchCV with built-in estimators. It covers the rules for __init__ in a custom estimator and the reasons behind them.
The rule
An estimator's __init__ method does one thing. It copies each argument to an attribute with the same name, unchanged.
- Every argument is a keyword argument with a default value.
- Each attribute has the same name as its argument.
- Nothing is validated, converted, computed or defaulted in the constructor.
- There is no
*argsor**kwargs.
Why scikit-learn depends on it
BaseEstimator.get_params reads the names in your __init__ signature and calls getattr(self, name) for each one. Three features rest on that:
clonebuilds a fresh, unfitted copy withtype(est)(**est.get_params(deep=False)).set_params, and thereforeGridSearchCV, assigns new values directly to the attributes.reprshows the current parameters.
If an attribute differs from the argument that created it, all three break. clone checks that the values passed to the new object are the same objects the new object stores.
A constructor that breaks cloning
from sklearn.base import BaseEstimator, TransformerMixin, clone
class BadScaler(TransformerMixin, BaseEstimator):
def __init__(self, percent=0.5):
self.percent = percent * 100 # modifies the argument
def fit(self, X, y=None):
return self
try:
clone(BadScaler())
except RuntimeError as err:
print("clone failed:", err)clone passes percent=50.0 to the new object, which stores 5000.0. The stored value is not the one that was passed in, so clone raises RuntimeError.
Moving the work into fit
Put conversion and validation in fit. By then the parameters are final, because set_params may have changed them after construction.
from sklearn.base import BaseEstimator, TransformerMixin, clone
class Clipper(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(
f"Need 0 <= lower < upper <= 1, got {self.lower} and {self.upper}"
)
return self
clipper = Clipper(lower=0.05)
print(clipper.get_params())
copy = clone(clipper)
copy.set_params(upper=0.9)
print(copy)
try:
Clipper(lower=0.9, upper=0.1).fit([[1.0], [2.0]])
except ValueError as err:
print("fit rejected the parameters:", err)Creating Clipper(lower=0.9, upper=0.1) succeeds. The error appears only when you call fit.
Mutable defaults and nested estimators
Do not use a list or dict as a default value. All instances would share it. Use None and build the real value in fit, or use a tuple.
If a parameter is itself an estimator, store it as given and call clone(self.estimator) in fit before fitting it. This leaves the object the user passed in untouched. get_params(deep=True) also exposes the inner parameters as estimator__name.
Exercise
A colleague writes self.columns = list(columns) in __init__ so that tuples and lists both work. What goes wrong, and where should the conversion happen?
Show answer
The stored attribute is a new list, not the object that was passed in. clone then finds that the new object's parameter is not the object it passed to the constructor, and raises RuntimeError. Keep self.columns = columns in __init__. Do list(self.columns) inside fit and store the result in a learned attribute such as columns_.