Module contents
Lesson 9 of 24Core 85 min

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: α\alpha for ridge and lasso, CC 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 Aλ\mathcal{A}_\lambda be a training algorithm with hyperparameters λ∈Λ\lambda \in \Lambda: it receives data and returns a predictor f^λ=Aλ(Dtr)\hat f_\lambda = \mathcal{A}_\lambda(\Data_{\text{tr}}). You want to minimize risk, R(λ)=E[ℓ(f^λ(X),Y)]R(\lambda) = \E[\ell(\hat f_\lambda(X), Y)], and can measure an estimate R^(λ)\hat R(\lambda) on validation data or with cross-validation. The problem is

λ⋆=arg min⁡λ∈ΛR(λ),observando solo R^(λ)=R(λ)+ε(λ).\lambda^\star = \argmin_{\lambda \in \Lambda} R(\lambda), \qquad \text{observando solo } \hat R(\lambda) = R(\lambda) + \varepsilon(\lambda).

Three properties distinguish this from optimization in earlier modules:

  • Black box. There is generally no usable gradient of R^\hat R with respect to λ\lambda: many hyperparameters are discrete or categorical (loss, regularization type), and for continuous ones differentiating through all training is expensive and fragile.
  • Noise. ε(λ)\varepsilon(\lambda) has two sources: finite validation sampling (with nvaln_{\text{val}} examples, 0-1 error has standard deviation e(1−e)/nval\sqrt{e(1 - e)/n_{\text{val}}}, about 1.4 points for e=0.09e = 0.09 and nval=400n_{\text{val}} = 400) 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 α\alpha or learning rate η0\eta_0 acts multiplicatively. In ridge, principal direction jj shrinks by factor dj2/(dj2+α)d_j^2 / (d_j^2 + \alpha), where djd_j is a singular value of X\mat{X}: moving from α=10−3\alpha = 10^{-3} to 10−210^{-2} has the same relative effect as moving from 1 to 10, because what matters is α\alpha relative to dj2d_j^2, distributed across orders of magnitude. In gradient descent, a stable step is bounded by 2/L2/L with LL the gradient’s Lipschitz constant, another scale known only by order of magnitude. Naturally, sample the exponent uniformly:

log⁡λ∼Unif⁡(log⁡a,log⁡b)⟺p(λ)=1λlog⁡(b/a),a≤λ≤b.\log \lambda \sim \Unif(\log a, \log b) \quad\Longleftrightarrow\quad p(\lambda) = \frac{1}{\lambda \log(b/a)}, \quad a \le \lambda \le b.

With that density, each decade [10k,10k+1][10^k, 10^{k+1}] within [a,b][a, b] receives the same probability, log⁡10/log⁡(b/a)\log 10 / \log(b/a). By contrast, Unif⁡(a,b)\Unif(a, b) on the original scale gives that decade a fraction 9⋅10k/(b−a)9 \cdot 10^{k} / (b - a) of the mass, proportional to its length: ten times the preceding decade, with the last receiving almost all if a≪ba \ll b. The next cell implements a sampler with scales and conditions and checks this.

[ ]Search space with scales and conditionsBrowser
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 α∈[10−6,10−1]\alpha \in [10^{-6}, 10^{-1}], 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 10−510^{-5}, 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.

The grid has two apparent virtues, exhaustiveness and reproducibility, and one drawback dominating both: its cost is exponential in dd. Random search has a user-chosen cost and a guarantee independent of dimension.

Proof

Events {λ(i)∉G}\{\lambda^{(i)} \notin G\} are independent and each has probability 1−v1 - v, so the probability all fail is (1−v)N(1 - v)^N. The condition 1−(1−v)N≥p1 - (1 - v)^N \ge p is equivalent to (1−v)N≤1−p(1 - v)^N \le 1 - p; taking logs gives Nlog⁡(1−v)≤log⁡(1−p)N\log(1 - v) \le \log(1 - p), and since log⁡(1−v)<0\log(1 - v) < 0, dividing reverses the inequality.

∎

