AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↘Training Results & Evaluation
  1. Reading Loss & Accuracy Curves
  2. Classification Metrics
  3. Regression Metrics & Validation
  4. Experiment Logging & Reproducibility
  5. Hyperparameter Tuning
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Training Results & Evaluation

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.

Intermediate~24 min·6 references
Key terms
Hyperparameter tuningHyperparameterGrid searchRandom searchBayesian optimizationCross-validationValidation setLearning rate

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.

≈
Seasoning a recipe
Salt, heat and cooking time are the hyperparameters of a dish. Grid search cooks every combination on a fixed menu. Random search tries random combinations — and quickly discovers that salt matters far more than the brand of pepper. Bayesian optimization is the chef who remembers every previous attempt and decides what to try next based on how they tasted. Pruning is tasting halfway and throwing out a pot that is clearly burnt.

The setup that every method shares

  1. Objective: one validation metric to optimize (val loss, F1, RMSE…), measured on a Validation set or via Cross-validation — never on the test set.
  2. 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.
  3. Budget: number of trials and compute per trial (epochs, data size).
  4. 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(at least one of n random trials in the top 5%) = 1 − 0.95ⁿ n = 60 → ≈ 0.95
Why ~60 random trials is a classic rule of thumb: whatever the number of dimensions, 60 trials land in the best 5% of the space with ~95% probability.
In words: “each random trial has a 5% chance of landing in the best 5% of the search space, so the chance that n independent trials all miss is 0.95ⁿ, and the chance that at least one hits is 1 minus that.” The number of hyperparameters never appears in the formula — which is why Random search scales so well.
Symbols(hover a symbol in the formula)
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
Each trial misses the top 5% with probability 0.95 n = 1: 1 − 0.95 = 0.05 n = 10: 1 − 0.95¹⁰ = 1 − 0.599 = 0.401 n = 30: 1 − 0.215 = 0.785 n = 60: 1 − 0.046 = 0.954 n = 100: 1 − 0.006 = 0.994 Solve 0.95ⁿ ≤ 0.05: n ≥ ln 0.05 / ln 0.95 ≈ 58.4 → 59 trials already give 95%.

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) = 𝔼[ max(0, f(x) − f(x⁺)) ]
Expected Improvement, a popular acquisition function: how much better than the best score so far, f(x⁺), we expect configuration x to be (for maximization).
In words: “the expected improvement of trying configuration x = the average, over everything the surrogate model believes x might score, of how much it would beat the best score so far (counting 0 when it would not).” Outcomes below the current best cost nothing, so EI rewards both a high predicted score (exploitation) and high uncertainty (exploration).
Symbols(hover a symbol in the formula)
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
Best accuracy so far f(x⁺) = 0.80. The surrogate's beliefs for three candidates: A: 0.78 (50%), 0.82 (30%), 0.86 (20%) → EI = 0.5·0 + 0.3·0.02 + 0.2·0.06 = 0.018 B: surely 0.81 → EI = 0.01 C: 0.70 (50%) or 0.90 (50%) → EI = 0.5·0 + 0.5·0.10 = 0.05 C's average (0.80) is no better than the current best, yet its EI is the highest: the downside costs nothing and the upside is large — EI picks C (exploration).

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]

MethodStrengthsWeaknessesGood for
GridSimple, exhaustive, reproducibleExponential cost; wastes trials on unimportant axes1–2 hyperparameters, cheap models
RandomEmbarrassingly parallel, strong default, any budgetDoes not learn from past trialsFirst pass, many hyperparameters
Bayesian (GP, TPE)Sample-efficient; focuses on promising regionsSequential; overhead; can get stuck if the space is poorly definedExpensive trials, ≲ 20 dims
Successive halving / Hyperband / pruningHuge compute savings; combines with any samplerCan kill slow starters (e.g. low LR that wins late)Iterative training (neural nets, boosting)

Optuna in practice

python
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)
TPE is Optuna's default sampler; log=True samples on a log scale. Swap in optuna.pruners.HyperbandPruner() for Hyperband-style pruning.
python
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_)
For scikit-learn models: 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

knobNumber of trials (n_trials / n_iter)
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.
knobSearch-space range & scale
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).
knobPruning aggressiveness (η, warm-up steps)
What it is
How quickly bad trials are stopped: the reduction factor η in successive halving/Hyperband, or n_warmup_steps / n_startup_trials in 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).
knobParallel workers (n_jobs)
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.
✓
Tuning playbook in one paragraph
Google's Deep Learning Tuning Playbook recommends an incremental process: start from a simple, well-known configuration; in each round, decide which hyperparameters are scientific (the ones you are studying), which are nuisance (must be re-tuned for a fair comparison, e.g. learning rate) and which are fixed; run a quasi-random search over the nuisance ones; and look at the training curves of the best trials, not only their final scores. Re-tune the learning rate whenever you change batch size, model size or optimizer.[6]
!
Pitfalls
Tuning on the test set (or reporting the best CV score as the final estimate); sampling learning rate uniformly; tuning before the pipeline and baseline are correct; changing several things at once between rounds; comparing trials with different numbers of epochs as if they were equal; trusting a best trial that sits on the edge of the search range; and spending a week tuning when more or cleaner data would help far more.
▸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

1.
You have a budget of 16 trials and 2 hyperparameters, but only one of them actually affects the score. How many distinct values of the important one does a 4×4 grid test, versus random search?
2.
How should the learning rate usually be sampled in a search from 1e-5 to 1e-1?
3.
What is the main advantage of Bayesian optimization over random search?
4.
In successive halving with η = 3, you start 81 configurations for 1 epoch each. How many survive to the next round, and with what budget?
5.
After 200 trials, the best configuration has the largest learning rate in your range (1e-2, the upper bound). What should you do?
Score: 0/5

References

  1. [1]
    Random Search for Hyper-Parameter Optimization
    PaperBergstra & Bengio2012jmlr.org
    JMLR 13.
  2. [2]
    Practical Bayesian Optimization of Machine Learning Algorithms
    PaperSnoek, Larochelle, Adams2012arxiv.org
  3. [3]
    Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization
    PaperLi et al.2016arxiv.org
  4. [4]
    Optuna: A Next-generation Hyperparameter Optimization Framework
    PaperAkiba et al.2019arxiv.org
  5. [5]
    scikit-learn User Guide — Tuning the hyper-parameters of an estimator
    Docsscikit-learn developersscikit-learn.org
  6. [6]
    Deep Learning Tuning Playbook
    DocsGodbole, Dahl, Gilmer, Shallue, Nado2023github.com
← Previous
Experiment Logging & Reproducibility
Next → · Deep Learning Architectures
Convolutional Neural Networks (CNNs)