Sub topic 10
Tuning hyperparameters with cross-validation
This chapter assumes you know how k-fold and stratified k-fold work, why preprocessing belongs inside a scikit-learn Pipeline, and how cross_val_score reports fold scores. Here you will use cross-validation to choose hyperparameters, and you will see where that choice can mislead you.
Parameters and hyperparameters
A model has two kinds of settings. Parameters are learned from data during fit, such as the coefficients of a logistic regression. Hyperparameters are set before training and control how the model learns, such as the regularization strength C of an SVM or the depth of a decision tree.
Training cannot choose hyperparameters well. A deeper tree always fits the training data at least as well as a shallower one, so training error would always pick the most complex model. You need an estimate of performance on unseen data, and cross-validation provides one.
The working model
Tuning with cross-validation follows one procedure:
- List candidate hyperparameter settings.
- For each candidate, run k-fold cross-validation and record the mean validation score.
- Pick the candidate with the best mean score.
- Refit a model with that candidate on all the data you gave the search.
Each candidate costs k model fits, so the total cost is the number of candidates times k, plus one refit.
Grid search with GridSearchCV
GridSearchCV implements this procedure. You give it an estimator, a dictionary of candidate values, and a cv splitter. It tries every combination in the grid.
When the estimator is a pipeline, parameter names use the step name, two underscores, and the parameter name. For make_pipeline(StandardScaler(), SVC()) the SVM step is named svc, so its regularization parameter is svc__C.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {
"svc__C": [0.1, 1, 10, 100],
"svc__gamma": ["scale", 0.01, 0.001],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = GridSearchCV(pipe, param_grid, cv=cv, scoring="accuracy")
search.fit(X_train, y_train)
print(search.best_params_)
print(f"best CV accuracy: {search.best_score_:.3f}")
print(f"held-out test accuracy: {search.score(X_test, y_test):.3f}")This grid has 4 × 3 = 12 candidates. With 5 folds that is 60 fits, plus one final refit.
Three things happen in this code:
- The scaler is refit inside every training fold, because it is part of the pipeline. Scaling
X_trainfirst and passing the scaled data to the search would leak validation-fold statistics into training. best_score_is the mean cross-validation score of the winning candidate.search.score(X_test, y_test)uses the refit model on a test set that the search never saw.
The refit step
By default GridSearchCV uses refit=True. After choosing the best candidate it trains a fresh model with those settings on the whole input, here X_train. The predict and score methods of the search object use that refit model. This is why you do not need to retrain by hand.
With several metrics in scoring, refit must name the metric to use, for example refit="f1". Otherwise scikit-learn raises an error.
Reading cv_results_
The cv_results_ attribute holds the score of every candidate on every fold. It is more informative than best_params_ alone, because it shows how close the runner-up candidates were.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10, 100]}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = GridSearchCV(pipe, param_grid, cv=cv).fit(X, y)
res = search.cv_results_
for rank, mean, std, params in zip(
res["rank_test_score"],
res["mean_test_score"],
res["std_test_score"],
res["params"],
):
print(f"rank {rank}: {mean:.3f} +/- {std:.3f} {params}")If the top three candidates differ by less than one standard deviation, the data cannot tell them apart. In that case prefer the simpler or cheaper one. For example, choose the smaller C, which means stronger regularization, or the shallower tree. Scikit-learn's refit parameter also accepts a function, so you can encode a rule like "the simplest model within one standard error of the best".
Random search
Grid search cost grows multiplicatively with each added hyperparameter. A grid of 5 values for each of 4 hyperparameters has 625 candidates. Most of those candidates also repeat the same few values of the parameters that matter most.
RandomizedSearchCV draws a fixed number of candidates (n_iter) from distributions that you specify. With the same budget it tries more distinct values of each hyperparameter, which usually matters when only a few hyperparameters strongly affect the score.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), SVC())
param_dist = {
"svc__C": loguniform(1e-2, 1e3),
"svc__gamma": loguniform(1e-4, 1e0),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = RandomizedSearchCV(
pipe, param_dist, n_iter=20, cv=cv, random_state=0
)
search.fit(X, y)
print(search.best_params_)
print(f"best CV accuracy: {search.best_score_:.3f}")Use a log-uniform distribution for scale-like parameters such as C, gamma, and learning rates. Values like 0.01 and 100 matter equally on a log scale, and a plain uniform distribution would almost never sample the small ones.
| Property | GridSearchCV | RandomizedSearchCV |
|---|---|---|
| Candidates | Every combination in the grid | `n_iter` random draws |
| Cost | Product of the list lengths, times k | `n_iter` times k |
| Good for | One to three hyperparameters with a few values each | Many hyperparameters, or continuous ranges |
| Reproducibility | Deterministic | Set `random_state` |
Choosing the metric and the splitter
The search optimizes whatever scoring says. The default for classifiers is accuracy, which is a poor target on imbalanced data. Choose a metric that reflects the real goal, such as "f1", "roc_auc", or "average_precision".
The cv argument must also match the data:
- Use
StratifiedKFoldfor classification. An integercvon a classifier already means stratified folds. - Use
GroupKFoldand passgroupstofitwhen samples are related, for example several rows per patient. - Use
TimeSeriesSplitfor time-ordered data.
The search is only as honest as its splitter. A tuned model that looks excellent under a leaky split will fail in production.
Why the best score is optimistic
best_score_ is the maximum over many noisy estimates. Each candidate's mean score is its true performance plus random noise from the particular folds. Picking the largest value tends to pick a candidate that was lucky as well as good. The more candidates you try, and the smaller the dataset, the bigger this selection bias becomes.
This is why the example above kept a separate test set. The test score is computed once, on data that played no part in selecting the hyperparameters, so it carries no selection bias. When data is too scarce to set aside a test set, nested cross-validation (covered later in this tutorial) estimates the same quantity by wrapping the whole search inside an outer cross-validation loop.
Common errors
- Reporting
best_score_as the final performance. It is biased upward. Report the score on untouched data or a nested cross-validation estimate. - Preprocessing outside the pipeline. Fitting a scaler, imputer, or feature selector on all data before the search leaks information into every validation fold.
- Using the test set to compare candidates. If you look at test scores, change something, and look again, the test set has become a validation set. Use it once.
- Searching a grid with the best value on its edge. If the best
Cis the largest value you tried, the optimum may lie outside the grid. Extend the range and search again. - Ignoring variance. A difference of 0.002 between candidates is noise. Look at
std_test_scorebefore trusting a ranking. - Forgetting group or time structure. Passing a plain
KFoldfor grouped or ordered data produces inflated scores and chooses overfit settings. - Underestimating cost. Total fits equal candidates × k. Use
n_jobs=-1to run fits in parallel, and fall back to random search when the grid gets large. On Windows and macOS, scripts that usen_jobsshould run under anif __name__ == "__main__":guard.
Practical workflow
- Split off a test set if you have enough data, stratified when you are classifying.
- Build a pipeline containing all preprocessing and the model.
- Pick a metric that matches the goal, and a splitter that matches the data structure.
- Start with a coarse random or grid search over wide ranges on a log scale.
- Inspect
cv_results_, then narrow the ranges around the best region. - Evaluate the refit model once on the test set, and report the mean and spread.
Exercise
A grid search over 6 values of C and 5 values of gamma uses 4-fold cross-validation with the default refit=True. How many model fits does it run in total? Then explain why search.best_score_ should not be reported as the model's expected accuracy on new data.
Show answer
There are 6 × 5 = 30 candidates, and each is fit 4 times, giving 120 fits. The refit on all the data adds one more, so 121 in total. best_score_ is the maximum of 30 noisy cross-validation estimates. Choosing the largest one favors candidates that were lucky on these folds, so it overestimates performance on new data. A separate test set, or nested cross-validation, gives an estimate free of that selection bias.
Exercise
You tune a logistic regression with GridSearchCV. You first fit a StandardScaler on the full dataset, transform it, and pass the result to the search. Why is this wrong, and how do you fix it?
Show answer
The scaler computed its mean and standard deviation using rows that later end up in validation folds, so validation data influenced training. This leaks information and inflates scores. Fix it by putting the scaler and the model in one Pipeline and passing the pipeline to GridSearchCV, so the scaler is refit on the training part of each fold. Grid parameter names then take the form logisticregression__C.