Sub topic 10
Cloning and tuning with GridSearchCV and nested parameters
This chapter assumes you can write a custom transformer with BaseEstimator, and that you know what Pipeline and cross-validation do. Here you will see why the constructor rules matter. Grid search relies on them completely.
How scikit-learn copies an estimator
Cross-validation needs a fresh, unfitted estimator for every fold. sklearn.base.clone builds one. It does not copy the object with copy.deepcopy. It reads the constructor parameters with get_params, builds a new object from them, and then checks that the new object stored each parameter unchanged.
BaseEstimator.get_params finds the parameter names by inspecting the signature of __init__. For each name, it reads the attribute with the same name. This is why each constructor argument must be stored as self.<argument> with no changes.
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):
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_)
est = QuantileClipper(lower=0.05)
est.fit(np.random.rand(100, 3))
copy = clone(est)
print(est.get_params()) # {'lower': 0.05, 'upper': 0.99}
print(hasattr(copy, "lower_")) # False: the clone is unfittedThe clone keeps lower=0.05 but drops everything learned, such as lower_. That is the reason learned values get a trailing underscore. They are not parameters, so clone ignores them.
Nested parameters
A Pipeline exposes the parameters of its steps as <step name>__<parameter>. The double underscore can repeat for deeper nesting, for example prep__num__scale__with_mean inside a ColumnTransformer. Your custom class gets this for free from get_params and set_params.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
X, y = load_iris(return_X_y=True)
pipe = Pipeline([
("clip", QuantileClipper()),
("clf", LogisticRegression(max_iter=1000)),
])
grid = GridSearchCV(
pipe,
param_grid={"clip__lower": [0.0, 0.05], "clip__upper": [0.95, 1.0]},
cv=5,
)
grid.fit(X, y)
print(grid.best_params_)For each candidate and each fold, GridSearchCV runs the steps in the diagram below.
Because each fold fits a fresh clone, the clipping bounds are learned from the training fold only. The validation fold is never used to compute lower_ or upper_, so there is no leakage.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: Invalid parameter 'clip__low'` | The name does not match a constructor argument | Check the names in `pipe.get_params().keys()` |
| `RuntimeError: Cannot clone object` | `__init__` changed a value, for example `self.lower = lower * 2` | Store the value as given and transform it in `fit` |
| `AttributeError` from `get_params` | An argument has no attribute with the same name | Name the attribute after the argument |
| Best score never changes | The step name in `param_grid` points to the wrong step | Print `pipe.named_steps` |
Mutable defaults
Never use a list or dict as a default value. Use None and create the object in fit. clone copies parameters with clone(param, safe=False), but a shared mutable default can still be changed by one instance and affect others.
Exercise
You write __init__(self, alpha=1.0) and inside it self.alpha = max(alpha, 0.0). What goes wrong when GridSearchCV clones the estimator with alpha=-1, and where should the max call go?
Show answer
clone builds the new object with alpha=-1, then finds that the stored self.alpha is 0.0, which is not the same object it passed in. It raises a RuntimeError. Store self.alpha = alpha in __init__ and apply max(self.alpha, 0.0) in fit, ideally saving the result in a trailing-underscore attribute such as alpha_.