Sub topic 10
Tuning hyperparameters with cross-validation
This chapter assumes you know k-fold cross-validation, scikit-learn pipelines, and the difference between a model's parameters and its hyperparameters.
Parameters and hyperparameters
A model learns parameters from data, such as the coefficients of a logistic regression. Hyperparameters are settings you choose before training, such as the regularization strength C of an SVM. The training algorithm can't pick them for you.
You could try a few values and keep the one with the best training score. That favors the most flexible model, because training scores reward overfitting. You could also score each candidate on the test set. Then the test set has helped choose the model, and it no longer gives an honest estimate. Cross-validation gives you a third option. It scores each candidate on held-out folds of the training data and leaves the test set untouched.
How the search works
For each candidate setting, the search runs k-fold cross-validation and records the mean score. It then picks the setting with the best mean. Finally it refits a model with that setting on all the training data.
Grid search in scikit-learn
GridSearchCV tries every combination in a grid. Put the preprocessing and the model in a pipeline. Then the scaler is refit inside every training fold, which avoids leakage. Reach pipeline steps with the stepname__parameter syntax.
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, stratify=y, random_state=0
)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "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"test accuracy: {search.score(X_test, y_test):.3f}")The search stores its results in these attributes:
best_params_holds the winning combination.best_score_is that combination's mean cross-validated score.cv_results_holds every candidate's mean and standard deviation. Check it, because two candidates whose means differ by less than one standard deviation are effectively tied.- With the default
refit=True,searchis itself a fitted model trained on all ofX_train.search.scoretherefore uses the refit model.
Cost
The number of model fits is the number of combinations times k, plus one refit. This grid has 3 × 3 = 9 combinations and 5 folds, so it needs 45 fits plus 1. Each extra hyperparameter multiplies the cost. When a grid gets large, use RandomizedSearchCV. It samples a fixed number of combinations (n_iter) from lists or distributions. It often finds a setting nearly as good for far less compute. Set n_jobs=-1 to run fits in parallel.
Common errors
- Tuning on the test set. Split off the test set first and never pass it to
fiton the search. - Trusting
best_score_as final performance. It is the maximum over many noisy scores, so it is optimistically biased. Report the held-out test score instead, or use nested cross-validation, which a later chapter covers. - Searching on unscaled or leaky pipelines. Fit the scaler outside the pipeline and every fold has already seen the validation data.
- Grids at the edge. If the best value sits at the edge of your grid, extend the grid in that direction.
Exercise
You tune an SVC with a grid of 4 values for C and 3 values for gamma, using 5-fold cross-validation and the default refit. How many times is a model fitted? Why is the search's bestscore not a fair estimate of future performance?
Show answer
There are 4 × 3 = 12 combinations. Each is fitted 5 times, giving 60 fits, plus 1 refit on all training data, for 61 in total. bestscore is the highest of many noisy cross-validation scores, and the data that selected the winner also produced the score. It is therefore optimistically biased. Use a held-out test set or nested cross-validation for an unbiased estimate.