Notably, dimension does not appear in the formula. Bergstra and Bengio use exactly this expression, 1−(1−v)T1 - (1 - v)^T, as expected random-search performance in their 2012 study. Dimension does control vv: if the good region is a cube of side 1/21/2 along each of dd axes, v=2−dv = 2^{-d}. 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 R(λ)R(\lambda) functions have low effective dimensionality: R(λ1,…,λd)≈g(λJ)R(\lambda_1, \dots, \lambda_d) \approx g(\lambda_J) for a small hyperparameter subset JJ, with JJ changing across datasets. Their figure 1 summarizes this using nine evaluations of f(x,y)=g(x)+h(y)≈g(x)f(x, y) = g(x) + h(y) \approx g(x): a 3×33 \times 3 grid tests gg at only three distinct points; random search at nine.

Proof

(1) The kdk^d combinations take only kk first-coordinate values; the grid point nearest any uu is at most half a step away, 12(k−1)\tfrac{1}{2(k-1)}. (2) First coordinates are NN independent uniforms, and two coincide with probability 0. Event DN>tD_N > t means none falls in (u⋆−t,u⋆+t)(u^\star - t, u^\star + t), length 2t2t if inside [0,1][0, 1]; by independence its probability is (1−2t)N(1 - 2t)^N. Integrating the tail, E[DN]=∫0∞P(DN>t) ⁣dt≈∫01/2(1−2t)N ⁣dt=12(N+1)\E[D_N] = \int_0^\infty \Pr(D_N > t)\dd t \approx \int_0^{1/2}(1 - 2t)^N \dd t = \tfrac{1}{2(N + 1)}, where the approximation ignores the nearest edge, which matters only if u⋆u^\star is within a few times 1/N1/N of it. This is the expected minimum order statistic of NN distances.

∎

With nine evaluations in two dimensions, the grid leaves u⋆u^\star at mean distance 14(k−1)=0.125\tfrac{1}{4(k-1)} = 0.125 (if u⋆u^\star is uniform) and random search at about 120=0.05\tfrac{1}{20} = 0.05. With 25 evaluations, 0.0625 versus 0.019. The advantage grows with dimension: a 35=2433^5 = 243-point grid over five hyperparameters still tests only three values of the relevant one; 243 random samples test 243.

InteractiveGrid versus random
Validation cross-entropy (darker blue is better)
Projection onto η0\eta_0: the best loss in each column and the values tested by each design
  • grid (3 x 3)
  • random (9 points)
  • best loss in each column
Surface
Evaluations
Optimum over all 576 cells0.2208
Values of η0\eta_0: grid / random3 / 8
Best grid result0.2518
Best in this random sample0.2302
Mean of 2000 random samples0.2298
Excess: grid / random mean0.0310 / 0.0090
The 9-point grid tests only 3 values of η0\eta_0, the only one that matters: each column repeats nearly the same loss 3 times. Random search tests 7.7 distinct values on average and its mean best result, 0.2298, improves on the grid result, 0.2518.
The map is a real surface: validation cross-entropy of 576 SGD configurations (logistic loss) after 9 epochs, calculated in the cell below; almost all variation depends on learning rate η0\eta_0, the horizontal axis. Squares are the grid and circles random search with the same evaluation count; rings mark each design's best point. Below is the projection onto η0\eta_0: short marks are values tried by each design. Request several random samples, change the evaluation count and switch to the surface where both axes matter equally: does random search still win?

The figure’s surface comes from a real experiment. We train linear classifiers with SGD on a small problem: deciding whether an 8×88\times 8-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 MM 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.

[ ]Data and vectorized trainerBrowser
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)
[ ]Grid versus random on a real surfaceBrowser
# 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: η0\eta_0 explains 99.7% of validation cross-entropy variance and α\alpha 0.1%. With 9 evaluations, the grid tests 3 η0\eta_0 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.

