Hyperparameter Tuning
Grid search, random search, Bayesian optimization and early stopping of bad trials (successive halving, Hyperband, Optuna pruners) — how they work, when each wins, and how to set up a search that does not fool you.
Parameters (weights) are learned by gradient descent; hyperparameters — learning rate, batch size, weight decay, depth, number of trees — are chosen by you, before training. Hyperparameter tuning is the outer loop that searches for good values by training many models (trials) and comparing them on validation data. Done well, it can be the difference between a mediocre and a state-of-the-art result; done badly, it burns compute and overfits the validation set.
The setup that every method shares
- Objective: one validation metric to optimize (val loss, F1, RMSE…), measured on a Validation set or via Cross-validation — never on the test set.
- Search space: a range and *scale* per hyperparameter. Learning rate and weight decay span orders of magnitude, so sample them log-uniformly (1e-5 … 1e-1), not uniformly.
- Budget: number of trials and compute per trial (epochs, data size).
- Search strategy: how to choose the next configuration (grid, random, Bayesian) and whether to stop bad trials early.
Grid search vs random search
Grid search evaluates every combination of a few values per hyperparameter. Its cost explodes: 5 values for each of 4 hyperparameters = 5⁴ = 625 trials. Worse, if only one hyperparameter really matters, a 5×5 grid tests just 5 distinct values of it in 25 trials. Random search draws each trial independently from the space, so 25 trials test 25 distinct values of every hyperparameter. Bergstra & Bengio showed that random search finds configurations as good as or better than grid search with a fraction of the trials, because in practice only a few hyperparameters matter for any given problem (low effective dimensionality).[1]
- P
- probability of the event in brackets
- n
- number of independent random trials
- top 5%
- the best-scoring 5% of all possible configurations
- 0.95ⁿ
- probability that all n trials miss the top 5% (each one misses with probability 0.95)
- →
- “gives”
- ≈
- approximately
▸Worked example
Bayesian optimization
Grid and random search ignore what they have already learned. Bayesian optimization fits a cheap surrogate model of 'hyperparameters → score' to all trials so far (a Gaussian process in Snoek et al.; a Tree-structured Parzen Estimator, TPE, in Hyperopt and Optuna's default sampler), then picks the next trial by maximizing an acquisition function that balances *exploitation* (try near the current best) and *exploration* (try where the surrogate is uncertain).[2] It shines when each trial is expensive (hours of GPU) and the number of hyperparameters is moderate (≲ 20). Its sequential nature makes it less parallel than random search.
- EI(x)
- expected improvement of candidate configuration x — the Bayesian optimization sampler tries the x with the highest EI next
- 𝔼
- expectation: probability-weighted average over the surrogate's uncertain prediction of f(x)
- max
- max(0, …) keeps only gains: a worse result counts as 0, not as a negative
- f(x)
- the (still unknown) score of configuration x, e.g. validation accuracy — the surrogate predicts it as a distribution
- f(x⁺)
- best score observed so far; x⁺ is the configuration that achieved it
▸Worked example
Stop bad trials early: successive halving, Hyperband, pruning
Most trials are obviously bad after a few epochs — their learning curves are already far above the leaders. Successive halving starts many configurations with a small budget, keeps the best 1/η of them, gives the survivors η× more budget, and repeats. Hyperband runs several successive-halving 'brackets' with different trade-offs between number of configurations and starting budget, so you do not have to guess how early is too early.[3] Optuna implements the same idea as pruners: a trial reports its intermediate value every epoch and is stopped if it is worse than, e.g., the median of earlier trials at the same step.[4]
| Method | Strengths | Weaknesses | Good for |
|---|---|---|---|
| Grid | Simple, exhaustive, reproducible | Exponential cost; wastes trials on unimportant axes | 1–2 hyperparameters, cheap models |
| Random | Embarrassingly parallel, strong default, any budget | Does not learn from past trials | First pass, many hyperparameters |
| Bayesian (GP, TPE) | Sample-efficient; focuses on promising regions | Sequential; overhead; can get stuck if the space is poorly defined | Expensive trials, ≲ 20 dims |
| Successive halving / Hyperband / pruning | Huge compute savings; combines with any sampler | Can kill slow starters (e.g. low LR that wins late) | Iterative training (neural nets, boosting) |
Optuna in practice
import optuna
def objective(trial):
lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)
weight_decay = trial.suggest_float("weight_decay", 1e-6, 1e-2, log=True)
n_layers = trial.suggest_int("n_layers", 1, 4)
optimizer_name = trial.suggest_categorical("optimizer", ["adamw", "sgd"])
model, opt = build_model_and_optimizer(n_layers, optimizer_name, lr, weight_decay)
for epoch in range(30):
train_one_epoch(model, opt)
val_acc = evaluate(model)
trial.report(val_acc, epoch) # intermediate value for the pruner
if trial.should_prune():
raise optuna.TrialPruned()
return val_acc
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=42),
pruner=optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=5),
)
study.optimize(objective, n_trials=100)
print(study.best_value, study.best_params)log=True samples on a log scale. Swap in optuna.pruners.HyperbandPruner() for Hyperband-style pruning.from scipy.stats import loguniform, randint
from sklearn.model_selection import RandomizedSearchCV
from sklearn.ensemble import HistGradientBoostingClassifier
search = RandomizedSearchCV(
HistGradientBoostingClassifier(),
param_distributions={
"learning_rate": loguniform(1e-3, 0.3),
"max_leaf_nodes": randint(8, 128),
"l2_regularization": loguniform(1e-6, 1.0),
},
n_iter=60, cv=5, scoring="f1", random_state=0, n_jobs=-1,
)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)GridSearchCV / RandomizedSearchCV combine tuning with cross-validation; HalvingRandomSearchCV adds successive halving (experimental, needs from sklearn.experimental import enable_halving_search_cv).[5]Knobs of the search itself
- What it is
- How many configurations are trained and evaluated.
- ↑ If you increase it
- Higher chance of finding a near-optimal configuration, with diminishing returns — and a growing risk of overfitting the validation set by sheer selection (the best of 1,000 noisy scores is optimistically biased).
- ↓ If you decrease it
- Cheaper, but you may only explore a corner of the space; results depend heavily on luck.
- Typical values
- 20–100 for random/TPE on a handful of hyperparameters; more if trials are cheap.
- What it is
- Lower/upper bound for each hyperparameter and whether it is sampled linearly or logarithmically.
- ↑ If you increase it
- (wider) Less risk of excluding the optimum, but most trials land in bad regions and you need more of them.
- ↓ If you decrease it
- (narrower) Efficient if centred on the right region; if the best trial sits at the edge of the range, the true optimum is probably outside — widen it.
- Typical values
- LR 1e-5–1e-1 (log); weight decay 1e-6–1e-1 (log); dropout 0–0.5 (linear).
- What it is
- How quickly bad trials are stopped: the reduction factor η in successive halving/Hyperband, or
n_warmup_steps/n_startup_trialsin Optuna's MedianPruner. - ↑ If you increase it
- (larger η, shorter warm-up) More trials fit in the budget, but late bloomers (small LR, heavy regularization) get killed before they shine.
- ↓ If you decrease it
- (smaller η, longer warm-up) Fairer to slow starters, but saves less compute.
- Typical values
- η = 3; warm-up of a few epochs (≈ 10–20% of the training budget).
- What it is
- How many trials run at the same time.
- ↑ If you increase it
- Faster wall-clock time. Perfect for random search; for Bayesian methods, each new trial is chosen with less information (pending trials have no results yet), so sample efficiency drops somewhat.
- ↓ If you decrease it
- Slower, but Bayesian optimization uses every finished result before proposing the next trial.
- Typical values
- One trial per GPU; −1 (all cores) for scikit-learn on CPU.
▸Go deeper: how TPE works
Instead of modelling p(score | x) like a Gaussian process, TPE splits finished trials into a 'good' group (top γ fraction, e.g. 10–25%) and a 'bad' group, fits a density l(x) to the good configurations and g(x) to the bad ones, and proposes the x that maximizes l(x)/g(x) — configurations that look much more like past winners than past losers. Maximizing this ratio is equivalent to maximizing Expected Improvement under TPE's model. It handles conditional and categorical spaces naturally (e.g. 'momentum only if optimizer = SGD'), which is why Optuna and Hyperopt use it.[4]
Quiz
References
- [1]
- [2]Practical Bayesian Optimization of Machine Learning AlgorithmsPaperSnoek, Larochelle, Adams2012arxiv.org
- [3]Hyperband: A Novel Bandit-Based Approach to Hyperparameter OptimizationPaperLi et al.2016arxiv.org
- [4]Optuna: A Next-generation Hyperparameter Optimization FrameworkPaperAkiba et al.2019arxiv.org
- [5]scikit-learn User Guide — Tuning the hyper-parameters of an estimatorDocsscikit-learn developersscikit-learn.org
- [6]Deep Learning Tuning PlaybookDocsGodbole, Dahl, Gilmer, Shallue, Nado2023github.com