Level 3 In-Depth AI · Classical Machine Learning
Hyperparameter Tuning
Choosing the settings that training itself doesn't learn, such as the learning rate, tree depth or regularization strength. Grid search, random search and Bayesian optimisation explore them; cross-validation judges them; and a final untouched test set keeps you honest.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
Read first
Cross-ValidationThis leads to
—The full path from zero — 6 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- Training, Validation and Test Sets
- Cross-Validation
- Hyperparameter Tuning
Read them roughly in this order. See it on the concept map →
Why it matters
Every learning algorithm has two kinds of numbers. Parameters, such as the weights of a linear model, are learned from the data by training. Hyperparameters are settings you choose before training that control how it learns: the learning rate, the strength of Regularization: L1 and L2, the maximum depth of a decision tree, the number of trees in a forest, the number of neighbours in k-Nearest Neighbours, the size and number of layers of a neural network.
They matter a great deal. A learning rate ten times too large makes a neural network diverge; ten times too small and it barely trains. A tree that is too deep memorises the training set (Overfitting and the Bias–Variance Tradeoff). Bad settings can make a strong algorithm look weak, so comparing algorithms without tuning each one is unfair.
Tuning is also where the most dangerous form of self-deception lives. Try enough settings, keep whichever scores best on your validation data, and you will find one that is lucky on that particular data. This chapter covers how to search efficiently (grid, random and Bayesian search, early stopping of bad trials), what to tune first, and how to avoid fooling yourself.
The intuition
Imagine tuning an old radio with two knobs, frequency and fine-tune, and you can only judge the sound by listening for a few seconds per setting. You could step through every combination on a fixed grid of positions. You could twiddle both knobs randomly. Or you could listen, form a rough mental picture of where the signal is strongest, and try next where your picture says it's probably best, or where you haven't listened yet.
Those are the three main strategies:
- Grid search: try every combination of a few chosen values for each hyperparameter.
- Random search: try a fixed number of random combinations.
- Bayesian optimisation: build a model of how the score depends on the settings, and use it to pick the next most promising one.
Each "listen" is expensive. It means training the model, usually several times with Cross-Validation. So the whole game is getting a good setting with as few trials as possible.
Key idea Hyperparameters are chosen, not learned. Judge each candidate on validation data (ideally cross-validation), search random or Bayesian rather than a full grid when there are more than two or three of them, search scale-like settings on a log scale, and report the final model on a test set the search never saw.
How it works
The search space
Start by deciding, for each hyperparameter, the range of values worth trying. This is the search space. Two rules make it effective:
- Use a log scale for scale-like settings. For a learning rate, the difference between 0.001 and 0.01 matters as much as between 0.01 and 0.1. Searching evenly between 0.0001 and 1 would put 90% of trials above 0.1. Sample the exponent instead: with uniform between and . The same applies to regularization strength, in SVMs, and the SVM kernel width .
- Start wide, then narrow. A first coarse search over several orders of magnitude finds the right region. A second search zooms in.
Grid search
Grid search lists a few values for each hyperparameter and tries every combination. With 4 values of and 4 of that is settings, and with 5-fold cross-validation, 80 training runs. It is simple, exhaustive within its grid and easy to parallelise.
Its weakness is the curse of dimensionality. The number of combinations multiplies: 5 values for each of 6 hyperparameters is settings. And it wastes most of its budget when some hyperparameters barely matter, which is usually the case.
Random search, and why it usually beats a grid
Random search draws each trial's settings at random from the search space. James Bergstra and Yoshua Bengio showed in 2012 that, for the same budget, it usually finds settings as good as or better than grid search, and they explained why.
Suppose only one of two hyperparameters really matters. A 3×3 grid tries just 3 distinct values of the important one, each three times over. Nine random trials try 9 distinct values of it. In real problems a few hyperparameters usually dominate, and you rarely know in advance which ones, so random search explores what matters much more thoroughly.
There is also a neat way to size the budget. Suppose the best 5% of the search space counts as "good enough". Each random trial independently has a 5% chance of landing there, so the chance that trials all miss is . For :
Sixty random trials find a top-5% setting with about 95% probability, no matter how many hyperparameters there are. A grid can't make that promise.
Bayesian optimisation
Random search ignores everything it has learned so far. Trial 50 is chosen exactly as blindly as trial 1. Bayesian optimisation uses the results so far to choose the next trial. It has two parts:
- A surrogate model: a cheap statistical model that predicts the validation score for any setting, with an uncertainty, fitted to the trials run so far. The classic choice is a Gaussian process. It gives a best guess and an error band that is narrow near tried points and wide in unexplored regions.
- An acquisition function that scores each candidate setting by how useful it would be to try next, balancing exploitation (try where the predicted score is high) with exploration (try where the uncertainty is large, because the best might be hiding there). The most common is expected improvement: the average amount by which the candidate is expected to beat the best score found so far, counting only improvements.
Each round: fit the surrogate, maximise the acquisition function (cheap, since it only queries the surrogate), run the real training at that setting, add the result, repeat.
Bayesian optimisation shines when each trial is expensive and there are not too many hyperparameters (up to about 10–20). Popular libraries use variants: Optuna's default sampler uses the Tree-structured Parzen Estimator (TPE), which models good and bad settings separately rather than fitting a Gaussian process.
Stopping bad trials early
Many trials are obviously bad after a fraction of their training. Successive halving starts many configurations on a small budget (a few epochs, or a subset of the data), keeps the best half (or third), gives the survivors more budget, and repeats. Hyperband runs successive halving several times with different trade-offs between "many configurations" and "long training each". Optuna calls this pruning: a trial reports its intermediate validation score after each epoch and is stopped if it is clearly behind earlier trials at the same point. For deep learning, this often cuts the cost of a search several-fold.
What to tune first
Tuning everything at once wastes effort. Some practical priorities, from experience rather than theory:
- Neural networks: the learning rate first, by a wide margin. Then the batch size and the training length (with a schedule), then regularization (Dropout and Regularizing Neural Networks, weight decay), then architecture size. Karpathy's "Recipe for Training Neural Networks" is a good practical guide.
- Gradient-boosted trees: the learning rate together with the number of trees (use early stopping on validation data to set the latter), then tree depth or number of leaves, then the subsampling fractions and regularization terms (Gradient Boosting: XGBoost and LightGBM).
- Random forests: usually fine at defaults. The number of features tried at each split matters most.
- Linear models and SVMs: the regularization strength (, or ), and for kernel SVMs the kernel width (Support Vector Machines).
- k-nearest neighbours: and the distance metric.
Check the defaults first. Modern library defaults are often good, and a tuned model that beats them by 0.2% on a small validation set may not beat them at all.
Don't overfit the validation set
Every comparison against validation data leaks a little information into your choices. With a handful of trials the effect is negligible. With hundreds or thousands it is real: the winning setting's validation score is the maximum of many noisy estimates, and the maximum of noisy estimates is biased upwards (Cross-Validation describes the Cawley and Talbot result). Defences:
- Keep a test set that the search never touches, and report it once at the end (Training, Validation and Test Sets).
- Use cross-validation rather than a single validation split during the search, to reduce the noise you are maximising over.
- Use nested cross-validation when the data is too small for a separate test set.
- Prefer simpler or more regularized settings when scores are within noise of each other.
- Be suspicious of a large gap between the best validation score and the test score. It means the search found luck.
In code
Grid search against random search in scikit-learn, with the same budget of 16 settings, tuning an SVM on the handwritten-digits dataset. Both use 5-fold cross-validation on the training set and are scored once on a held-out test set:
from scipy.stats import loguniform
from sklearn.datasets import load_digits
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
print("defaults: test acc %.4f" % SVC().fit(X_tr, y_tr).score(X_te, y_te))
grid = GridSearchCV(SVC(), {"C": [0.1, 1, 10, 100], "gamma": [1e-4, 1e-3, 1e-2, 1e-1]}, cv=5)
grid.fit(X_tr, y_tr) # 16 settings x 5 folds = 80 fits
print("grid (16): CV %.4f test %.4f %s" % (grid.best_score_, grid.score(X_te, y_te), grid.best_params_))
rand = RandomizedSearchCV(SVC(), {"C": loguniform(1e-1, 1e2), "gamma": loguniform(1e-4, 1e-1)},
n_iter=16, cv=5, random_state=0)
rand.fit(X_tr, y_tr) # 16 random settings, same budget
best = {k: round(float(v), 5) for k, v in rand.best_params_.items()}
print("random (16): CV %.4f test %.4f %s" % (rand.best_score_, rand.score(X_te, y_te), best))
# defaults: test acc 0.9911
# grid (16): CV 0.9918 test 0.9933 {'C': 10, 'gamma': 0.001}
# random (16): CV 0.9911 test 0.9956 {'C': 3.67743, 'gamma': 0.00175}
Two lessons. loguniform samples on a log scale, as recommended. And the defaults are already excellent here: tuning gains one or two test examples out of 450, which is within noise. Always measure the default first. By default both searches refit the best setting on the whole training set (refit=True), so grid.score uses the final tuned model.
Bayesian optimisation from scratch, in one dimension, using a Gaussian process from scikit-learn as the surrogate and expected improvement as the acquisition function. It tunes for an SVM, starting from three deliberately poor guesses:
import numpy as np
from scipy.stats import norm
from sklearn.datasets import load_digits
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
def score(log_gamma): # the expensive black box
return cross_val_score(SVC(C=10, gamma=10 ** log_gamma), X, y, cv=3).mean()
candidates = np.linspace(-6, 0, 300).reshape(-1, 1) # log10(gamma) from 1e-6 to 1
tried = [-5.5, -1.5, -0.5] # three starting points
scores = [score(g) for g in tried]
print("start:", [f"{g}: {s:.4f}" for g, s in zip(tried, scores)])
for step in range(8):
gp = GaussianProcessRegressor(Matern(nu=2.5), normalize_y=True, alpha=1e-6)
gp.fit(np.array(tried).reshape(-1, 1), scores) # surrogate model of the score
mu, sigma = gp.predict(candidates, return_std=True)
best = max(scores)
imp = mu - best - 0.01 # 0.01: a little extra exploration
z = imp / np.maximum(sigma, 1e-9)
ei = imp * norm.cdf(z) + sigma * norm.pdf(z) # expected improvement
nxt = float(candidates[np.argmax(ei), 0])
tried.append(nxt); scores.append(score(nxt))
print(f"step {step}: try log10(gamma) = {nxt:6.2f} -> CV accuracy {scores[-1]:.4f}")
i = int(np.argmax(scores))
print(f"best: gamma = {10 ** tried[i]:.2e}, accuracy {scores[i]:.4f} after {len(tried)} evaluations")
# start: ['-5.5: 0.9176', '-1.5: 0.1486', '-0.5: 0.1013']
# step 0: try log10(gamma) = -6.00 -> CV accuracy 0.8804
# step 1: try log10(gamma) = -4.72 -> CV accuracy 0.9488
# step 2: try log10(gamma) = -4.17 -> CV accuracy 0.9544
# step 3: try log10(gamma) = -4.39 -> CV accuracy 0.9544
# step 4: try log10(gamma) = -3.65 -> CV accuracy 0.9661
# step 5: try log10(gamma) = -3.31 -> CV accuracy 0.9722
# step 6: try log10(gamma) = -3.03 -> CV accuracy 0.9755
# step 7: try log10(gamma) = -2.79 -> CV accuracy 0.9716
# best: gamma = 9.33e-04, accuracy 0.9755 after 11 evaluations
Watch it work. Step 0 explores the unknown left edge. Steps 1 to 3 refine the promising region around . Then it steps rightwards, each time a little higher, until it passes the peak near and the score drops again. Eleven evaluations, none wasted on the hopeless region above where accuracy collapses to about 10%.
In practice you would use a library. With Optuna (not run here: install it with pip install optuna; results vary from run to run), the same search over two hyperparameters looks like this:
import optuna
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
def objective(trial):
C = trial.suggest_float("C", 1e-1, 1e2, log=True) # log-scale search
gamma = trial.suggest_float("gamma", 1e-5, 1e-1, log=True)
return cross_val_score(SVC(C=C, gamma=gamma), X, y, cv=3).mean()
study = optuna.create_study(direction="maximize") # TPE sampler by default
study.optimize(objective, n_trials=40)
print(study.best_params, round(study.best_value, 4))
Common pitfalls
- Reporting the best validation score as the final result. It is optimistic. Report a held-out test score, or nested cross-validation.
- Linear ranges for scale-like settings. Searching the learning rate uniformly between 0 and 1 wastes almost every trial. Use a log scale.
- Searching too narrow a range. If the best value lies at the edge of your range, the true optimum is probably outside it. Widen the range and search again.
- Tuning with leaky preprocessing. Scaling or feature selection fitted outside the cross-validation loop contaminates every trial. Tune the whole
Pipeline(Data Cleaning and Preparation). - Chasing noise. Differences smaller than the fold-to-fold spread are not real. Prefer the simpler setting.
- Tuning on the test set. Even once. Even "just to check".
Watch out A huge search on a small validation set is a machine for finding lucky settings. If your tuned model's test score is well below its best validation score, the search has overfitted the validation data. Use cross-validation, a reasonable number of trials, and a final untouched test set.
Where it leads
- Cross-Validation: the judge inside every search, and nested CV for honest reporting.
- Regularization: L1 and L2: the most common hyperparameter to tune in classical models.
- Optimizers: SGD, Momentum and Adam and Learning Rate Schedules: the hyperparameters that matter most for neural networks.
- Gradient Boosting: XGBoost and LightGBM: a model whose strength depends heavily on careful tuning with early stopping.
- Training Neural Networks in Practice: practical tuning workflows for deep learning.
- Experiment Tracking and Reproducibility: recording every trial, setting and score so a search is reproducible.
- Scaling Laws: how the best hyperparameters change as models get larger, and why large labs tune on small models first.
A bit of history
Hand-tuning and grid search were the default for decades. Bergstra and Bengio's 2012 paper "Random Search for Hyper-Parameter Optimization" changed common practice by showing that random search is usually more efficient. Bayesian optimisation has older roots, in Jonas Mockus's work in the 1970s and the "efficient global optimization" method of Jones, Schonlau and Welch (1998). It became popular for machine learning after Jasper Snoek, Hugo Larochelle and Ryan Adams' 2012 paper "Practical Bayesian Optimization of Machine Learning Algorithms". Bergstra and colleagues introduced the TPE method in 2011. Lisha Li and colleagues introduced Hyperband in 2016. Optuna, from the Japanese company Preferred Networks, was released in 2018 and described in a 2019 paper. Today, AutoML systems automate tuning along with model and feature choices, though for the largest models, where a single run can cost millions of dollars, careful small-scale experiments and scaling rules have replaced brute-force search.
Try it
- How many random trials do you need for a 99% chance of hitting the top 1% of the search space? (Solve .)
- In the scikit-learn code, change
n_iter=16ton_iter=60and the grid to 8×8 values. Which finds a better CV score per training run?- Change the three starting points in the Bayesian-optimisation code to
[-3.5, -2.5, -0.5]. How many steps does it now need to reach 0.975?Hint for 1: take logarithms: .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
scikit-learn: Tuning the hyper-parameters of an estimator
How GridSearchCV, RandomizedSearchCV and the successive-halving searches work, with tips on search spaces and parallelism.
Random Search for Hyper-Parameter Optimization
Shows that random search finds settings as good as grid search in a fraction of the trials, because only a few hyperparameters usually matter.
Optuna
A popular open-source hyperparameter-optimisation library with Bayesian (TPE) sampling, pruning of bad trials and a dashboard; works with any framework.
Practical Bayesian Optimization of Machine Learning Algorithms
The paper that made Gaussian-process Bayesian optimisation a practical tool for tuning machine-learning models.
Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization
Speeds up hyperparameter search by giving many configurations a small budget and repeatedly keeping only the best ones (successive halving).
Deep Learning Specialization
Five courses on neural networks, tuning, CNNs and sequence models, with very clear explanations of the maths.
A Recipe for Training Neural Networks
Hard-won, practical advice on training neural nets without fooling yourself.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/hyperparameter-tuning.md