Sub topic 7
Tuning hyperparameters across steps
This chapter assumes you can build a Pipeline or make_pipeline object. It also assumes you know how to run cross_val_score on one, and how ColumnTransformer groups columns. You will use that knowledge to tune settings in every step of a pipeline, using one search object and one cross-validation loop.
Why tune the pipeline instead of the model
A hyperparameter is a setting you choose before training, such as the regularization strength C of a logistic regression. In a pipeline, preprocessing steps have hyperparameters too. An imputer has a strategy. A dimensionality reducer has n_components. A one-hot encoder has min_frequency. These settings affect the final score just as much as the model's own settings.
If you tune only the final model, you leave the other steps fixed at defaults. You also risk leakage if you preprocess the data before you tune. Passing the whole pipeline to a search object solves both problems. The search clones the pipeline for each candidate and each fold. It refits every step on the training part of the fold, then scores on the validation part.
The step__parameter naming convention
A search object needs to address a parameter that lives inside a step. Scikit-learn uses the step name, two underscores, and the parameter name. For a step named clf with a parameter C, the key 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))Four values of C and five folds give 20 fits. After the search, GridSearchCV refits the best combination on all of X_train. That is one more fit, so 21 in total. The test set is touched only once, in the final score call.
If you built the pipeline with make_pipeline, the step names are generated from the lowercase class names. The logistic regression step is called logisticregression, so the key is logisticregression__C. Explicit names with Pipeline are easier to read and stay stable if you change the model class.
Finding valid names
You do not have to guess names. Every estimator has a get_params() method that lists every parameter it accepts, including the nested ones. The search uses the same method to validate your grid.
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
names = sorted(k for k in model.get_params() if k.endswith("strategy"))
print(names)The output contains prep__cat__impute__strategy and prep__num__impute__strategy. Each double underscore descends one level: the prep step, then the num or cat transformer inside the ColumnTransformer, then the impute step inside that inner pipeline, then the strategy parameter. Nesting can go as deep as your pipeline does.
Tuning preprocessing and the model together
Once you can name a nested parameter, a grid can mix settings from several steps. The next example tunes the imputation strategy, the regularization strength, and the one-hot encoder's handling of rare categories. It uses a synthetic dataset with missing values and one categorical column, so it runs as shown.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 300
df = pd.DataFrame({
"age": rng.normal(40, 10, n),
"income": rng.normal(60000, 15000, n),
"city": rng.choice(["Oslo", "Bergen", "Trondheim", "Tromso"], n),
})
y = ((df["age"] + df["income"] / 2000 + rng.normal(0, 5, n)) > 70).astype(int)
df.loc[rng.choice(n, 30, replace=False), "age"] = np.nan
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer()),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="infrequent_if_exist"), ["city"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression(max_iter=1000))])
param_grid = {
"prep__num__impute__strategy": ["mean", "median"],
"prep__cat__min_frequency": [None, 80],
"clf__C": [0.1, 1, 10],
}
search = GridSearchCV(model, param_grid, cv=5, scoring="roc_auc")
search.fit(df, y)
print(search.best_params_)
print(round(search.best_score_, 3))This grid has 2 × 2 × 3 = 12 combinations, so 60 fits plus the refit. Grids multiply quickly, which is the main practical limit of this approach. The scoring argument controls which metric ranks the combinations. Pick it to match the problem. Accuracy is a poor choice for imbalanced classes.
Swapping whole steps
A step is just an object, so a grid can replace it. Give a step name a list of estimators and the search tries each one. The string "passthrough" replaces a step with a no-op, which lets you test whether a step helps at all.
When different choices need different parameters, use a list of dictionaries. The search runs the grids in the list one after another and treats them as a single search.
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, StandardScaler
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()),
("reduce", PCA()),
("clf", LogisticRegression(max_iter=1000)),
])
scalers = [StandardScaler(), MinMaxScaler()]
param_grid = [
{
"scale": scalers,
"reduce": ["passthrough"],
"clf__C": [0.1, 1, 10],
},
{
"scale": scalers,
"reduce": [PCA()],
"reduce__n_components": [5, 10, 15],
"clf__C": [0.1, 1, 10],
},
]
search = GridSearchCV(pipe, param_grid, cv=5, n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_)
print(round(search.score(X_test, y_test), 3))The first grid skips PCA, so it has no reduce__n_components key. Putting reduce__n_components in that grid would fail, because a string has no such parameter. The second grid sets reduce to a PCA object and then tunes it. The search applies the step replacement before the nested parameters.
The first grid has 2 × 1 × 3 = 6 combinations and the second has 2 × 1 × 3 × 3 = 18, so there are 24 candidates in total. Each candidate is fitted five times.
Reading the results
search.best_params_ and search.best_score_ give the winner. The full table is in cv_results_, which loads cleanly into pandas.
import pandas as pd
results = pd.DataFrame(search.cv_results_)
cols = ["params", "mean_test_score", "std_test_score", "rank_test_score"]
print(results[cols].sort_values("rank_test_score").head())Look at std_test_score as well as the mean. If the top five candidates differ by less than one standard deviation, the search cannot tell them apart. In that case prefer the simplest one, such as fewer components or stronger regularization.
The attribute search.best_estimator_ is the refit pipeline. You can use it like any pipeline: call predict, slice it, or save it. Calling search.predict does the same thing.
Scaling up: randomized search
A grid tries every combination, which is wasteful when some parameters matter much more than others. RandomizedSearchCV samples a fixed number of combinations. It accepts the same step__param keys. Instead of a list, you can give a distribution from scipy.stats, which suits a parameter like C that varies over orders of magnitude.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
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)),
])
search = RandomizedSearchCV(
pipe,
{"clf__C": loguniform(1e-3, 1e2)},
n_iter=20,
cv=5,
random_state=0,
)
search.fit(X_train, y_train)
print(search.best_params_)The cost is n_iter × cv fits, regardless of how many parameters you add. Setting random_state makes the sampling repeatable.
Common errors and pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: Invalid parameter 'C' for estimator Pipeline` | The key lacks the step prefix. | Use `clf__C`, and check names with `get_params().keys()`. |
| Invalid parameter `logisticregression__C` with a named pipeline | The step was named `clf`, not generated by `make_pipeline`. | Use the step name you gave in `Pipeline`. |
| A grid fails when one option has no `n_components` | A single dictionary mixes `"passthrough"` with a nested key. | Split the grid into a list of dictionaries. |
| Every score is `nan` and a warning appears | Some combination raised an error during fitting. | Set `error_score="raise"` to see the real exception. |
| `best_score_` is higher than the test score | The best of many candidates is optimistically biased. | Report the held-out test score. |
| A search runs for hours | The grid size multiplies by the number of folds. | Use `RandomizedSearchCV`, a smaller grid, or `n_jobs=-1`. |
An honest estimate of the tuned model
best_score_ is the highest of many cross-validation scores, so it is biased upward. To estimate how well the whole tuning procedure generalizes, run nested cross-validation. Pass the search object itself to cross_val_score. The outer loop holds out data that the inner search never sees.
from sklearn.model_selection import cross_val_score
outer_scores = cross_val_score(search, X_train, y_train, cv=3)
print(outer_scores.mean())This multiplies the cost by the number of outer folds. Use it when you need a trustworthy number, for example to compare two modeling approaches, and not in every experiment.
Cost and caching
During a search, a candidate that changes only clf__C still refits the scaler and any other expensive early steps on every fold. If the early steps are slow, for example a large PCA or a text vectorizer, the repeated work dominates the runtime. A later chapter covers the memory argument of Pipeline, which stores fitted transformers so that candidates with identical early settings reuse them. For now, keep expensive steps out of the grid when you can, and tune them in a separate, smaller search.
Exercise
A pipeline is built as make_pipeline(SimpleImputer(), StandardScaler(), SVC()). Write the grid key that sets the imputer's strategy and the key that sets the SVC's C. Then explain how you would confirm the names.
Show answer
The imputer key is simpleimputer__strategy and the SVC key is svc__C. make_pipeline names each step with the lowercase class name. You can confirm the names by calling pipe.get_params().keys() or by looking at pipe.named_steps.
Exercise
You want to compare three setups in one search: no dimensionality reduction, PCA with 5 or 10 components, and PCA with whitening turned on. Why must you use a list of dictionaries, and what goes in the first dictionary?
Show answer
The no-reduction option sets the step to "passthrough", which has no parameters. A key such as reduce__n_components would raise an error for it. So the first dictionary has "reduce": ["passthrough"] and the other keys that apply to every setup, such as clf__C. The second dictionary has "reduce": [PCA()], "reduce__n_components": [5, 10], and the shared keys. A third dictionary can add "reduce__whiten": [True] if you want whitening. Each dictionary is a separate grid, and the search combines them.