Hyperparameter Tuning: Grid and Random Search
Parameters are learned by training; hyperparameters are chosen before it: the depth of a tree, the and of an SVM, the learning rate and weight decay of a network. They control the bias-variance balance of the previous lessons, and good values depend on the data, so they are searched. Every search follows the same pattern: propose a configuration, estimate its quality on validation data (usually by cross-validation), keep the best. This lesson covers the two simplest proposal strategies, grid and random, a faster variant that drops bad candidates early, and nested cross-validation, which tells you how good the tuned model really is.
The search problem
Write for a hyperparameter configuration and for its cross-validated error. Tuning solves
a black-box problem: there is no gradient, each evaluation costs trainings, and the objective is noisy. Scale-type hyperparameters (, , learning rate, regularisation strength) matter in orders of magnitude, so they are searched on a log scale: rather than .
Grid search
GridSearchCV tries every combination of the listed values. An RBF SVM on the breast-cancer data, tuned on a training part with 5-fold CV, then scored once on a held-out test part:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, 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)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), SVC())
grid = {"svc__C": [0.1, 1, 10, 100, 1000], "svc__gamma": [1e-4, 1e-3, 1e-2, 1e-1, 1]}
search = GridSearchCV(pipe, grid, cv=StratifiedKFold(5, shuffle=True, random_state=0))
search.fit(X_tr, y_tr)
res = search.cv_results_
table = res["mean_test_score"].reshape(5, 5) # rows: C, columns: gamma
print("CV accuracy gamma: " + " ".join(f"{g:6g}" for g in grid["svc__gamma"]))
for C, row in zip(grid["svc__C"], table):
print(f"C = {C:<6g} " + " ".join(f"{v:6.3f}" for v in row))
print("best:", search.best_params_, f"CV {search.best_score_:.3f}")
print(f"test accuracy of the refitted best model: {search.score(X_te, y_te):.3f}")CV accuracy gamma: 0.0001 0.001 0.01 0.1 1
C = 0.1 0.627 0.716 0.944 0.944 0.627
C = 1 0.723 0.946 0.969 0.967 0.627
C = 10 0.946 0.972 0.984 0.967 0.629
C = 100 0.969 0.986 0.986 0.967 0.629
C = 1000 0.984 0.984 0.981 0.967 0.629
best: {'svc__C': 100, 'svc__gamma': 0.001} CV 0.986
test accuracy of the refitted best model: 0.958
The table is the CV accuracy surface. Too little with too little (top left) underfits (0.627 is the share of the majority class: the SVM predicts one class); (right column) overfits for every , because each training point gets its own narrow bump. A diagonal ridge of good values runs from to : larger (less regularisation) pairs with smaller (smoother kernel). Two cells tie at 0.986, and scikit-learn keeps the first one it met. The refitted best model scores 0.958 on the 143 test tumours, below its CV score of 0.986: partly noise, partly the optimism of taking a maximum (see nested CV below).
Grid search is simple, easy to parallelise and reproducible. Its cost is the product of the grid sizes: 5 values for each of 4 hyperparameters is 625 configurations, times 5 folds.
Why random search beats grid search
Usually only one or two hyperparameters really matter. A grid spends 9 trials but tests only 3 distinct values of the important one; 9 random points test 9 distinct values. A toy objective that depends strongly on and hardly on makes this concrete:
import numpy as np
def score(a, b): # peak at a = 0.37; b barely matters
return np.exp(-((a - 0.37) / 0.08) ** 2) + 0.02 * b
g = np.array([1 / 6, 3 / 6, 5 / 6]) # 3 x 3 grid, centred cells
A, B = np.meshgrid(g, g)
grid_best = score(A, B).max()
rng = np.random.default_rng(0)
random_best = [score(*rng.random((2, 9))).max() for _ in range(1000)] # 1000 random searches of 9 trials
print(f"grid: {len(np.unique(A))} distinct values of a, best score {grid_best:.3f}")
print(f"random: 9 distinct values of a, median best score {np.median(random_best):.3f}")
print(f"random search beats the grid in {np.mean(np.array(random_best) > grid_best):.0%} of 1000 runs")grid: 3 distinct values of a, best score 0.088
random: 9 distinct values of a, median best score 0.811
random search beats the grid in 93% of 1000 runs
The grid's three values of (1/6, 1/2, 5/6) all miss the narrow peak at 0.37, so its best score is 0.088. Nine random points land near the peak most of the time: the median best score over 1000 random searches is 0.811, and random search wins 93 % of the time. With more hyperparameters that do not matter, the grid wastes even more of its budget.
RandomizedSearchCV samples each hyperparameter from a distribution. scipy.stats.loguniform(a, b) draws uniformly on a log scale between and :
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, 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)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), SVC())
dists = {"svc__C": loguniform(1e-1, 1e3), "svc__gamma": loguniform(1e-4, 1)}
search = RandomizedSearchCV(pipe, dists, n_iter=25, cv=StratifiedKFold(5, shuffle=True, random_state=0),
random_state=0)
search.fit(X_tr, y_tr)
best = search.best_params_
print(f"best C {best['svc__C']:.3g}, gamma {best['svc__gamma']:.3g}, CV {search.best_score_:.3f}")
print(f"test accuracy: {search.score(X_te, y_te):.3f}")best C 25.8, gamma 0.0151, CV 0.988
test accuracy: 0.965
Twenty-five random draws found , , on the same ridge as the grid's winner, with CV 0.988 and test accuracy 0.965. Random search could reach values between the grid lines; the test-set difference from the grid (0.965 vs 0.958) is a single tumour out of 143, so do not read it as random search being better here.
Successive halving
Most configurations are clearly bad after a little training. Successive halving evaluates many candidates on a small budget (few samples, few trees, few epochs), keeps the best third (factor=3), triples the budget, and repeats. scikit-learn's version is still marked experimental, so it needs an extra import:
from sklearn.experimental import enable_halving_search_cv # noqa: F401 (switches the feature on)
from sklearn.model_selection import HalvingGridSearchCV, StratifiedKFold
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
grid = {"max_depth": [2, 4, 8, None], "max_features": [0.1, 0.3, 0.6, 1.0], "min_samples_leaf": [1, 5]}
search = HalvingGridSearchCV(RandomForestClassifier(random_state=0), grid, resource="n_estimators",
min_resources=10, max_resources=90, factor=3,
cv=StratifiedKFold(3, shuffle=True, random_state=0), random_state=0)
search.fit(X, y)
for it, (n_cand, n_res) in enumerate(zip(search.n_candidates_, search.n_resources_)):
print(f"round {it}: {n_cand:2d} candidates with {n_res} trees each")
print("best:", search.best_params_, f"CV {search.best_score_:.3f}")round 0: 32 candidates with 10 trees each
round 1: 11 candidates with 30 trees each
round 2: 4 candidates with 90 trees each
best: {'max_depth': None, 'max_features': 0.3, 'min_samples_leaf': 1, 'n_estimators': 90} CV 0.961
All 32 combinations got 10 trees; the best 11 got 30 trees; the best 4 got 90. The full grid at 90 trees would have trained trees, successive halving trained , about a third. The risk is that a configuration that starts slowly (for example a small learning rate) is dropped before it shines. HalvingRandomSearchCV is the random-search version.
Nested cross-validation: how good is the tuned model?
best_score_ is the maximum of many noisy CV estimates, so it is optimistically biased: the winner is partly the configuration that got lucky folds. To estimate the performance of the whole procedure (tune, then refit), wrap the search in an outer cross-validation: each outer fold tunes on its own training part and is scored on data the search never saw. Nested Cross-Validation explains the scheme; here is the gap it measures.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = make_classification(n_samples=200, n_features=30, n_informative=4, flip_y=0.1, random_state=3)
pipe = make_pipeline(StandardScaler(), SVC())
grid = {"svc__C": [0.1, 1, 10, 100], "svc__gamma": [1e-3, 1e-2, 1e-1, 1]}
inner = StratifiedKFold(3, shuffle=True, random_state=0)
outer = StratifiedKFold(5, shuffle=True, random_state=1)
search = GridSearchCV(pipe, grid, cv=inner).fit(X, y)
nested = cross_val_score(GridSearchCV(pipe, grid, cv=inner), X, y, cv=outer)
print(f"best_score_ of one search (optimistic): {search.best_score_:.3f}")
print(f"nested CV estimate : {nested.mean():.3f} +/- {nested.std():.3f}")best_score_ of one search (optimistic): 0.785
nested CV estimate : 0.760 +/- 0.078
On this small, noisy problem (200 rows, 10 % flipped labels) the best configuration's CV score is 0.785, while the nested estimate of the tune-then-refit procedure is 0.760, with a fold-to-fold spread of 0.078. The 0.025 gap is the selection optimism; it grows with the number of configurations and shrinks with the amount of data. Report the nested number (or a separate test set), and use the plain search only to pick the final hyperparameters.
Pitfalls
- Tuning on the test set. Every look at the test score that influences a choice spends it. Tune on CV folds; touch the test set once.
- Linear grids for scale parameters. explores one decade; use log spacing.
- The best value on the edge of the grid. If the winner is the smallest or largest value tried, extend the range.
- Preprocessing outside the search. The scaler belongs in the pipeline that is cross-validated, as above.
- Over-tuning small data. With 200 rows, differences of 0.01 in CV accuracy between configurations are noise; prefer the simpler model among near-ties.
Practice
- How many model fits does
GridSearchCVwith a grid and 5-fold CV perform, including the final refit?
Answer
configurations, times 5 folds is 300 fits, plus 1 refit on all the training data: 301.
- A random search draws 60 configurations. What is the probability that at least one lies in the best 5 % of the search space?
Answer
. This independence argument, which does not depend on the number of hyperparameters, is the classic case for random search.
- Why is
best_score_optimistic even though each configuration is cross-validated honestly?
Answer
Each CV score is an unbiased but noisy estimate. Taking the maximum of many noisy estimates selects partly for favourable noise, so the maximum is biased upwards; the more configurations, the larger the bias.
Test yourself
Why should and of an SVM be searched on a log scale?
- scikit-learn requires it
- Their effect changes by orders of magnitude, so equal steps in are equally informative
- It makes the search deterministic
- It avoids negative values only
With a budget of 9 trials and one important hyperparameter out of two, how many distinct values of the important one does a grid test?
- 9
- 6
- 3
- 1
What does nested cross-validation estimate?
- The best hyperparameters
- The performance of the whole tune-then-refit procedure on new data
- The training error
- The variance of the hyperparameters
In successive halving with factor=3, what happens after each round?
- All candidates continue with the same budget
- The best third of the candidates continue with three times the resource
- The worst third are dropped and the budget stays
- A new random set of candidates is drawn