Sub topic 7
Tuning hyperparameters across steps
This chapter assumes you can build a Pipeline, and that you know what cross-validation and a train/test split do. You will tune settings that live inside different pipeline steps, using one search object.
Why tune the whole pipeline
A hyperparameter is a setting you choose before training, such as the regularization strength C of logistic regression. Some of these settings sit in preprocessing steps, not in the model. If you tune only the model on data you already scaled or imputed, you repeat the leakage problem from earlier chapters: the preprocessing saw the validation rows.
GridSearchCV accepts a pipeline as its estimator. For every candidate setting and every fold, it clones the pipeline and fits all steps on the training part of that fold only. It then scores on the held-out part.
The step__parameter naming rule
A pipeline exposes its steps' parameters through names of the form <step name>__<parameter name>, with two underscores. In a pipeline built as Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression())]), the regularization strength is clf__C.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
pipe = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
# Parameter names are <step name>__<parameter name>.
param_grid = {"clf__C": [0.01, 0.1, 1, 10]}
search = GridSearchCV(pipe, param_grid, cv=5)
search.fit(X_train, y_train)
print(search.best_params_)
print(search.score(X_test, y_test))best_params_ shows the winning combination. After the search, GridSearchCV refits the best pipeline on all of X_train. So search.score and search.predict use that refitted pipeline. The test set is touched only once, at the end.
If you are unsure of a name, print pipe.get_params().keys(). It lists every valid key.
Nested names
Names nest when a step is itself a pipeline or a ColumnTransformer. Each level adds a __. With the earlier mixed-column model, where the pipeline has a prep step, a ColumnTransformer with a num branch, and a scale step inside it, you could address a setting like this:
param_grid = {
"prep__num__impute__strategy": ["mean", "median"],
"clf__C": [0.1, 1, 10],
}Read the first key from left to right: pipeline step prep, transformer num, inner step impute, parameter strategy.
Searching over whole steps
You can also swap a step for another estimator. Setting a step name as a key replaces that step. Setting it to "passthrough" skips it.
from sklearn.decomposition import PCA
param_grid = [
{
"scale": [StandardScaler(), "passthrough"],
"clf__C": [0.1, 1, 10],
},
{
"scale": [StandardScaler()],
"clf": [PCA(n_components=10), ],
},
]Use this carefully. The second grid above is wrong, because PCA is not a classifier, and it would fail at fit time. A step that replaces a final estimator must itself be a classifier. Keep each grid consistent with the step's role.
A list of dictionaries, as in param_grid above, is the correct way to search several separate grids. Parameters in different dictionaries are never combined.
Common errors
ValueError: Invalid parameter: the step name or parameter name is misspelled, or you used one underscore. Checkget_params().keys().- Using the step's class name: the key uses the name you gave the step.
make_pipelinelowercases class names, soStandardScalerbecomesstandardscalerand logistic regression becomeslogisticregression. - Tuning on the test set: pass only training data to
search.fit. Reserve the test set for the final score. - Grid size: the number of fits is combinations × folds. Three parameters with five values each, with
cv=5, is 625 fits, plus the final refit.
Exercise
A pipeline is created with make_pipeline(StandardScaler(), LogisticRegression()). What key would you use in a grid to tune C, and why is tuning inside GridSearchCV safer than scaling X_train first and then searching over the model alone?
Show answer
The key is logisticregression__C, because make_pipeline names steps after their lowercased class names. Inside GridSearchCV, the scaler is refit on the training part of every fold, so validation rows do not influence the scaling statistics. Scaling X_train first would let each validation fold shape the mean and standard deviation, which leaks information.
Exercise
A grid has clf__C with 4 values and prep__num__impute__strategy with 2 values. With cv=5, how many model fits does the search run, not counting the final refit?
Show answer
4 × 2 = 8 combinations, and 8 × 5 = 40 fits.