[ ]Learning curves of 729 configurationsBrowser
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 rr epochs and final ranking is 0.645 at r=1r = 1, 0.844 at r=3r = 3 and 0.893 at r=9r = 9: 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 η=2\eta = 2, the case analyzed by Karnin, Koren and Somekh (2013) for stochastic bandits. Cost accounting makes it attractive. Without resuming, round kk costs nkrk=nηk rmin⁡ηk=n rmin⁡n_k r_k = \tfrac{n}{\eta^k}\, r_{\min}\eta^k = n\, r_{\min}: all rounds cost the same, totaling (s+1) n rmin⁡(s+1)\,n\,r_{\min}. Training all nn configurations to R=rmin⁡ηsR = r_{\min}\eta^s costs n rmin⁡ ηsn\,r_{\min}\,\eta^s. The ratio is (s+1)/ηs(s + 1)/\eta^s: with n=81n = 81, η=3\eta = 3 and rmin⁡=1r_{\min} = 1, 405 epochs versus 6561, sixteen times less. Resuming costs even less because each survivor trains only its remaining epochs.

[ ]Successive halving from scratchBrowser
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, η=3\eta = 3 and rmin⁡=1r_{\min} = 1, rounds are 27→9→3→127 \to 9 \to 3 \to 1 at 1,3,9,271, 3, 9, 27 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 rmin⁡=3r_{\min} = 3 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 η0≈0.0045\eta_0 \approx 0.0045, 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 (≈1.4\approx 1.4 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 ii is a bandit arm; pulling it means training one more unit, and its validation-loss sequence ℓi,1,ℓi,2,…\ell_{i,1}, \ell_{i,2}, \dots is not random and independent as in classical bandits, but an arbitrary learning curve. The only assumption is convergence: νi=lim⁡t→∞ℓi,t\nu_i = \lim_{t\to\infty}\ell_{i,t} exists. Define the envelope γi(t)\gamma_i(t) as the smallest nonincreasing function satisfying ∣ℓi,t−νi∣≤γi(t)\abs{\ell_{i,t} - \nu_i} \le \gamma_i(t) for all tt, and its inverse γi−1(α)=min⁡{t:γi(t)≤α}\gamma_i^{-1}(\alpha) = \min\{t : \gamma_i(t) \le \alpha\} as the number of pulls needed to bring the curve within α\alpha of its limit. Order arms so ν1<ν2≤⋯≤νn\nu_1 < \nu_2 \le \cdots \le \nu_n and let γˉ=max⁡iγi\bar\gamma = \max_i \gamma_i. 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 zSHz_{\text{SH}} by 2⌈log⁡2n⌉(n+∑i≥2γˉ−1(νi−ν12))2\lceil\log_2 n\rceil\big(n + \sum_{i\ge 2}\bar\gamma^{-1}(\tfrac{\nu_i - \nu_1}{2})\big): successive halving pays, up to a logarithmic factor, the sum of costs of distinguishing each arm from the best, while uniform allocation pays nn 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 nn times the maximum. The price is dependence on envelopes: if a curve takes long to approach its limit (slowly decreasing γi\gamma_i), the theorem requires a large budget, and with fixed budget and small rmin⁡r_{\min} you may eliminate it.

InteractiveThe successive-halving race
Validation error of 27 real configurations; the cutoffs are the rounds
round 4: 1 at 27 ep.
  • alive
  • eliminated
  • best at 27 epochs
  • chosen
  • full curve
Curves
Algorithm
Race (27 configurations)
η\eta (keeps 1 in every η\eta)
Minimum budget rmin⁡r_{\min} (epochs)
Round4 of 4: 1 alive at 27 epochs
Cost in epochs (training all: 729)81
Chosen: error at 27 epochs0.0975
Best at 27 epochs0.0925
Test (397) for chosen / best0.0756 / 0.1008
The best at 27 epochs (orange) is eliminated in round 1, after 1 epochs, ranked 25 of 27: it started slowly. Successive halving chooses another, with 0.0975 at 27 epochs versus 0.0925.
Each curve is one configuration's validation error versus epochs (logarithmic scale). Press play: in each round the vertical dashed line marks budget rkr_k, configurations outside the top fraction 1/η1/\eta are eliminated (gray cross), and survivors continue. The orange curve is best at 27 epochs and faint dashed curves are what the algorithm cannot see. With real curves compare the three races and minimum budgets. In the slow-start model (described below), a curve's speed says nothing about its final value: request several samples and see how often orange is eliminated. In Hyperband compare all four brackets, each with its own configurations.

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 rmin⁡r_{\min}. In the first it always falls, even with rmin⁡=9r_{\min} = 9, because after 9 epochs it is tenth of 27 and only nine advance. In the third it falls with rmin⁡=1r_{\min} = 1 and 33 and wins with 99. The slow-start model is explicit: configuration ii has error ei(r)=νi+(0.5−νi) e−r/τie_i(r) = \nu_i + (0.5 - \nu_i)\,e^{-r/\tau_i} plus normal noise with standard deviation 0.006 at each evaluation, with final value νi∼Unif⁡(0.06,0.20)\nu_i \sim \Unif(0.06, 0.20) and time constant τi\tau_i log-uniform on [0.3,8][0.3, 8] epochs, independently. Since speed says nothing about final quality, a good slow configuration trails early, and orange often dies with rmin⁡=1r_{\min} = 1. Raising rmin⁡r_{\min} saves it more often but makes each round three times as expensive. No rmin⁡r_{\min} 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 BB requires choosing nn: 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 s=smax⁡s = s_{\max} is most aggressive (most configurations, minimum budget Rη−smax⁡R\eta^{-s_{\max}}, one unit if RR is a power of η\eta), and s=0s = 0 is random search: n=smax⁡+1n = s_{\max} + 1 configurations trained to RR. Without resuming, each bracket spends at most about BB units, and the total is on the order of (smax⁡+1)B(s_{\max} + 1)B. Hyperband thus searches geometrically over average budget per configuration, at roughly smax⁡+1s_{\max} + 1 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.

[ ]Hyperband from scratch and equal-budget comparisonBrowser
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 R=81R = 81 and η=3\eta = 3: five brackets with n=81,34,15,8,5n = 81, 34, 15, 8, 5 configurations and initial budgets 1,3,9,27,811, 3, 9, 27, 81. The paper’s table 1 shows n=81,27,9,6,5n = 81, 27, 9, 6, 5: endpoints agree, but for s=3,2,1s = 3, 2, 1 it differs from the formula in its own algorithm 1 (⌈5⋅27/4⌉=34\lceil 5\cdot 27/4\rceil = 34, for example). Here we use the formula. In the paper’s example (LeNet on MNIST, R=81R = 81 epochs), the best bracket was intermediate s=3s = 3, 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 R=27R = 27, 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 s=1s = 1, 0.0892 with s=2s = 2, 0.0870 with the most aggressive s=3s = 3, 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 1/η1/\eta 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 R^(λ)\hat R(\lambda) 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 p(y∣λ)p(y \given \lambda), it fits two search-space densities,

ℓ(λ)=p(λ∣R^<y⋆),g(λ)=p(λ∣R^≥y⋆),\ell(\lambda) = p(\lambda \given \hat R < y^\star), \qquad g(\lambda) = p(\lambda \given \hat R \ge y^\star),

where y⋆y^\star 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 ℓ(λ)/g(λ)\ell(\lambda)/g(\lambda) among samples from ℓ\ell (24 by default in Optuna); the authors show this maximizes expected improvement under their model, since expected improvement is proportional to (γ+(1−γ) g(λ)/ℓ(λ))−1\big(\gamma + (1 - \gamma)\,g(\lambda)/\ell(\lambda)\big)^{-1}, with γ\gamma 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 tt 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 rmin⁡=3r_{\min} = 3 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-NN 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 NN configurations have the same risk ee and normally distributed validation errors with equal variance and pairwise correlation ρ\rho: R^j=e+σ(ρ Z0+1−ρ Zj)\hat R_j = e + \sigma(\sqrt{\rho}\,Z_0 + \sqrt{1 - \rho}\,Z_j), with independent standard normals Z0,Z1,…,ZNZ_0, Z_1, \dots, Z_N. Then

E[min⁡jR^j]=e−σ1−ρ  E[max⁡j≤NZj],E[max⁡j≤NZj]≤2log⁡N.\E\Big[\min_j \hat R_j\Big] = e - \sigma\sqrt{1 - \rho}\;\E\Big[\max_{j \le N} Z_j\Big], \qquad \E\Big[\max_{j\le N} Z_j\Big] \le \sqrt{2\log N}.

The common part Z0Z_0 does not affect the winner, only the independent part does. And σ2(1−ρ)\sigma^2(1 - \rho) is directly measurable: half the variance of the difference between two configurations. If two classifiers disagree on a fraction dd of examples and have similar errors, the variance of their validation-error difference is ≈d/nval\approx d / n_{\text{val}}, so

brecha≈d2 nval  E[max⁡j≤NZj].\text{brecha} \approx \sqrt{\frac{d}{2\,n_{\text{val}}}}\;\E\Big[\max_{j \le N} Z_j\Big].

It grows like log⁡N\sqrt{\log N} with trial count and decreases like 1/nval1/\sqrt{n_{\text{val}}} with validation size. The chosen configuration’s test score, in contrast, is unbiased: test did not participate in selection.

[ ]Overfitting validationBrowser
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 nvaln_{\text{val}} validation examples and uses the rest as untouched test. With nval=50n_{\text{val}} = 50, best validation falls from 0.0994 (N=1N = 1) to 0.0884 (N≥30N \ge 30), while the chosen model’s test stays at 0.0985: a 1-point gap corresponding to nothing real. With nval=400n_{\text{val}} = 400 the maximum gap is 0.6 points (0.0920 versus 0.0977).

The normal model predicts the first configurations accurately (0.00340.0034 measured versus 0.00340.0034 predicted for nval=400n_{\text{val}} = 400 and N=3N = 3), but beyond N≈10N \approx 10 it greatly exceeds measurements: it predicts 3.1 points for nval=50n_{\text{val}} = 50 and N=200N = 200, 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.

InteractiveOverfitting validation
Mean of 150 searches with randomly drawn validation and test splits · calculating…
mean true error 0.0982
  • best validation error
  • test of the chosen configuration
  • mean true error
  • equicorrelated normal prediction
Configurations
100
100
Best validation with N=100N = 100…
Untouched test for the chosen configuration…
Test minus validation gap…
Predicted gap for equicorrelated normals2.00 points
Mean disagreement dd between two configurations0.0127
Distinct classifiers34 of 200
Examples where they disagree26 of 797
The 200 configurations produce only 34 distinct classifiers and disagree on 26 examples: the maximum plateaus early because there are not many independent bets. The chosen model’s test stays at the mean true error, 0.0982: the search gains nothing and validation promises what is not there.
Real data from the preceding cell: successes and failures of 200 configurations on 797 held-out examples. Each point averages 150 searches with randomly split validation and test: orange is the best validation score among NN configurations tried; blue is the chosen one's test error; the black line is mean true error. Change NN and validation size. Then switch to “Independent errors,” a model with the same per-configuration error rate but independent failures: the extreme approached by truly different configurations, such as a broad space of flexible models.

With independent errors the gap keeps growing with NN 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 η\eta and min_resources is rmin⁡r_{\min}. 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.

[ ]HalvingRandomSearchCV inside nested CVBrowser
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.

[ ]Best-value versus budget curves and nested CV with OptunaLocal GPU
# 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})")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 −0.0105±0.0045-0.0105 \pm 0.0045). 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, +0.0062±0.0024+0.0062 \pm 0.0024 and +0.0101±0.0023+0.0101 \pm 0.0023 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

ModelHyperparameterStarting range and scale
Ridge, lasso (standardized features)α\alphalog-uniform; for lasso, 10−3αmax⁡10^{-3}\alpha_{\max} to αmax⁡=∥X⊤y∥∞/n\alpha_{\max} = \norm{\mat{X}\T\vb{y}}_\infty / n, as in the regularization path
Logistic regressionC=1/αC = 1/\alphalog-uniform on [10−4,104][10^{-4}, 10^{4}]; penalty and l1_ratio as conditional branches
Linear SGDα\alpha, η0\eta_0, scheduleα\alpha log-uniform on [10−6,10−1][10^{-6}, 10^{-1}], η0\eta_0 log-uniform on [10−4,1][10^{-4}, 1], power_t only with invscaling
RBF kernel SVMCC, γ\gammalogarithmic scale: LIBSVM guide (Hsu, Chang and Lin) recommends C∈{2−5,2−3,…,215}C \in \{2^{-5}, 2^{-3}, \dots, 2^{15}\} and γ∈{2−15,2−13,…,23}\gamma \in \{2^{-15}, 2^{-13}, \dots, 2^{3}\} as a first coarse grid
Any epoch-trained modelnumber of epochsas 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

NumericHow many random configurations?
The good region occupies 5% of the search space under its sampling distribution. What minimum number of independent random configurations gives at least 95% probability that one falls in it?
QuizWhat a grid tests
You run a 5 × 5 grid over two hyperparameters and only the first affects the result. How many distinct values of the first did you test?
QuizWhy logarithmic scale?
Why are learning rate and regularization strength usually sampled on a logarithmic scale?
NumericCost of a race
Successive halving uses n=81n = 81 configurations, η=3\eta = 3 and rmin⁡=1r_{\min} = 1 epoch, resuming survivors (each trains only remaining epochs). How many epochs does it cost in total?
NumericThe most aggressive bracket
Hyperband uses R=81R = 81 and η=3\eta = 3. How many configurations start in the most aggressive bracket?
NumericExpected optimism
You test N=100N = 100 configurations with nearly identical true errors on a validation set of nval=200n_{\text{val}} = 200 examples. Any two configurations disagree on 2% of examples on average (d=0.02d = 0.02). Under the equicorrelated normal model, knowing E[max⁡j≤100Zj]=2.508\E[\max_{j\le 100} Z_j] = 2.508 for independent standard normals, how many percentage points of optimism do you expect in the best validation score?
QuizWhich number do you report?
You tune gradient boosting with 300 Optuna trials, each evaluated by 5-fold CV on 2000 development examples. The best trial has mean CV AUC 0.912. You also have 1000 untouched test examples. How do you report expected performance?
QuizWhen early ranking misleads
In 30 complete curves, Spearman correlation between rank after 1 epoch and after 81 is 0.15; between 9 and 81 epochs it is 0.85. You will tune with R = 81 and η = 3. Which strategy is more reasonable?
ProofComparing before convergence
Prove: Let ν1<νi\nu_1 < \nu_i be limits of loss curves ℓ1,t\ell_{1,t} and ℓi,t\ell_{i,t} with nonincreasing envelopes ∣ℓj,t−νj∣≤γj(t)\abs{\ell_{j,t} - \nu_j} \le \gamma_j(t). If γi(ti)<νi−ν12\gamma_i(t_i) < \tfrac{\nu_i - \nu_1}{2} and γ1(t1)<νi−ν12\gamma_1(t_1) < \tfrac{\nu_i - \nu_1}{2}, then ℓi,ti>ℓ1,t1\ell_{i,t_i} > \ell_{1,t_1}.
0
Let Δ=νi−ν1>0\Delta = \nu_i - \nu_1 > 0 and decompose the intermediate-loss difference.

Step 1 of 3. How do you write ℓi,ti−ℓ1,t1\ell_{i,t_i} - \ell_{1,t_1} to use the envelopes?

CodeSuccessive halving
Implement 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], gastado
Shift+Enter to run

Summary

Key idea
Hyperparameter tuning optimizes a noisy, expensive black box: sample on the right scale, prefer random search to grids because usually only a few hyperparameters matter, abandon poor runs early with successive halving or Hyperband if early ranking predicts the end, and above all do not confuse the best validation result with performance you will obtain.
  • 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 vv with probability 1−(1−v)N1 - (1 - v)^N, independent of dimension, and with low effective dimensionality tests NN relevant-hyperparameter values where a grid tests N1/dN^{1/d}.
  • Successive halving allocates budget in equally costly rounds and discards the worst fraction; Jamieson and Talwalkar prove it pays the sum, not nn 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 smax⁡+1s_{\max} + 1 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 NN trials is optimistic by an amount growing like log⁡N\sqrt{\log N} and decreasing like 1/nval1/\sqrt{n_{\text{val}}}, less when configurations are more similar. Report nested CV or untouched test.