Overview
A model has settings that training does not learn, such as the learning rate or the strength of a penalty. They are called hyperparameters. The only way to judge a setting is to train with it and look at the validation score, which is slow. So each trial is precious, and the question is where to try next. Grid search tries a fixed lattice. Random search scatters points. The model-based methods look at the results so far, guess where good values are likely, and try there, while still exploring regions they know little about.
A short history
Grid search is the oldest approach and has no single inventor. James Bergstra and Yoshua Bengio showed in 2012 that random search finds good settings faster than a grid when only a few parameters matter. Bayesian optimisation dates to work by Jonas Mockus in the 1970s. Snoek, Larochelle and Adams made it practical for machine learning with Gaussian processes in 2012. Bergstra and colleagues introduced the Tree-structured Parzen Estimator, TPE, in 2011, and it is the default sampler of the Optuna library released in 2019.
How it works
- Describe the search space: each parameter is a float, a log (searched on a logarithmic scale), an int or a choice from a list.
- Write an objective function that takes a dict of parameters and returns the value to minimise or maximise, usually a validation score.
- Grid tries every combination of a fixed set of values. Random draws each trial independently from the space.
- Bayesian and TPE start with
n_initialrandom trials, then use a model of the results so far to pick each new trial. - Bayesian fits a Gaussian process to the trials and evaluates the candidate with the largest expected improvement.
- TPE splits the trials into a good group and a bad group, estimates a density for each, and picks the candidate where good is most likely compared with bad.
optimize(objective)runs the loop and returns the best trial and all trials.suggest()andreport()give the same loop one step at a time.
Watch out for
- Grid search grows as a product over the parameters, so five values for each of six parameters is already 15,625 trials.
- Searching a learning rate or penalty on a linear scale spends nearly all trials on the large values. Use the log type for parameters that span several powers of ten.
- The best validation score of a search is optimistic, because it was selected from many noisy scores. Keep a test set the search never sees.
- A noisy objective can mislead the model-based methods into chasing a lucky trial. Score each trial with cross-validation to steady it.
- This is a compact NumPy version: one RBF kernel, random candidates for the acquisition, and TPE treating parameters independently. It has no trial pruning, no parallel workers and no study storage, and it does not use the Optuna library.
Use cases
When to use it
Whenever a model has settings that are not learned by training. Use grid for one or two parameters with few values, random as the dependable default, and bayesian or tpe when each trial is expensive.
In industry
- Tabular modelling
- Teams tuning gradient boosted trees search learning rate, depth and regularisation with random search or TPE, since the defaults are rarely best for their data.
- Deep learning
- Each training run of a neural network can take hours, so Bayesian optimisation or TPE is used to reach a good learning rate and weight decay in few trials.
- AutoML services
- Automated machine learning products run a hyperparameter search for the customer and return the best model found within a time budget.
Choosing it: what must hold
- A model with settings that training does not learn, and reason to think they matter.
- An objective that returns one number per trial, usually a validation or cross-validation score.
- A search space with sensible bounds, using a logarithmic scale for values such as the learning rate.
- Budget for many training runs, and a test set kept out of the search.
When to choose something else
| If | Use instead |
|---|---|
| There are one or two parameters with a handful of values each | The grid method of this lesson |
| Trials are cheap or can run in parallel in large numbers | The random method of this lesson |
| The budget allows only a few runs in total | Published default settings, or a model that works well untuned such as Random Forest |
| The objective is noisy from one split | The cross-validation strategies lesson as the objective |
Math foundations
Size of a grid
The number of trials is the product of the number of values per parameter. This is why grid search stops being practical beyond a few parameters.
Why random search works
Each random trial lands in the best fraction of the space with probability . The chance that independent trials all miss it shrinks fast.
The RBF kernel
The Gaussian process assumes that nearby settings give similar results. The kernel says how similar, and the length scale sets how fast that similarity fades with distance.
Gaussian process posterior
Given the trials so far, the prediction at a new point is a mean and a variance. The variance is near 0 close to tried points and near 1 far from all of them.
Expected improvement
The average amount by which is expected to beat the best value when minimising. The first term rewards a low predicted mean, the second rewards uncertainty. The next trial is the candidate with the largest EI.
TPE
TPE models where the good trials lie, , and where the rest lie, . It draws candidates from and keeps the one with the largest ratio.
Symbols
- number of hyperparameters
- number of grid values for parameter j
- number of trials so far
- fraction of the search space counted as good enough
- one setting of the hyperparameters, as a point in the unit cube
- length scale of the kernel
- kernel matrix of the tried points, and kernel vector between x and them
- observed (standardised) objective values and the noise variance
- posterior mean and standard deviation at x
- best objective value found so far
- standard normal cumulative distribution and density
- density of the good trials and of the remaining trials
- gamma, the share of trials treated as good
Worked by hand
The best value so far is . Candidate A has , . Candidate B has , . Use , , , .
B is tried next. A still has a sizeable expected improvement from uncertainty alone, which is how unexplored regions get their turn. The last line shows that 60 random trials hit the best 5 percent of the space with probability 0.954.
Visual example
Loading the example.
Try this
- Press Run one trial a few times with random search, then switch to bayesian and compare where the trials go.
- With bayesian, watch the lower curve: the next trial is always at its peak, sometimes near the best point and sometimes in a gap.
- Set the method to grid with 5 points and see how far the best grid value is from the true minimum.
Code sample
import numpy as np
from impl import Tuner
from config import HPOConfig
rng = np.random.default_rng(0)
X = rng.normal(size=(80, 30)) # 30 features, 40 training rows: needs regularisation
y = X[:, 0] - 2 * X[:, 1] + rng.normal(size=80)
X_train, y_train, X_val, y_val = X[:40], y[:40], X[40:], y[40:]
def objective(params): # validation error of ridge regression
gram = X_train.T @ X_train + params["alpha"] * np.eye(30)
w = np.linalg.solve(gram, X_train.T @ y_train)
return float(((X_val @ w - y_val) ** 2).mean())
tuner = Tuner({"alpha": ("log", 1e-4, 1e3)}, HPOConfig(method="bayesian", n_trials=25, seed=0))
result = tuner.optimize(objective)
print(result.best_params, result.best_value) # alpha around 4, error about 1.6
print(objective({"alpha": 1e-4})) # about 2.1 with almost no penaltyRead the implementation (280 lines)
"""Hyperparameter optimisation: grid search, random search, Bayesian optimisation with a Gaussian process
and expected improvement, and a tree-structured Parzen estimator (TPE, the method behind Optuna's default
sampler).
NumPy and the standard library only. Small by design: the Gaussian process uses one RBF kernel whose length
scale is picked from a short list by marginal likelihood, the acquisition function is maximised over random
candidates, and TPE treats the parameters independently. That is enough for the usual handful of
hyperparameters and a few dozen trials. There is no pruning of running trials, no parallel workers and no
storage.
A search space is a dict, for example
{"lr": ("log", 1e-4, 1.0), "depth": ("int", 1, 8), "dropout": ("float", 0.0, 0.5), "act": ("choice", ["relu", "tanh"])}
"""
from __future__ import annotations
import itertools
import math
from dataclasses import dataclass, field
from typing import Callable
import numpy as np
try:
from .config import HPOConfig
except ImportError: # run from the template's own folder
from config import HPOConfig
KINDS = ("float", "log", "int", "choice")
_erf = np.vectorize(math.erf, otypes=[float])
class SearchSpace:
"""Named parameters with their ranges, and the map between real values and the unit cube.
Every parameter is one coordinate u in [0, 1]:
float low + u * (high - low)
log exp(log(low) + u * (log(high) - log(low))) (uniform on a log scale)
int the integers low..high as equal slices of [0, 1]
choice the options as equal slices of [0, 1]
The model-based methods work in the unit cube, so they never need to know the kinds.
"""
def __init__(self, spec: dict) -> None:
if not spec:
raise ValueError("the search space is empty")
self.names = list(spec)
self.spec = {}
for name, entry in spec.items():
kind = entry[0]
if kind not in KINDS:
raise ValueError(f"parameter {name!r}: kind must be one of {KINDS}, got {kind!r}")
if kind == "choice":
options = list(entry[1])
if not options:
raise ValueError(f"parameter {name!r} has no options")
self.spec[name] = (kind, options)
continue
low, high = entry[1], entry[2]
if not low < high or (kind == "log" and low <= 0):
raise ValueError(f"parameter {name!r}: need low < high (and low > 0 for log), got {low}, {high}")
self.spec[name] = (kind, low, high)
def n_slots(self, name: str) -> int:
"""Number of distinct values of an int or choice parameter (0 for continuous ones)."""
entry = self.spec[name]
if entry[0] == "choice":
return len(entry[1])
return int(entry[2]) - int(entry[1]) + 1 if entry[0] == "int" else 0
def decode(self, u: np.ndarray) -> dict:
"""Turn a point of the unit cube, shape (n_params,), into a dict of parameter values."""
params = {}
for name, x in zip(self.names, np.clip(np.asarray(u, dtype=float), 0.0, 1.0)):
entry = self.spec[name]
if entry[0] == "float":
params[name] = float(entry[1] + x * (entry[2] - entry[1]))
elif entry[0] == "log":
params[name] = float(math.exp(math.log(entry[1]) + x * (math.log(entry[2]) - math.log(entry[1]))))
else:
slot = min(int(x * self.n_slots(name)), self.n_slots(name) - 1)
params[name] = entry[1][slot] if entry[0] == "choice" else int(entry[1]) + slot
return params
def encode(self, params: dict) -> np.ndarray:
"""Inverse of `decode` (int and choice values map to the middle of their slice). Shape (n_params,)."""
u = np.zeros(len(self.names))
for i, name in enumerate(self.names):
entry, value = self.spec[name], params[name]
if entry[0] == "float":
u[i] = (value - entry[1]) / (entry[2] - entry[1])
elif entry[0] == "log":
u[i] = (math.log(value) - math.log(entry[1])) / (math.log(entry[2]) - math.log(entry[1]))
else:
slot = entry[1].index(value) if entry[0] == "choice" else int(value) - int(entry[1])
u[i] = (slot + 0.5) / self.n_slots(name)
return u
def grid(self, points: int) -> list[dict]:
"""Every combination of grid values: all options and integers (at most `points` evenly spaced
integers), and `points` evenly spaced values for float and log parameters, ends included."""
axes = []
for name in self.names:
entry = self.spec[name]
if entry[0] == "choice":
axes.append(list(entry[1]))
elif entry[0] == "int":
count = min(points, self.n_slots(name))
axes.append(sorted({int(round(v)) for v in np.linspace(entry[1], entry[2], count)}))
elif entry[0] == "float":
axes.append([float(v) for v in np.linspace(entry[1], entry[2], points)])
else:
axes.append([float(v) for v in np.exp(np.linspace(math.log(entry[1]), math.log(entry[2]), points))])
return [dict(zip(self.names, combo)) for combo in itertools.product(*axes)]
# ------------------------------------------------------------------------------------ Gaussian process
def _rbf(A: np.ndarray, B: np.ndarray, length: float) -> np.ndarray:
"""RBF kernel matrix exp(-|a - b|^2 / (2 length^2)) between rows of A (n, d) and B (m, d). Shape (n, m)."""
squared = ((A[:, None, :] - B[None, :, :]) ** 2).sum(axis=2)
return np.exp(-0.5 * squared / length**2)
def gp_posterior(X: np.ndarray, y: np.ndarray, X_new: np.ndarray, length: float | None = None,
noise: float = 1e-6) -> tuple[np.ndarray, np.ndarray]:
"""Posterior mean and standard deviation of a zero-mean Gaussian process with a unit-variance RBF kernel.
X: observed points (n, d). y: observed values (n,), ideally standardised. X_new: query points (m, d).
length: kernel length scale. None picks, from a short list, the one with the highest marginal likelihood.
noise: variance added to the diagonal (observation noise and numerical jitter).
Returns (mean (m,), std (m,)).
"""
X, y, X_new = np.asarray(X, dtype=float), np.asarray(y, dtype=float), np.asarray(X_new, dtype=float)
def factor(scale: float):
chol = np.linalg.cholesky(_rbf(X, X, scale) + noise * np.eye(len(X)))
alpha = np.linalg.solve(chol.T, np.linalg.solve(chol, y))
log_likelihood = -0.5 * y @ alpha - np.log(np.diag(chol)).sum() # constant term left out
return log_likelihood, chol, alpha
if length is None:
length = max((0.1, 0.2, 0.4, 0.8, 1.6), key=lambda scale: factor(scale)[0])
_, chol, alpha = factor(length)
cross = _rbf(X_new, X, length) # (m, n)
mean = cross @ alpha
solved = np.linalg.solve(chol, cross.T) # (n, m)
variance = np.clip(1.0 - (solved**2).sum(axis=0), 0.0, None)
return mean, np.sqrt(variance)
def expected_improvement(mean: np.ndarray, std: np.ndarray, best: float) -> np.ndarray:
"""Expected improvement over `best` when MINIMISING: E[max(best - f, 0)] for f ~ Normal(mean, std^2).
Closed form (best - mean) * Phi(z) + std * phi(z) with z = (best - mean) / std. Where std is 0 the
improvement is simply max(best - mean, 0).
"""
mean, std = np.asarray(mean, dtype=float), np.asarray(std, dtype=float)
safe = np.where(std > 0, std, 1.0)
z = (best - mean) / safe
cdf = 0.5 * (1.0 + _erf(z / math.sqrt(2.0)))
pdf = np.exp(-0.5 * z**2) / math.sqrt(2.0 * math.pi)
return np.where(std > 0, (best - mean) * cdf + std * pdf, np.maximum(best - mean, 0.0))
@dataclass
class TuningResult:
"""Outcome of a search.
best_params, best_value: the best trial.
trials: every trial in order, each {"params": dict, "value": float}.
"""
best_params: dict = field(default_factory=dict)
best_value: float = float("nan")
trials: list = field(default_factory=list)
def best_so_far(self, direction: str = "minimize") -> list[float]:
"""Best value after each trial: the convergence curve."""
values = [trial["value"] for trial in self.trials]
pick = np.minimum if direction == "minimize" else np.maximum
return pick.accumulate(values).tolist()
class Tuner:
"""Search a space for the parameters that optimise an objective.
Either call `optimize(objective)`, or drive it yourself with `suggest()` and `report(params, value)`
(useful when trials run somewhere else).
"""
def __init__(self, space: dict | SearchSpace, config: HPOConfig | None = None) -> None:
self.space = space if isinstance(space, SearchSpace) else SearchSpace(space)
self.config = config or HPOConfig()
self.rng = np.random.default_rng(self.config.seed)
self.trials: list[dict] = []
self._grid = self.space.grid(self.config.grid_points) if self.config.method == "grid" else []
# ------------------------------------------------------------------------------------ model inputs
def _observations(self) -> tuple[np.ndarray, np.ndarray]:
"""Trials as (points in the unit cube (n, d), losses (n,)) where smaller loss is always better."""
points = np.array([self.space.encode(trial["params"]) for trial in self.trials])
sign = 1.0 if self.config.direction == "minimize" else -1.0
return points, sign * np.array([trial["value"] for trial in self.trials])
def _suggest_bayesian(self) -> np.ndarray:
cfg, d = self.config, len(self.space.names)
points, losses = self._observations()
spread = losses.std()
scaled = (losses - losses.mean()) / (spread if spread > 0 else 1.0)
# candidates: uniform over the cube, plus small perturbations of the best point so far
local = points[losses.argmin()] + 0.05 * self.rng.normal(size=(cfg.n_candidates // 4, d))
candidates = np.vstack([self.rng.uniform(size=(cfg.n_candidates, d)), np.clip(local, 0.0, 1.0)])
mean, std = gp_posterior(points, scaled, candidates, noise=1e-4)
return candidates[expected_improvement(mean, std, scaled.min()).argmax()]
def _suggest_tpe(self) -> np.ndarray:
cfg, d = self.config, len(self.space.names)
points, losses = self._observations()
n_good = max(1, int(math.ceil(cfg.gamma * len(losses))))
order = np.argsort(losses, kind="stable")
good, bad = points[order[:n_good]], points[order[n_good:]]
chosen = np.zeros(d)
for j, name in enumerate(self.space.names):
slots = self.space.n_slots(name)
if slots: # discrete: smoothed frequency of each slot among the good and the bad trials
def frequency(column):
counts = np.bincount(np.minimum((column * slots).astype(int), slots - 1), minlength=slots)
return (counts + 1.0) / (counts.sum() + slots)
p_good, p_bad = frequency(good[:, j]), frequency(bad[:, j])
picks = self.rng.choice(slots, size=cfg.n_candidates, p=p_good) # draw from "good"
best = picks[(p_good[picks] / p_bad[picks]).argmax()]
chosen[j] = (best + 0.5) / slots
continue
def density(x, centres):
"""Parzen estimate on [0, 1]: a uniform prior plus one Gaussian bump per observation."""
width = max(0.05, 1.0 / (1.0 + len(centres)))
bumps = np.exp(-0.5 * ((x[:, None] - centres[None, :]) / width) ** 2) / (width * math.sqrt(2 * math.pi))
return (1.0 + bumps.sum(axis=1)) / (1.0 + len(centres))
width = max(0.05, 1.0 / (1.0 + len(good)))
centres = good[self.rng.integers(0, len(good), size=cfg.n_candidates), j]
samples = np.clip(centres + width * self.rng.normal(size=cfg.n_candidates), 0.0, 1.0) # draw from "good"
chosen[j] = samples[(density(samples, good[:, j]) / density(samples, bad[:, j])).argmax()]
return chosen
# ------------------------------------------------------------------------------------------- public
def suggest(self) -> dict:
"""Parameters for the next trial."""
cfg = self.config
if cfg.method == "grid":
if len(self.trials) >= len(self._grid):
raise StopIteration("the grid is exhausted")
return dict(self._grid[len(self.trials)])
if cfg.method == "random" or len(self.trials) < cfg.n_initial:
return self.space.decode(self.rng.uniform(size=len(self.space.names)))
point = self._suggest_bayesian() if cfg.method == "bayesian" else self._suggest_tpe()
return self.space.decode(point)
def report(self, params: dict, value: float) -> None:
"""Record the objective value of a trial."""
value = float(value)
if not math.isfinite(value):
raise ValueError(f"objective returned {value} for {params}")
self.trials.append({"params": dict(params), "value": value})
def result(self) -> TuningResult:
"""The best trial so far and the full list."""
if not self.trials:
raise ValueError("no trials have been reported")
pick = min if self.config.direction == "minimize" else max
best = pick(self.trials, key=lambda trial: trial["value"])
return TuningResult(dict(best["params"]), best["value"], list(self.trials))
def optimize(self, objective: Callable[[dict], float]) -> TuningResult:
"""Run the search: call objective(params) -> float for each suggested trial."""
total = len(self._grid) if self.config.method == "grid" else self.config.n_trials
while len(self.trials) < total:
params = self.suggest()
self.report(params, objective(params))
return self.result()- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 12, run with
python3 -m unittest -v
Practice
Tune ridge regression as in the template's README with Tuner({"alpha": ("log", 1e-4, 1e3)}, HPOConfig(method=m, n_trials=25, seed=0)) for random, bayesian and tpe. Plot result.best_so_far() for each. Then call expected_improvement on the two candidates of the worked example and check the numbers.
Check on learning
- With two hyperparameters where only one matters, why does random search usually beat a grid with the same number of trials?
A way to think about it
A 5 by 5 grid tests 5 distinct values of the important parameter. Count how many distinct values 25 random points test.
- Expected improvement can be large for a point whose predicted mean is no better than the best so far. Why is that sensible and not a flaw?
A way to think about it
Look at the second term of the formula. Ask what you learn from trying a point you already understand compared with one you do not.
- Why search a learning rate between 0.0001 and 1 on a log scale and not a linear one?
A way to think about it
On a linear scale, work out what share of uniform draws falls below 0.01. Compare that with how different 0.0001 and 0.01 are for training.
- Bayesian optimisation runs 8 random trials first. What would go wrong if it used its model from the very first trial?
A way to think about it
A model fitted to one or two points knows almost nothing. Ask where it would send the next trials and whether it could recover from a bad start.
- After 200 trials the best validation error is 0.081 and the test error of that setting is 0.094. Is the search broken?
A way to think about it
The best of 200 noisy validation scores is lower than the true quality of that setting. Think about what the test set measures that the search could not influence.