Hyperparameter tuning: grid, random and bandit-based search
Treat hyperparameter tuning as optimization of a noisy, expensive black-box function. Compare grid and random search through low effective dimensionality, derive successive halving and Hyperband as adaptive budget allocation, and examine validation-set overfitting. Bayesian optimization is used as a tool; its theory is in m14.
After this lesson you can
- Define search spaces with appropriate scales (logarithmic for rates and regularization) and conditional dependencies.
- Explain why random search outperforms a grid at equal budget using effective dimensionality.
- Implement successive halving and Hyperband and reason about the trade-off between configurations and budget per configuration.
- Use HalvingRandomSearchCV and Optuna with early pruning inside properly nested cross-validation.
- Quantify the risk of overfitting the validation set with large searches.
Before you start
Motivation: tuning also decides who wins
In 2017, Gábor Melis, Chris Dyer and Phil Blunsom (DeepMind) retrained several recurrent language-model architectures presented as state of the art on Penn Treebank: standard LSTMs, Recurrent Highway Networks (RHN), and the architecture-search (NAS) cell of Zoph and Le. The difference from the original papers was equal treatment: a black-box optimizer (Google Vizier, with Gaussian processes and expected improvement) tuned six to seven hyperparameters per model (learning rate, input embedding proportion, weight decay, and three dropout types, plus a fourth in deep LSTMs); the authors note that even so, thousands of evaluations were needed to converge. The result, published at ICLR 2018 as On the State of the Art of Evaluation in Neural Language Models, reversed the ranking. With 10 million parameters, a one-layer LSTM reached test perplexity 59.6, versus 63.5 for RHN and 62.7 for NAS tuned the same way. Originally published numbers for those architectures, with over twice as many parameters, were 65.4 (RHN, 24M) and 64.0 (NAS, 25M). The authors concluded that well-regularized standard LSTMs outperform newer models, and published comparisons mixed architecture quality with uncontrolled variation such as different codebases and limited tuning budgets.
That motivates this lesson. Each algorithm in this module has knobs not learned by training: for ridge and lasso, for logistic regression, learning rate and schedule, number of epochs. In lesson 3’s validation curve you swept one knob manually. With five or ten knobs and fits taking minutes or hours, manual sweeping stops being practical and becomes an optimization problem with three awkward properties: no gradient, expensive evaluations and noisy measurements.
You will build tools in increasing sophistication. First, describe the search space without wasting evaluations. Next, why random search beats a grid. Then successive halving and Hyperband, which allocate budget adaptively and abandon poor configurations early. Next, model-based optimization (TPE) as a tool, with theory in the Bayesian methods module. Finally, a danger common to all: the more you search, the more the result fits validation-set noise.
Formalization: optimizing a noisy, expensive black box
Let be a training algorithm with hyperparameters : it receives data and returns a predictor . You want to minimize risk, , and can measure an estimate on validation data or with cross-validation. The problem is
Three properties distinguish this from optimization in earlier modules:
- Black box. There is generally no usable gradient of with respect to : many hyperparameters are discrete or categorical (loss, regularization type), and for continuous ones differentiating through all training is expensive and fragile.
- Noise. has two sources: finite validation sampling (with examples, 0-1 error has standard deviation , about 1.4 points for and ) and randomness in training itself (seed, minibatch order).
- Cost. Every evaluation is a fit. Total budget, in epochs, GPU hours or fitted models, is the governing constraint.
The search space
Scale is the most important and most neglected decision. A hyperparameter such as regularization strength or learning rate acts multiplicatively. In ridge, principal direction shrinks by factor , where is a singular value of : moving from to has the same relative effect as moving from 1 to 10, because what matters is relative to , distributed across orders of magnitude. In gradient descent, a stable step is bounded by with the gradient’s Lipschitz constant, another scale known only by order of magnitude. Naturally, sample the exponent uniformly:
With that density, each decade within receives the same probability, . By contrast, on the original scale gives that decade a fraction of the mass, proportional to its length: ten times the preceding decade, with the last receiving almost all if . The next cell implements a sampler with scales and conditions and checks this.
import math
import numpy as np
# Cada entrada: (tipo, argumentos..., [condición]). La condición (padre, valor) activa el parámetro.
SPACE = {
"loss": ("cat", ["hinge", "log"]),
"alpha": ("logu", 1e-6, 1e-1), # fuerza de la regularización
"eta0": ("logu", 1e-4, 1.0), # tasa de aprendizaje inicial
"schedule": ("cat", ["constant", "invscaling"]),
"power_t": ("unif", 0.1, 0.9, ("schedule", "invscaling")),
"penalty": ("cat", ["l2", "elasticnet"]),
"l1_ratio": ("unif", 0.0, 1.0, ("penalty", "elasticnet")),
}
def sample_config(space, rng):
"""Una configuración: recorre el espacio en orden y omite los parámetros cuya condición no se cumple."""
cfg = {}
for name, spec in space.items():
cond = spec[-1] if isinstance(spec[-1], tuple) else None
if cond is not None and cfg.get(cond[0]) != cond[1]:
continue
kind = spec[0]
if kind == "cat":
cfg[name] = spec[1][int(rng.integers(len(spec[1])))]
elif kind == "logu": # log-uniforme: uniforme en log10
cfg[name] = float(10 ** rng.uniform(math.log10(spec[1]), math.log10(spec[2])))
elif kind == "unif":
cfg[name] = float(rng.uniform(spec[1], spec[2]))
return cfg
rng = np.random.default_rng(0)
muestras = [sample_config(SPACE, rng) for _ in range(10_000)]
alpha = np.array([c["alpha"] for c in muestras])
lineal = rng.uniform(1e-6, 1e-1, 10_000) # el error típico: uniforme en la escala original
decadas = [(10.0**k, 10.0**(k + 1)) for k in range(-6, -1)]
print("décadas de alpha: " + " ".join(f"[1e{k},1e{k+1})" for k in range(-6, -1)))
print("log-uniforme " + " ".join(f"{np.mean((alpha >= a) & (alpha < b)):11.3f}" for a, b in decadas))
print("uniforme lineal " + " ".join(f"{np.mean((lineal >= a) & (lineal < b)):11.3f}" for a, b in decadas))
activos = {k: np.mean([k in c for c in muestras]) for k in ("power_t", "l1_ratio", "eta0")}
print("fracción de configuraciones con el parámetro activo:", {k: round(float(v), 3) for k, v in activos.items()})
print("ejemplo:", muestras[0])With , linear uniform sampling puts 90.1% of samples in the final decade and 0.1% in the first two together: if the good value is at , you will almost never see it. Log-uniform puts 20% in each decade. Conditional parameters are active in half the configurations (0.498 and 0.504), as expected when a parent randomly chooses between two options. Notice dictionary order: parents precede children, so by power_t you know whether it exists. Libraries handle this in two ways. scikit-learn accepts a list of dictionaries, one per tree branch. Optuna uses define-by-run: objective-function code defines the space using ordinary if statements as it executes.
Grid versus random search
The grid has two apparent virtues, exhaustiveness and reproducibility, and one drawback dominating both: its cost is exponential in . Random search has a user-chosen cost and a guarantee independent of dimension.
Proof
Events are independent and each has probability , so the probability all fail is . The condition is equivalent to ; taking logs gives , and since , dividing reverses the inequality.
∎Notably, dimension does not appear in the formula. Bergstra and Bengio use exactly this expression, , as expected random-search performance in their 2012 study. Dimension does control : if the good region is a cube of side along each of axes, . Random search does not defeat the curse of dimensionality; it exploits another property of real problems.
Low effective dimensionality
Bergstra and Bengio’s argument (Random Search for Hyper-Parameter Optimization, JMLR 2012) is that practical functions have low effective dimensionality: for a small hyperparameter subset , with changing across datasets. Their figure 1 summarizes this using nine evaluations of : a grid tests at only three distinct points; random search at nine.
Proof
(1) The combinations take only first-coordinate values; the grid point nearest any is at most half a step away, . (2) First coordinates are independent uniforms, and two coincide with probability 0. Event means none falls in , length if inside ; by independence its probability is . Integrating the tail, , where the approximation ignores the nearest edge, which matters only if is within a few times of it. This is the expected minimum order statistic of distances.
∎With nine evaluations in two dimensions, the grid leaves at mean distance (if is uniform) and random search at about . With 25 evaluations, 0.0625 versus 0.019. The advantage grows with dimension: a -point grid over five hyperparameters still tests only three values of the relevant one; 243 random samples test 243.
The figure’s surface comes from a real experiment. We train linear classifiers with SGD on a small problem: deciding whether an -pixel handwritten digit (scikit-learn’s digits dataset, 1797 images) is even or odd, with 1000 training examples, 400 validation and 397 test untouched until the end. The trainer is vectorized: it trains configurations at once, each with its loss (hinge or logistic), penalty (L2 or elastic net), initial rate and schedule. All see minibatches in the same order, so a configuration’s result does not depend on which others train with it or whether it pauses and resumes. The resource you allocate is epochs.
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
y = np.where(y % 2 == 1, 1.0, -1.0) # tarea binaria: dígito impar frente a par
perm = np.random.default_rng(0).permutation(len(y))
X, y = X[perm], y[perm]
mu, sd = X[:1000].mean(0), X[:1000].std(0) + 1e-8 # estandarizar con el entrenamiento solamente
X = (X - mu) / sd
Xtr, ytr = X[:1000], y[:1000] # entrenamiento
Xva, yva = X[1000:1400], y[1000:1400] # validación (400)
Xte, yte = X[1400:], y[1400:] # test intocable (397)
class LinearSGD:
"""M clasificadores lineales entrenados a la vez con SGD por minilotes, cada uno con sus hiperparámetros.
Pérdida bisagra o logística, regularización L2 o elastic net, tasa constante o eta0 / t^power_t.
El orden de los ejemplos de cada época es el mismo para todos, así que el resultado de cada
configuración no depende de con cuáles se entrene ni de si se reanuda: el recurso son las épocas."""
BATCH = 32
def __init__(self, configs, d):
M = len(configs)
self.W, self.b = np.zeros((M, d)), np.zeros(M)
self.epochs = self.steps = 0
self.hinge = np.array([c["loss"] == "hinge" for c in configs])
self.alpha = np.array([c["alpha"] for c in configs])
self.eta0 = np.array([c["eta0"] for c in configs])
self.pw = np.array([c.get("power_t", 0.0) for c in configs]) # 0 = tasa constante
self.rho = np.array([c.get("l1_ratio", 0.0) for c in configs]) # 0 = solo L2
def train(self, epochs, X, y):
n = len(y)
for _ in range(epochs):
order = np.random.default_rng(1000 + self.epochs).permutation(n)
for s in range(0, n, self.BATCH):
idx = order[s:s + self.BATCH]
Xb, yb = X[idx], y[idx]
self.steps += 1
m = (self.W @ Xb.T + self.b[:, None]) * yb # márgenes, (M, B)
dl = np.where(self.hinge[:, None], -(m < 1.0).astype(float), # derivada de la pérdida
-1.0 / (1.0 + np.exp(np.clip(m, -30, 30)))) * yb # respecto de la puntuación
eta = self.eta0 / self.steps ** self.pw
reg = self.alpha[:, None] * ((1 - self.rho)[:, None] * self.W + self.rho[:, None] * np.sign(self.W))
self.W -= eta[:, None] * (dl @ Xb / len(idx) + reg)
self.b -= eta * dl.mean(1)
self.epochs += 1
return self
def error(self, X, y):
"""Error de clasificación (0-1) de cada configuración."""
return ((X @ self.W.T + self.b) * y[:, None] <= 0).mean(0)
def logloss(self, X, y):
"""Entropía cruzada media log(1 + e^{-y s}) de cada configuración."""
return np.logaddexp(0.0, -(X @ self.W.T + self.b) * y[:, None]).mean(0)# Superficie real: pérdida logística, tasa constante, L2; 24 x 24 valores de (alpha, eta0), 9 épocas.
# El objetivo es la entropía cruzada de validación, menos ruidosa que el error 0-1.
G = 24
la, le = np.linspace(-6, -1, G), np.linspace(-4, 0, G)
rejilla_fina = [{"loss": "log", "alpha": 10**a, "eta0": 10**e} for a in la for e in le]
sup = LinearSGD(rejilla_fina, X.shape[1]).train(9, Xtr, ytr)
E = sup.logloss(Xva, yva).reshape(G, G) # filas: alpha; columnas: eta0
Ete = sup.logloss(Xte, yte).reshape(G, G)
tot = E.var()
ia_opt, ie_opt = np.unravel_index(E.argmin(), E.shape)
print(f"entropía cruzada de validación: mínimo {E.min():.4f} (alpha = {10**la[ia_opt]:.1e}, eta0 = {10**le[ie_opt]:.1e}), máximo {E.max():.4f}")
print(f"fracción de la varianza explicada: alpha {E.mean(1).var() / tot:.3f}, eta0 {E.mean(0).var() / tot:.3f}, "
f"interacción {1 - (E.mean(1).var() + E.mean(0).var()) / tot:.3f}")
g = np.random.default_rng(1)
print(" N | rejilla: valores de eta0, val, test | aleatoria (media de 1000 búsquedas): valores de eta0, val, test")
for s in (3, 4, 5):
idx = np.round(np.linspace(0, G - 1, s)).astype(int)
celdas = (idx[:, None] * G + idx[None, :]).ravel() # la rejilla s x s
k = celdas[np.argmin(E.flat[celdas])]
aleat = np.argsort(g.random((1000, G * G)), axis=1)[:, : s * s] # 1000 subconjuntos aleatorios de s^2 celdas
best = aleat[np.arange(1000), np.argmin(E.flat[aleat], axis=1)]
distintos = np.mean([len(np.unique(a % G)) for a in aleat])
print(f"{s*s:2d} | {s:2d} {E.flat[k]:.4f} {Ete.flat[k]:.4f} | {distintos:5.1f} {E.flat[best].mean():.4f} {Ete.flat[best].mean():.4f}")The surface is nearly one-dimensional: explains 99.7% of validation cross-entropy variance and 0.1%. With 9 evaluations, the grid tests 3 values and its best point gives 0.2518; random search tests 7.7 distinct values on average (repetitions are possible on the fine grid of 24) and its best point averages 0.2293, only 0.0085 from the 576-cell optimum, 0.2208. With 16 evaluations, 0.2424 versus 0.2263; with 25, 0.2297 versus 0.2251. Test columns tell the same story, so this is not an effect of selection on validation.
Bergstra and Bengio measured this on real neural networks. They repeated experiments by Larochelle and colleagues (2007), who had tuned single-hidden-layer networks by grid search on image datasets (MNIST variants with rotations and backgrounds, and synthetic rectangle and convex-shape problems), finding that in an equivalent restricted space eight random trials sufficed to match or beat the grid. An expanded space with preprocessing options needed 32. For deep belief networks, whose 32-dimensional space had been tuned using manual and grid search, pure random search matched results on four of seven datasets and surpassed one. Gaussian-process analysis of the surfaces confirmed the explanation: on most datasets only a few hyperparameters mattered, and not always the same ones.
Successive halving: abandon poor configurations early
Random search trains each configuration to completion, even when divergence is visible in the first epoch. If training can be measured along the way, do better: give many configurations a small budget, see which lead, and concentrate the rest on promising ones. The resource may be epochs or iterations, training subsample size, or number of ensemble trees: anything making training cheaper whose partial result predicts the final one.
That last condition is empirical, so we measure it. The next cell trains 729 search-space configurations for 27 epochs and saves their full validation and test learning curves.
from scipy.stats import spearmanr
POOL, R_MAX = 729, 27
pool = [sample_config(SPACE, np.random.default_rng(10_000 + i)) for i in range(POOL)]
modelo = LinearSGD(pool, X.shape[1])
curva_va, curva_te = np.empty((POOL, R_MAX)), np.empty((POOL, R_MAX))
for r in range(R_MAX):
modelo.train(1, Xtr, ytr)
curva_va[:, r], curva_te[:, r] = modelo.error(Xva, yva), modelo.error(Xte, yte)
def train_fn(i, r):
"""Error de validación de la configuración i tras r épocas (consulta la curva ya calculada)."""
return curva_va[i, r - 1]
fin = curva_va[:, -1]
print(f"error de validación tras {R_MAX} épocas: mínimo {fin.min():.4f}, mediana {np.median(fin):.4f}, máximo {fin.max():.4f}")
for r in (1, 3, 9):
print(f" correlación de Spearman entre el ranking a {r:2d} épocas y a {R_MAX}: {spearmanr(curva_va[:, r - 1], fin)[0]:.3f}")
top = np.argsort(fin, kind="stable")[:10]
print("las 10 mejores a 27 épocas: puesto que ocupaban tras 1 época:",
[int(np.sum(curva_va[:, 0] < curva_va[i, 0])) + 1 for i in top])After 27 epochs, validation error ranges from 0.0825 to 0.19, median 0.125. Spearman rank correlation between ranking after epochs and final ranking is 0.645 at , 0.844 at and 0.893 at : the first epoch ranks fairly well, but imperfectly. Notice the last line: after one epoch the final top ten included ranks 92, 159 and 225 of 729. Discarding everything outside the first third after one epoch would lose some of them.
The name comes from , the case analyzed by Karnin, Koren and Somekh (2013) for stochastic bandits. Cost accounting makes it attractive. Without resuming, round costs : all rounds cost the same, totaling . Training all configurations to costs . The ratio is : with , and , 405 epochs versus 6561, sixteen times less. Resuming costs even less because each survivor trains only its remaining epochs.
def successive_halving(ids, train_fn, r_min, eta, r_max=None):
"""Successive halving sobre las configuraciones ids. Coste: épocas, reanudando (cada superviviente
solo entrena las épocas que le faltan). Devuelve (mejor, su error, coste, historia por rondas)."""
vivos, r, prev, coste, hist = list(ids), r_min, 0, 0, []
while True:
errs = np.array([train_fn(i, r) for i in vivos])
coste += (r - prev) * len(vivos)
hist.append((r, len(vivos), coste))
k = max(1, len(vivos) // eta)
if len(vivos) == 1 or (r_max is not None and r * eta > r_max):
j = int(np.argmin(errs))
return vivos[j], float(errs[j]), coste, hist
orden = np.argsort(errs, kind="stable")
vivos, prev, r = [vivos[j] for j in orden[:k]], r, r * eta
carrera = list(range(27)) # las 27 primeras del pool
mejor_real = min(carrera, key=lambda i: curva_va[i, -1])
for r_min in (1, 3):
best, err, coste, hist = successive_halving(carrera, train_fn, r_min, 3, r_max=R_MAX)
print(f"r_min = {r_min}: rondas (épocas, configuraciones, coste acumulado) {hist}")
print(f" elegida {best}: validación {err:.4f}, test {curva_te[best, hist[-1][0] - 1]:.4f}; "
f"la mejor a 27 épocas era la {mejor_real} (validación {curva_va[mejor_real, -1]:.4f}, test {curva_te[mejor_real, -1]:.4f}); "
f"búsqueda aleatoria con las 27 a 27 épocas: coste {27 * R_MAX}")
i = mejor_real
print(f"curva de la {i}: " + " ".join(f"r={r}: {curva_va[i, r - 1]:.3f} (puesto {int(np.sum(curva_va[carrera, r - 1] < curva_va[i, r - 1])) + 1})" for r in (1, 3, 9, 27)))With 27 configurations, and , rounds are at epochs and cost 81 epochs (27 in the first round and 18 in each of the next three), versus 729 to train all of them. But see configuration 6, lowest validation error at 27 epochs (0.0925): after one epoch it ranked 25 of 27 and is eliminated in round one. With it ranked 13th and is also eliminated because only 9 advance. This is the risk of judging early: slow starters die before proving their worth. Configuration 6 is a textbook example: hinge loss with small constant rate , whose validation error falls from 0.185 to 0.152, 0.125 and 0.092 after 1, 3, 9 and 27 epochs.
There is a second reading you should not skip. The chosen configuration (24) has validation error 0.0975 at 27 epochs versus 0.0925 for 6: a difference of two examples out of 400, well below validation noise ( points). On test, the chosen one gives 0.0756 and 6 gives 0.1008. Here the “injustice” cost nothing; on other problems it can, and the next figure shows both cases.
Why it works: best-arm identification
Jamieson and Talwalkar (2016) gave the theoretical framework. Each configuration is a bandit arm; pulling it means training one more unit, and its validation-loss sequence is not random and independent as in classical bandits, but an arbitrary learning curve. The only assumption is convergence: exists. Define the envelope as the smallest nonincreasing function satisfying for all , and its inverse as the number of pulls needed to bring the curve within of its limit. Order arms so and let . The goal is to identify arm 1 with little total budget: best-arm identification without stochasticity.
The first claim is the heart of the argument and you reconstruct it in a guided exercise. Budget bounds are the paper’s theorems 1–3. The key comparison bounds by : successive halving pays, up to a logarithmic factor, the sum of costs of distinguishing each arm from the best, while uniform allocation pays times the maximum. If a few configurations are close to the best and most are far away (the usual case), the sum is much smaller than times the maximum. The price is dependence on envelopes: if a curve takes long to approach its limit (slowly decreasing ), the theorem requires a large budget, and with fixed budget and small you may eliminate it.
The three real races (pool configurations 0–26, 27–53 and 54–80) tell different stories. In the second, the best at 27 epochs is among the leaders from the start and wins for any . In the first it always falls, even with , because after 9 epochs it is tenth of 27 and only nine advance. In the third it falls with and and wins with . The slow-start model is explicit: configuration has error plus normal noise with standard deviation 0.006 at each evaluation, with final value and time constant log-uniform on epochs, independently. Since speed says nothing about final quality, a good slow configuration trails early, and orange often dies with . Raising saves it more often but makes each round three times as expensive. No works best for every problem: it depends on how well early ranking predicts the final one, precisely what is unknown initially.
Hyperband: hedge against the wrong minimum budget
Successive halving with total budget requires choosing : many configurations with little budget each (aggressive exploration, risky for slow starters) or a few with much (conservative, wasting budget on bad configurations). Li, Jamieson, DeSalvo, Rostamizadeh and Talwalkar (JMLR 2018) proposed not choosing.
Bracket is most aggressive (most configurations, minimum budget , one unit if is a power of ), and is random search: configurations trained to . Without resuming, each bracket spends at most about units, and the total is on the order of . Hyperband thus searches geometrically over average budget per configuration, at roughly times the work of choosing the right bracket first. In bandit terms, each bracket attempts best-arm identification with infinitely many arms (you can sample as many configurations as desired) and unknown curve convergence rates; the full analysis is in best-arm identification and successive halving.
def brackets(R, eta):
"""(s, n, r) de cada bracket de Hyperband, como en el algoritmo 1 de Li et al."""
s_max = int(math.floor(math.log(R) / math.log(eta) + 1e-9))
B = (s_max + 1) * R
return [(s, int(math.ceil(B / R * eta**s / (s + 1))), R * eta**(-s)) for s in range(s_max, -1, -1)]
for s, n, r in brackets(81, 3):
print(f"R = 81, eta = 3, bracket s = {s}: n = {n:3d}, r = {r:4.0f}; n_i = {[int(n * 3.0**(-i)) for i in range(s + 1)]}")
def hyperband(nuevas, train_fn, R, eta):
"""nuevas(n) devuelve n configuraciones sin usar. Devuelve (mejor, su error, coste total, traza)."""
mejor, coste, traza = (None, np.inf), 0, []
for s, n, r in brackets(R, eta):
b, e, c, _ = successive_halving(nuevas(n), train_fn, int(round(r)), eta, r_max=R)
coste += c
traza.append((s, n, int(round(r)), c, b, e))
if e < mejor[1]:
mejor = (b, e)
return mejor[0], mejor[1], coste, traza
primeras = iter(range(POOL))
_, _, B_HB, traza = hyperband(lambda n: [next(primeras) for _ in range(n)], train_fn, R_MAX, 3)
print(f"\nHyperband con R = {R_MAX}, eta = 3: brackets (s, n, r, coste) = {[t[:4] for t in traza]}; coste total {B_HB} épocas")
def una_busqueda(metodo, candidatas, g, B=B_HB, eta=3, R=R_MAX):
"""Configuración elegida por el método con un presupuesto de B épocas (las configuraciones salen al azar de candidatas)."""
orden = iter(g.permutation(candidatas))
nuevas = lambda n: [int(next(orden)) for _ in range(n)]
if metodo == "Hyperband":
return hyperband(nuevas, train_fn, R, eta)[0]
if metodo == "aleatoria": # cada configuración, R épocas completas
ids = nuevas(B // R)
return ids[int(np.argmin(fin[ids]))]
s = int(metodo[-1]) # un solo bracket, repetido mientras quepa
_, n, r = brackets(R, eta)[-1 - s]
ganadoras, gastado = [], 0
while True:
b, e, c, _ = successive_halving(nuevas(n), train_fn, int(round(r)), eta, r_max=R)
if gastado + c > B:
break
gastado += c
ganadoras.append((e, b))
return min(ganadoras)[1]
metodos = ["aleatoria", "bracket s=1", "bracket s=2", "bracket s=3", "Hyperband"]
perdida = np.array([c["loss"] for c in pool])
print(f"\nerror de TEST medio de la configuración elegida (300 búsquedas, presupuesto {B_HB} épocas cada una)")
print(f"{'espacio':15s}" + "".join(f"{m:>14s}" for m in metodos))
for nombre, cand in [("ambas pérdidas", np.arange(POOL)), ("solo bisagra", np.flatnonzero(perdida == "hinge")),
("solo logística", np.flatnonzero(perdida == "log"))]:
res = {m: [curva_te[una_busqueda(m, cand, np.random.default_rng(rep)), -1] for rep in range(300)] for m in metodos}
print(f"{nombre:15s}" + "".join(f"{np.mean(v):8.4f}±{np.std(v) / np.sqrt(300):.4f}" for v in res.values()))
print(f"referencias: mediana del pool {np.median(curva_te[:, -1]):.4f}; mejor del pool en test {curva_te[:, -1].min():.4f}")The first table is Li et al.’s for and : five brackets with configurations and initial budgets . The paper’s table 1 shows : endpoints agree, but for it differs from the formula in its own algorithm 1 (, for example). Here we use the formula. In the paper’s example (LeNet on MNIST, epochs), the best bracket was intermediate , neither most aggressive nor most conservative; Hyperband nearly matched it and beat random search. Across their experiments the authors observed speedups of over an order of magnitude against competitors.
In our problem, with , Hyperband runs four brackets costing 81, 78, 90 and 108 epochs: 357 total. With that fixed budget, mean test error of the chosen configuration (300 searches over the pool of 729) is 0.0943 with random search, 0.0930 repeating bracket , 0.0892 with , 0.0870 with the most aggressive , and 0.0906 with Hyperband. The ordering matches theory for a problem with informative early ranking (Spearman 0.645 after one epoch): more aggressive is better; Hyperband is in the middle because it spends part of the budget on conservative brackets unnecessary here. It is insurance, and insurance has a cost when nothing goes wrong. Restricting the space to one loss changes the level (hinge reaches 0.0867, logistic does not go below 0.0969 in 27 epochs), but not the ordering.
Two developments used in practice. ASHA (Li et al., 2020) performs asynchronous successive halving: instead of waiting for a round to finish, it promotes a configuration as soon as it is in the top fraction of those reaching its level, keeping hundreds of parallel workers busy. BOHB (Falkner, Klein and Hutter, 2018) retains Hyperband’s structure but samples new configurations from a density model rather than uniformly.
Model-based optimization and trial pruning
Random search and brackets learn nothing from past evaluations: configuration 300 is sampled like the first. Model-based optimization (SMBO) fits a model of to completed evaluations and chooses the next by maximizing an acquisition function balancing exploration of uncertain regions with exploitation of good ones. With a Gaussian process as model and expected improvement as acquisition, this is Bayesian optimization, whose theory you study in the Bayesian methods module. Here we use it as a tool.
The tree-structured Parzen estimator (TPE, Bergstra, Bardenet, Bengio and Kégl, 2011) is Optuna’s default sampler and models the reverse: instead of , it fits two search-space densities,
where is a quantile of observed losses (in Optuna, “good” trials are the best 10%, at most 25). Each density is a product of per-hyperparameter kernel estimates and respects the condition tree because each hyperparameter is modeled only on trials where active. The next configuration maximizes among samples from (24 by default in Optuna); the authors show this maximizes expected improvement under their model, since expected improvement is proportional to , with the good-trial fraction. Before it has a model, Optuna runs 10 random trials. TPE is cheap (linear in trial count) and handles conditional and categorical spaces, in exchange for modeling hyperparameters separately and missing interactions.
Pruning brings successive halving into sequential search. Each trial reports intermediate loss after each epoch (trial.report) and asks whether to continue (trial.should_prune). Optuna’s median rule (MedianPruner) prunes at step if the trial’s best intermediate value so far is worse than the median of previous trials’ intermediate values at that same step. With n_startup_trials=5 it prunes nothing until five trials finish, and with n_warmup_steps=3 nothing before step 3 (here, the third epoch). This is a sequential version of successive halving with and a gentler threshold: retain the best half, not a third. Optuna (Akiba et al., KDD 2019) also offers asynchronous successive halving and Hyperband pruning.
Overfitting validation
Every search chooses the argmin of a noisy estimate, and the minimum of many noisy estimates is optimistic. You saw this as best-of- bias in nested cross-validation. Here we examine it from the search side: what controls its size and how trial count matters.
A simple model shows what controls it. Suppose configurations have the same risk and normally distributed validation errors with equal variance and pairwise correlation : , with independent standard normals . Then
The common part does not affect the winner, only the independent part does. And is directly measurable: half the variance of the difference between two configurations. If two classifiers disagree on a fraction of examples and have similar errors, the variance of their validation-error difference is , so
It grows like with trial count and decreases like with validation size. The chosen configuration’s test score, in contrast, is unbiased: test did not participate in selection.
from scipy import integrate, stats
# Un espacio estrecho en el que todas las configuraciones son casi equivalentes
ESTRECHO = {"loss": ("cat", ["log"]), "alpha": ("logu", 1e-5, 1e-3), "eta0": ("logu", 0.03, 0.3)}
cfgs = [sample_config(ESTRECHO, np.random.default_rng(50_000 + i)) for i in range(200)]
m200 = LinearSGD(cfgs, X.shape[1]).train(27, Xtr, ytr)
Xh, yh = X[1000:], y[1000:] # los 797 ejemplos que no se usan para entrenar
acierta = ((Xh @ m200.W.T + m200.b) * yh[:, None] > 0).T # (200 configuraciones, 797 ejemplos)
err_h = 1 - acierta.mean(1)
print(f"error en los 797 ejemplos reservados: media {err_h.mean():.4f}, desviación entre configuraciones {err_h.std():.4f}, "
f"rango {err_h.min():.4f} a {err_h.max():.4f}; aciertos totales {int(acierta.sum())}")
distintas = len(np.unique(acierta, axis=0))
en_disputa = int(np.sum((acierta.mean(0) > 0) & (acierta.mean(0) < 1)))
print(f"patrones de predicción distintos: {distintas} de 200; ejemplos en los que alguna discrepa: {en_disputa} de 797")
reps, Ns = 400, (1, 3, 10, 30, 100, 200)
print("n_val N:" + "".join(f"{N:>17d}" for N in Ns) + " (mejor validación / test de la elegida)")
brecha = {}
for n_val in (50, 100, 400):
filas = np.zeros((len(Ns), 2))
for rep in range(reps):
g = np.random.default_rng(rep)
ej, conf = g.permutation(len(yh)), g.permutation(200)
va_e, te_e = ej[:n_val], ej[n_val:] # validación y test disjuntos, sorteados cada vez
ev, et = 1 - acierta[:, va_e].mean(1), 1 - acierta[:, te_e].mean(1)
for j, N in enumerate(Ns):
c = conf[:N][np.argmin(ev[conf[:N]])] # la búsqueda prueba N configuraciones
filas[j] += ev[c], et[c]
filas /= reps
brecha[n_val] = filas[:, 1] - filas[:, 0]
print(f"{n_val:5d} " + "".join(f" {a:.4f} / {b:.4f}" for a, b in filas))
# Predicción: si las N puntuaciones fueran normales equicorrelacionadas, con Var(e_j - e_k) = d / n_val
A = acierta.astype(float)
a = A.mean(1)
D = a[:, None] + a[None, :] - 2 * (A @ A.T) / A.shape[1] # D[j, k] = fracción de ejemplos en que discrepan
d = D[np.triu_indices(200, 1)].mean()
e_max = lambda N: integrate.quad(lambda z: z * N * stats.norm.pdf(z) * stats.norm.cdf(z) ** (N - 1), -10, 10)[0]
print(f"\ndesacuerdo medio entre dos configuraciones d = {d:.4f}")
for n_val in (50, 100, 400):
pred = [np.sqrt(d / (2 * n_val)) * e_max(N) for N in Ns]
print(f"n_val = {n_val:3d}: brecha medida " + " ".join(f"{b:.4f}" for b in brecha[n_val])
+ " | predicha " + " ".join(f"{p:.4f}" for p in pred))The 200 configurations in this experiment come from a narrow space and are nearly equivalent: their error on 797 held-out examples averages 0.0982 with between-configuration standard deviation 0.0026. Each repetition samples validation examples and uses the rest as untouched test. With , best validation falls from 0.0994 () to 0.0884 (), while the chosen model’s test stays at 0.0985: a 1-point gap corresponding to nothing real. With the maximum gap is 0.6 points (0.0920 versus 0.0977).
The normal model predicts the first configurations accurately ( measured versus predicted for and ), but beyond it greatly exceeds measurements: it predicts 3.1 points for and , while the measured gap plateaus at 1. The diagnostic line explains why: 200 configurations produce only 34 distinct classifiers and disagree on 26 of 797 examples. There are not 200 independent bets on validation, but a few. The equicorrelated model assumes each new configuration brings new noise; here almost all repeat another’s predictions. The figure lets you compare the opposite case.
With independent errors the gap keeps growing with and is several times larger, on the order predicted by the formula. This is the dangerous situation: broad spaces, flexible models (boosting or networks with dozens of hyperparameters), and small validation sets. Three practical consequences:
- The best trial’s validation score is not expected performance. For reporting, use nested CV (entire search inside each outer fold) or a test set that played no part in decisions.
- A repeatedly consulted test ceases to be a test. Each time you inspect it to decide something (another architecture or preprocessing), it becomes validation. Cawley and Talbot (JMLR 2010) documented how selection overfitting biases algorithm comparisons; Dwork and colleagues (Science 2015) proposed “reusable holdout” mechanisms adding controlled noise to each query.
- More search is not always better. If validation noise exceeds real differences between good configurations, more searching only selects noise. You will see this in the local lab’s curves below.
Tools: HalvingRandomSearchCV and Optuna
scikit-learn implements successive halving in HalvingGridSearchCV and HalvingRandomSearchCV, still experimental: import them after from sklearn.experimental import enable_halving_search_cv. The default resource is training-sample count; resource= can select any integer estimator parameter, such as max_iter (SGD epochs) or n_estimators. factor is our and min_resources is . A conditional space is a list of dictionaries, one per branch. Like any scikit-learn search, the object is an estimator, so placing it in cross_val_score gives nested CV without extra code.
import warnings
from scipy.stats import loguniform, uniform
from sklearn.exceptions import ConvergenceWarning
from sklearn.experimental import enable_halving_search_cv # noqa: F401 (activa la clase experimental)
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import HalvingRandomSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
warnings.filterwarnings("ignore", category=ConvergenceWarning) # tol=None: entrena exactamente max_iter épocas
Xd, yd = load_digits(return_X_y=True)
yd = (yd % 2 == 1).astype(int)
Xd, yd = Xd[perm], yd[perm] # el mismo orden que antes
Xdev, ydev, Xtest, ytest = Xd[:1400], yd[:1400], Xd[1400:], yd[1400:]
pipe = make_pipeline(StandardScaler(), SGDClassifier(tol=None, random_state=0))
P = "sgdclassifier__"
comunes = {P + "loss": ["hinge", "log_loss"], P + "alpha": loguniform(1e-6, 1e-1), P + "eta0": loguniform(1e-4, 1.0)}
espacio = [ # una lista de diccionarios = un espacio condicional
{**comunes, P + "learning_rate": ["constant"], P + "penalty": ["l2"]},
{**comunes, P + "learning_rate": ["constant"], P + "penalty": ["elasticnet"], P + "l1_ratio": uniform(0, 1)},
{**comunes, P + "learning_rate": ["invscaling"], P + "power_t": uniform(0.1, 0.8), P + "penalty": ["l2"]},
{**comunes, P + "learning_rate": ["invscaling"], P + "power_t": uniform(0.1, 0.8), P + "penalty": ["elasticnet"],
P + "l1_ratio": uniform(0, 1)},
]
busqueda = HalvingRandomSearchCV(pipe, espacio, resource=P + "max_iter", min_resources=1, max_resources=27,
factor=3, cv=StratifiedKFold(3, shuffle=True, random_state=0), random_state=0)
busqueda.fit(Xdev, ydev)
print("rondas (candidatas, épocas):", list(zip(busqueda.n_candidates_, busqueda.n_resources_)))
print(f"mejor exactitud de la CV interna {busqueda.best_score_:.4f}; test intocable {busqueda.score(Xtest, ytest):.4f}")
print("elegida:", {k.replace(P, ""): (round(v, 5) if isinstance(v, float) else v) for k, v in busqueda.best_params_.items()})
externa = cross_val_score(busqueda, Xdev, ydev, cv=StratifiedKFold(3, shuffle=True, random_state=1))
print(f"CV anidada (3 x 3): {externa.mean():.4f} por pliegue {np.round(externa, 4)}")Rounds match our implementation: 27 candidates at 1 epoch, 9 at 3, 3 at 9 and one at 27. Best inner-CV accuracy, 0.9136, is optimistic: untouched test gives 0.8992 and nested CV 0.9100, with folds between 0.9015 and 0.9165. tol=None forces SGD to run exactly max_iter epochs without early stopping so the resource means what it says.
The second lab compares four strategies by budget with new configurations each search (20 searches per method) and repeats nested CV with Optuna. It needs the local kernel because Optuna is not in Pyodide; if your Python lacks it, install with python -m pip install optuna; the cell skips those parts until then.
# El kernel local no comparte memoria con el navegador: repetimos datos, entrenador y muestreador.
import math, warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
warnings.filterwarnings("ignore", category=ConvergenceWarning)
try:
import optuna
optuna.logging.set_verbosity(optuna.logging.WARNING)
except ImportError: # instálalo con: python -m pip install optuna
optuna = None
print("Optuna no está instalado en este Python: python -m pip install optuna (se omiten sus partes)")
X, y = load_digits(return_X_y=True)
y = np.where(y % 2 == 1, 1.0, -1.0)
perm = np.random.default_rng(0).permutation(len(y))
X, y = X[perm], y[perm]
X = (X - X[:1000].mean(0)) / (X[:1000].std(0) + 1e-8)
Xtr, ytr, Xva, yva, Xte, yte = X[:1000], y[:1000], X[1000:1400], y[1000:1400], X[1400:], y[1400:]
class LinearSGD: # el mismo entrenador vectorizado de la lección
def __init__(self, cfgs, d):
self.W, self.b, self.epochs, self.steps = np.zeros((len(cfgs), d)), np.zeros(len(cfgs)), 0, 0
self.hinge = np.array([c["loss"] == "hinge" for c in cfgs])
self.alpha, self.eta0 = np.array([c["alpha"] for c in cfgs]), np.array([c["eta0"] for c in cfgs])
self.pw = np.array([c.get("power_t", 0.0) for c in cfgs])
self.rho = np.array([c.get("l1_ratio", 0.0) for c in cfgs])
def train(self, epochs):
for _ in range(epochs):
order = np.random.default_rng(1000 + self.epochs).permutation(len(ytr))
for s in range(0, len(ytr), 32):
Xb, yb = Xtr[order[s:s + 32]], ytr[order[s:s + 32]]
self.steps += 1
m = (self.W @ Xb.T + self.b[:, None]) * yb
dl = np.where(self.hinge[:, None], -(m < 1.0).astype(float), -1.0 / (1.0 + np.exp(np.clip(m, -30, 30)))) * yb
eta = self.eta0 / self.steps ** self.pw
reg = self.alpha[:, None] * ((1 - self.rho)[:, None] * self.W + self.rho[:, None] * np.sign(self.W))
self.W -= eta[:, None] * (dl @ Xb / len(yb) + reg)
self.b -= eta * dl.mean(1)
self.epochs += 1
return self
def keep(self, idx):
for k in ("W", "b", "hinge", "alpha", "eta0", "pw", "rho"):
setattr(self, k, getattr(self, k)[idx])
def error(self, X, y):
return ((X @ self.W.T + self.b) * y[:, None] <= 0).mean(0)
def sample_config(g): # el espacio condicional de la lección
c = {"loss": ["hinge", "log"][g.integers(2)], "alpha": 10 ** g.uniform(-6, -1), "eta0": 10 ** g.uniform(-4, 0)}
if g.integers(2):
c["power_t"] = g.uniform(0.1, 0.9)
if g.integers(2):
c["l1_ratio"] = g.uniform(0, 1)
return c
R, ETA = 27, 3
def run_sh(cfgs, r_min, gastado, log):
"""Successive halving reanudable. Anota en log (épocas gastadas, val, test) de cada evaluación a R épocas."""
model, r, prev = LinearSGD(cfgs, X.shape[1]), r_min, 0
while True:
model.train(r - prev)
gastado += (r - prev) * len(model.W)
ev = model.error(Xva, yva)
if r == R:
et = model.error(Xte, yte)
log += [(gastado, a, b) for a, b in zip(ev, et)]
if len(model.W) == 1 or r * ETA > R:
return gastado
model.keep(np.argsort(ev, kind="stable")[: max(1, len(model.W) // ETA)])
prev, r = r, r * ETA
def incumbente(log, presupuestos):
"""(validación, test) de la configuración con menor error de validación (a R épocas) terminada antes de cada presupuesto."""
out, best, j = [], (np.inf, np.nan), 0
log = sorted(log, key=lambda t: t[0])
for B in presupuestos:
while j < len(log) and log[j][0] <= B:
if log[j][1] < best[0]:
best = log[j][1:]
j += 1
out.append(best)
return out
def busqueda(metodo, seed, B_max):
g, log, gastado = np.random.default_rng(seed), [], 0
s_max = int(math.floor(math.log(R) / math.log(ETA) + 1e-9))
while gastado < B_max:
if metodo == "aleatoria":
gastado = run_sh([sample_config(g)], R, gastado, log)
elif metodo == "SH (s = 3)":
gastado = run_sh([sample_config(g) for _ in range(27)], 1, gastado, log)
elif metodo == "Hyperband":
for s in range(s_max, -1, -1):
n = int(math.ceil((s_max + 1) * ETA**s / (s + 1)))
gastado = run_sh([sample_config(g) for _ in range(n)], int(round(R * ETA**(-s))), gastado, log)
else: # TPE + poda por mediana
gastado = [0]
def objetivo(trial):
c = {"loss": trial.suggest_categorical("loss", ["hinge", "log"]),
"alpha": trial.suggest_float("alpha", 1e-6, 1e-1, log=True),
"eta0": trial.suggest_float("eta0", 1e-4, 1.0, log=True)}
if trial.suggest_categorical("schedule", ["constant", "invscaling"]) == "invscaling":
c["power_t"] = trial.suggest_float("power_t", 0.1, 0.9) # parámetro condicional
if trial.suggest_categorical("penalty", ["l2", "elasticnet"]) == "elasticnet":
c["l1_ratio"] = trial.suggest_float("l1_ratio", 0.0, 1.0)
model = LinearSGD([c], X.shape[1])
for epoca in range(1, R + 1):
model.train(1)
gastado[0] += 1
ev = float(model.error(Xva, yva)[0])
trial.report(ev, epoca)
if trial.should_prune():
raise optuna.TrialPruned()
log.append((gastado[0], ev, float(model.error(Xte, yte)[0])))
return ev
study = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=seed),
pruner=optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=3))
while gastado[0] < B_max:
study.optimize(objetivo, n_trials=1)
return log, study
return log, None
PRES = (108, 216, 357, 714, 1071)
metodos = ["aleatoria", "SH (s = 3)", "Hyperband"] + (["TPE + mediana"] if optuna else [])
curvas = {m: [] for m in metodos}
for seed in range(20):
for m in metodos:
log, study = busqueda(m, seed, max(PRES))
curvas[m].append(incumbente(log, PRES))
if study is not None and seed == 0:
podados = sum(t.state == optuna.trial.TrialState.PRUNED for t in study.trials)
print(f"TPE, semilla 0: {len(study.trials)} ensayos, {podados} podados; mejor {study.best_params}")
print("\nincumbente: error de validación / error de TEST (media de 20 búsquedas) frente al presupuesto en épocas")
print(f"{'presupuesto':15s}" + "".join(f"{b:>17d}" for b in PRES))
for m, v in curvas.items():
v = np.array(v, dtype=float) # (búsquedas, presupuestos, 2)
print(f"{m:15s}" + "".join(f" {a:.4f} / {b:.4f}" for a, b in np.nanmean(v, 0)))
print(f"{' error típico':15s}" + "".join(f" {a:.4f} / {b:.4f}" for a, b in np.nanstd(v, 0) / np.sqrt(len(v))))
dif = v[:, -1, 1] - v[:, 0, 1] # test con el mayor presupuesto menos test con el menor
print(f"{' test 1071-108':15s} {dif.mean():+.4f} ± {dif.std() / np.sqrt(len(dif)):.4f} (diferencia pareada)")
# CV anidada con Optuna: TPE + poda por mediana con CV interna de 3 pliegues, repetida en cada pliegue externo
if optuna is not None:
Xr, yr = load_digits(return_X_y=True)
Xr, yr = Xr[perm][:1400], (yr[perm][:1400] % 2 == 1).astype(int)
def busqueda_optuna(Xa, ya, n_trials=40, seed=0):
internos = list(StratifiedKFold(3, shuffle=True, random_state=seed).split(Xa, ya))
def objetivo(trial):
kw = {"loss": trial.suggest_categorical("loss", ["hinge", "log_loss"]),
"alpha": trial.suggest_float("alpha", 1e-6, 1e-1, log=True),
"eta0": trial.suggest_float("eta0", 1e-4, 1.0, log=True),
"learning_rate": trial.suggest_categorical("learning_rate", ["constant", "invscaling"])}
if kw["learning_rate"] == "invscaling":
kw["power_t"] = trial.suggest_float("power_t", 0.1, 0.9)
kw["penalty"] = trial.suggest_categorical("penalty", ["l2", "elasticnet"])
if kw["penalty"] == "elasticnet":
kw["l1_ratio"] = trial.suggest_float("l1_ratio", 0.0, 1.0)
mods = []
for tr, va in internos: # el escalado se ajusta dentro de cada pliegue interno
sc = StandardScaler().fit(Xa[tr])
mods.append((SGDClassifier(random_state=0, **kw), sc.transform(Xa[tr]), ya[tr], sc.transform(Xa[va]), ya[va]))
for epoca in range(1, R + 1): # una época por paso: partial_fit
acc = np.mean([m.partial_fit(a, b, classes=[0, 1]).score(c, d) for m, a, b, c, d in mods])
trial.report(acc, epoca)
if trial.should_prune():
raise optuna.TrialPruned()
return acc
st = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=seed),
pruner=optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=3))
st.optimize(objetivo, n_trials=n_trials)
return st
def ajustar(params, Xa, ya):
sc = StandardScaler().fit(Xa)
m = SGDClassifier(random_state=0, **params)
for _ in range(R):
m.partial_fit(sc.transform(Xa), ya, classes=[0, 1])
return lambda Xb: m.predict(sc.transform(Xb))
ext, internas = [], []
for f, (tr, va) in enumerate(StratifiedKFold(3, shuffle=True, random_state=1).split(Xr, yr)):
st = busqueda_optuna(Xr[tr], yr[tr], seed=f)
ext.append(np.mean(ajustar(st.best_params, Xr[tr], yr[tr])(Xr[va]) == yr[va]))
internas.append(st.best_value)
podados = sum(t.state == optuna.trial.TrialState.PRUNED for t in st.trials)
print(f"pliegue externo {f}: {podados} de 40 ensayos podados; mejor CV interna {st.best_value:.4f} -> exactitud externa {ext[-1]:.4f}")
print(f"CV anidada con Optuna: {np.mean(ext):.4f} (media de las mejores CV internas: {np.mean(internas):.4f})")npm run lab and open the connection link.This is what the cell prints with Optuna 5.0 installed; it takes about a minute and a half on CPU. At one Hyperband budget, 357 epochs, ordering matches the Pyodide pool: incumbent test error is 0.0843 with aggressive successive halving, 0.0893 with Hyperband, 0.0907 with random search and 0.0926 with TPE and median pruning. TPE starts worse (0.1003 at 108 epochs, because its first ten trials are random and the model knows nothing yet) and is the only method whose test clearly improves with budget: 0.0898 at 1071 epochs, 1.05 points less (paired difference ). At seed 0 it ran 78 trials, pruning 44; without pruning, 1071 epochs allow only 39.
But look at each cell’s two columns. Incumbent validation decreases monotonically with budget for all four methods, to 0.087 or 0.088. Test does not follow: random search stays flat, and successive halving and Hyperband worsen, and between 108 and 1071 epochs. At 108 epochs, successive halving’s sole finalist has 0.0948 validation and 0.0811 test; at 1071 there are thirteen finalists and the winner is best on these particular 400 validation examples, not on test. Since validation and test are the same across all 20 searches, those standard errors measure search variability, not split variability: another split could change the signs. The robust conclusion: with 400 validation examples, beyond a few hundred search epochs validation noise and peculiarities decide, and more search no longer buys real performance. This is the preceding section’s validation overfitting viewed through budget curves.
Nested CV with Optuna quantifies this for the full procedure: across three outer folds, best inner CV scores are 0.9121, 0.9250 and 0.9069, and outer accuracies 0.9101, 0.8929 and 0.9142. The outer mean, 0.9057, is 0.9 points below the inner mean, 0.9147. Nested CV with HalvingRandomSearchCV gave 0.9100: both tools end up in the same place for this problem, and their difference is smaller than variation across folds.
Search-space recipes
| Model | Hyperparameter | Starting range and scale |
|---|---|---|
| Ridge, lasso (standardized features) | log-uniform; for lasso, to , as in the regularization path | |
| Logistic regression | log-uniform on ; penalty and l1_ratio as conditional branches | |
| Linear SGD | , , schedule | log-uniform on , log-uniform on , power_t only with invscaling |
| RBF kernel SVM | , | logarithmic scale: LIBSVM guide (Hsu, Chang and Lin) recommends and as a first coarse grid |
| Any epoch-trained model | number of epochs | as successive-halving resource, not a sampled hyperparameter |
Kernel SVMs appear later in this module; two hyperparameters that both matter are a case where a coarse logarithmic grid, later refined around its best point, remains reasonable. For gradient boosting see GBDT tuning; for deep networks, see learning-rate and schedule tuning in the deep learning module and hyperparameter transfer. When comparing methods give them equal tuning budgets: this is the lesson of Melis et al. and tuning-budget parity.
Common mistakes
Exercises
Step 1 of 3. How do you write to use the envelopes?
successive_halving(configs, train_fn, budget_min, eta). train_fn(config, r) returns deterministic validation loss of config after r resource units. In each round evaluate survivors at current budget r; if only one remains, stop; otherwise keep the max(1, len(vivas) // eta) lowest-loss configurations (ties go to the one earlier in configs) and multiply r by eta. Consumed budget accounts for resumption: each survivor spends r - r_anterior per round. Return (mejor_config, presupuesto_consumido).def successive_halving(configs, train_fn, budget_min, eta):
"""Devuelve (mejor configuración, presupuesto consumido)."""
vivas, r, previo, gastado = list(configs), budget_min, 0, 0
# tu código: rondas de evaluar, contar el coste, quedarse con las mejores y multiplicar r
return vivas[0], gastadoSummary
- The search space is a hyperparameter tree with types, domains, scales and conditions. Rates and regularization use log-uniform scale: linear sampling puts 90% of samples in the last decade.
- Random search hits a region of probability with probability , independent of dimension, and with low effective dimensionality tests relevant-hyperparameter values where a grid tests .
- Successive halving allocates budget in equally costly rounds and discards the worst fraction; Jamieson and Talwalkar prove it pays the sum, not times the maximum, of costs to distinguish each configuration from the best. Slow-start curves are its risk.
- Hyperband runs successive halving at several minimum budgets (brackets) and, without knowing the best, pays at most about times its budget; here the most aggressive bracket won because the first epoch already ranked well, and Hyperband landed among intermediate brackets.
- Optuna’s TPE and median pruning learn from earlier trials and stop poor ones along the way; Bayesian optimization theory comes later.
- Best validation among trials is optimistic by an amount growing like and decreasing like , less when configurations are more similar. Report nested CV or untouched test.