Sub topic 10
Cloning and tuning with GridSearchCV and nested parameters
This chapter assumes you can write a custom transformer with BaseEstimator and TransformerMixin, and that you know how Pipeline and cross-validation work. It explains how scikit-learn copies and reconfigures your estimator during a search. It also shows which constructor habits break that process.
Why tuning depends on cloning
GridSearchCV never fits the estimator you hand it. For every parameter combination and every cross-validation fold, it makes a fresh unfitted copy, sets the candidate parameters on the copy, fits it on the training part of the fold, and scores it on the validation part. Two functions make this possible, and both come from BaseEstimator:
get_paramsreads the constructor arguments of an estimator.set_paramschanges them.
sklearn.base.clone builds on get_params. It creates a new object of the same class, passes it the same constructor arguments, and discards everything learned during fit.
Save the transformer from the earlier chapter as clipper.py. The listings below import it.
# clipper.py
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
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)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but {self.__class__.__name__} "
f"is expecting {self.n_features_in_} features as input"
)
return np.clip(X, self.lower_, self.upper_)What clone does
clone follows four steps:
- It calls
get_params(deep=False)on the original to get a dictionary of constructor arguments. - It clones each value. Sub-estimators are cloned recursively, and other values are deep-copied.
- It calls
type(estimator)(**params)to build the new object. - It reads the parameters back from the new object. It raises
RuntimeErrorunless each one is the same object (is) that it passed in.
Step 4 is why the rule "store constructor arguments unchanged" is enforced and not merely advised. The following listing shows a constructor that breaks it.
from sklearn.base import BaseEstimator, clone
from clipper import QuantileClipper
class BadClipper(BaseEstimator):
def __init__(self, columns=(0,)):
self.columns = list(columns) # converts the argument: violates the contract
good = QuantileClipper(lower=0.05)
fitted = good.fit([[1.0], [2.0], [3.0], [100.0]])
fresh = clone(fitted)
print(fresh.get_params()) # {'lower': 0.05, 'upper': 0.99}
print(hasattr(fresh, "lower_")) # False: learned state is not copied
try:
clone(BadClipper())
except RuntimeError as err:
print("clone failed:", err)The clone of good keeps its parameters and loses lower_, upper_ and n_features_in_. The clone of BadClipper fails because list(columns) creates a new object, so the value read back is not the one clone passed in. Do any conversion inside fit, and store the result under a trailing-underscore name such as columns_.
Constructor shapes that break cloning
| Constructor pattern | What happens |
|---|---|
| `self.x = float(x)` or `list(x)` in `__init__` | `clone` raises `RuntimeError` because the stored value is a different object. |
| An argument `foo` stored as `self.bar` | `get_params` cannot find `foo`. It raises `AttributeError` (older versions returned `None`). |
| `*args` in the signature | `get_params` raises `RuntimeError`. Every parameter must be named. |
| `**kwargs` in the signature | The extra arguments are invisible to `get_params`, so they are lost on clone and cannot be tuned. |
| A mutable default such as `cols=[]` | All instances share one list, and any in-place edit affects every instance. Use `None` or a tuple and handle it in `fit`. |
| Validation in `__init__` | `set_params` bypasses `__init__`, so a bad grid value is never checked there. Validate in `fit`. |
How get_params and set_params work
BaseEstimator reads the signature of __init__ and treats each named argument as a parameter. Reading back is getattr(self, name). Your attribute names must therefore match your argument names exactly.
set_params calls setattr for each name you give it. It does not call __init__ again. It raises ValueError for names that are not parameters, and the message lists the valid ones.
from clipper import QuantileClipper
clipper = QuantileClipper()
clipper.set_params(lower=0.05, upper=0.95)
print(clipper.get_params()) # {'lower': 0.05, 'upper': 0.95}
try:
clipper.set_params(lowr=0.1) # typo
except ValueError as err:
print(err)Nested parameter names
Composite estimators such as Pipeline and ColumnTransformer hold other estimators. Their get_params(deep=True) returns their own parameters plus every sub-parameter, named <name>__<param> with a double underscore. set_params accepts the same names and forwards each value to the right sub-estimator. This is how a grid reaches inside a pipeline.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from clipper import QuantileClipper
pipe = Pipeline([
("clip", QuantileClipper()),
("clf", LogisticRegression(max_iter=1000)),
])
for name in sorted(pipe.get_params()):
if name.startswith("clip__"):
print(name)
# clip__lower
# clip__upper
pipe.set_params(clip__lower=0.05, clf__C=0.5)Step names are your own labels, so "clip" and "clf" are arbitrary. Avoid double underscores inside step names. A step name must also differ from every constructor parameter of the pipeline, such as memory, steps and verbose.
Tuning a custom transformer with GridSearchCV
The following listing tunes the clipper's bounds and the classifier's regularization together.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from clipper import QuantileClipper
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],
"clf__C": [0.1, 1.0, 10.0],
},
cv=5,
)
grid.fit(X, y)
print(grid.best_params_)
print(round(grid.best_score_, 3))
best_clip = grid.best_estimator_.named_steps["clip"]
print(best_clip.lower_)This grid has 2 × 2 × 3 = 12 candidates, and with 5 folds the search fits 60 pipelines. Each fit uses a fresh clone, so the lower_ values learned in one fold never reach another. After the search, refit=True (the default) clones the pipeline once more, applies best_params_, and fits it on all the data. That object is best_estimator_, and its fitted attributes are the ones you inspect.
The following diagram shows what happens for one candidate and one fold.
The clipper's bounds come from the training fold only, and the validation fold is transformed with those bounds. That separation is the reason to put the clipper inside the pipeline. If you clipped the whole dataset before the search, the quantiles would be computed from validation rows too, which is a form of data leakage.
Searching over whole steps
A grid value can be an entire estimator, and the name of a step is itself a parameter. This lets you compare steps with different parameter sets, or switch a step off with the string "passthrough".
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from clipper import QuantileClipper
X, y = load_iris(return_X_y=True)
pipe = Pipeline([("clip", QuantileClipper()), ("clf", LogisticRegression())])
param_grid = [
{
"clip": ["passthrough", QuantileClipper(lower=0.05, upper=0.95)],
"clf": [LogisticRegression(max_iter=1000)],
"clf__C": [0.1, 1.0],
},
{
"clip": ["passthrough", QuantileClipper(lower=0.05, upper=0.95)],
"clf": [RandomForestClassifier(random_state=0)],
"clf__n_estimators": [50, 100],
},
]
grid = GridSearchCV(pipe, param_grid, cv=5).fit(X, y)
print(grid.best_params_)A list of dictionaries is needed here because clf__C is invalid when clf is a random forest. Each dictionary is searched separately.
ColumnTransformer paths
Parameter names grow one __ segment per level of nesting. In a ColumnTransformer that contains a pipeline, the path includes the transformer name, the inner step name and the parameter.
from sklearn.compose import ColumnTransformer
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from clipper import QuantileClipper
X, y = load_iris(return_X_y=True)
prep = ColumnTransformer([
("num", Pipeline([("clip", QuantileClipper())]), [0, 1]),
("rest", "passthrough", [2, 3]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
grid = GridSearchCV(
model,
{"prep__num__clip__lower": [0.0, 0.05], "prep__num__clip__upper": [0.95, 1.0]},
cv=5,
).fit(X, y)
print(grid.best_params_)When a name is rejected, print model.get_params().keys(). The valid paths are listed there, and a missing path almost always means a wrong step name.
Checklist
- Every
__init__argument is stored unchanged under the same name. - No
*args, no**kwargs, no mutable defaults, and no validation in__init__. - Conversion and validation happen in
fit, and results go to underscore attributes. - Grid keys use
step__param, one level per nested estimator. - Any preprocessing that learns from data sits inside the pipeline being searched.
Exercise
A colleague writes def __init__(self, cols=None): self.cols = [] if cols is None else cols. clone works when cols is a list, but fails when cols is None. Why, and how should the class be fixed?
Show answer
With cols=None, clone passes None to the constructor. The new object stores a fresh [], and the value read back ([]) is not the None that was passed in. The identity check in clone therefore raises RuntimeError. With a list argument the constructor stores the same list object, so the check passes. The fix is self.cols = cols in __init__, and in fit something like cols = [] if self.cols is None else self.cols, with the result stored as self.cols_.
Exercise
A pipeline has steps named prep (a ColumnTransformer with a transformer named num that holds a QuantileClipper) and clf. Write the grid key that sets the clipper's upper parameter, and say how you would list every valid key.
Show answer
The key is prep__num__upper when num is the clipper itself, or prep__num__clip__upper when num is a pipeline whose clipper step is named clip. To list all valid keys, call pipe.get_params().keys() (deep=True is the default) on the outer pipeline.