Hyperparameter Search and Nested Cross-Validation › Formula

Michael BrenndoerferOctober 25, 202626 min read
Machine Learning from ScratchAll chapters
Part 4 of 15Model Evaluation and Selection
Chapter 33Hyperparameter Search and Nested Cross-Validation › Formula
Reading section 4 of 10 · Formula · 26 minSection 4 of 10 · 26 min

Section 4 of 10 · 26 min read

Hyperparameter Search and Nested Cross-Validation › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Notes & comments

It helps to view hyperparameter search as a second learning problem wrapped around the first. The inner problem fits model parameters for a fixed hyperparameter setting. The outer problem compares those settings using held-out data. The formulas below make both layers explicit, because the distinction between them is exactly what nested cross-validation is designed to protect.

Let the training data be

D={(xi,yi)}i=1n,D=\{(x_i,y_i)\}_{i=1}^{n},

where xix_i is a feature vector and yiy_i is a target. A learning algorithm AA takes a training set and a hyperparameter vector λ\lambda and returns a fitted model fλf_\lambda. The hyperparameters live in a search space Λ\Lambda, where:

  • λ\lambda: a hyperparameter vector, an element of the search space
  • Λ\Lambda: the search space, the set of all allowed hyperparameter values
  • AA: the learning algorithm that maps a training set and λ\lambda to a fitted model
  • fλf_\lambda: the fitted model returned by AA for hyperparameters λ\lambda

In a polynomial ridge pipeline, for example,

λ=(d,α),\lambda=(d,\alpha),

where:

  • dd: the polynomial degree (a discrete hyperparameter)
  • α\alpha: the ridge penalty strength (a continuous hyperparameter)

The degree controls the feature map

ϕd(x)=(x,x2,…,xd),\phi_d(x)=(x,x^2,\ldots,x^d),

where:

  • ϕd(x)\phi_d(x): the polynomial feature map that sends a scalar input xx to a vector of its powers up to degree dd
  • dd: the polynomial degree, the highest power included in the feature map
  • xx: a scalar input feature value

Note that ϕd(x)\phi_d(x) is a dd-dimensional vector for scalar input xx, with components x,x2,…,xdx, x^2, \ldots, x^d, so the coefficient vector β\beta also has length dd, ensuring the inner product is well defined:

ϕd(xi)⊤β=∑p=1dβpxip\phi_d(x_i)^\top\beta = \sum_{p=1}^{d} \beta_{p} x_i^{p}

The dot product is a scalar prediction, where:

  • ϕd(xi)\phi_d(x_i): the dd-dimensional polynomial feature vector for observation ii, with components xi,xi2,…,xidx_i, x_i^2, \ldots, x_i^d
  • β\beta: the coefficient vector of length dd that weights each power
  • βp\beta_p: the coefficient associated with the pp-th power of the input
  • xix_i: the feature value for observation ii (a scalar in this univariate polynomial case)
  • dd: the polynomial degree, the highest power included in the sum

This feature map excludes a constant column. The implementation adds an unpenalized intercept and standardizes each power using training-fold means μp\mu_p and positive scales sps_p. Write the standardized power as zip=(xip−μp)/spz_{ip}=(x_i^p-\mu_p)/s_p and the standardized feature vector as zi=(zi1,…,zid)z_i=(z_{i1},\ldots,z_{id}), where:

  • zipz_{ip}: the standardized version of the pp-th power of input xix_i
  • μp\mu_p: the mean of xpx^p computed on the training fold only
  • sps_p: the positive scale of xpx^p (typically its standard deviation) computed on the training fold only
  • ziz_i: the vector of standardized polynomial features for observation ii

For a constant column, use scale one. Ridge trades residual error against coefficient size on this standardized scale:

(β^0(d,α),β^α)=arg⁡min⁡β0,β(∑i=1n(yi−β0−zi⊤β)2+α∥β∥22),\left(\hat\beta_0(d,\alpha),\hat\beta_\alpha\right)=\arg\min_{\beta_0,\beta}\left(\sum_{i=1}^{n}\left(y_i-\beta_0-z_i^\top\beta\right)^2+\alpha\lVert\beta\rVert_2^2\right),

where:

  • β^0(d,α)\hat\beta_0(d,\alpha): the unpenalized intercept estimate, a function of the degree dd and penalty α\alpha
  • β^α\hat\beta_\alpha: the fitted (penalized) coefficient vector at penalty strength α\alpha; it implicitly depends on the standardized feature basis determined by dd
  • β\beta: the coefficient vector being optimized over, of dimension dd (the same length as the standardized feature vector ziz_i)
  • nn: the number of training observations
  • yiy_i: the observed target for observation ii
  • β0\beta_0: the unpenalized intercept, not penalized by the ridge term
  • ziz_i: the polynomial features standardized using only the training observations
  • β0+zi⊤β\beta_0+z_i^\top\beta: the model's predicted value for observation ii
  • α\alpha: the ridge penalty strength (controls the size of the shrinkage)
  • ∥β∥22\lVert\beta\rVert_2^2: the squared L2 norm of the coefficients, ∑p=1dβp2\sum_{p=1}^{d}\beta_{p}^2

We will study linear regression and polynomial regression in detail later; for now, the important point is that dd changes the model family and α\alpha changes the fitting objective, but neither is learned by the inner least-squares step. Changing λ\lambda changes the model family or the fitting rule. Note that the ridge objective above shows the unpenalized intercept β0\beta_0 alongside the penalized coefficients, so the prediction used in the loss includes both.

The quantity we would like to know is the generalization risk

R(λ∣D)=E(X,Y)∼P[L(Y, A(D;λ)(X))],R(\lambda\mid D)=\mathbb{E}_{(X,Y)\sim P}\left[L\left(Y,\,A(D;\lambda)(X)\right)\right],

where:

  • R(λ∣D)R(\lambda\mid D): the expected loss of the particular model fitted on DD with setting λ\lambda, where λ\lambda is a hyperparameter vector in the search space Λ\Lambda
  • DD: the training data, held fixed in this conditional risk
  • (X,Y)(X,Y): a new observation drawn from the data-generating distribution
  • PP: the data-generating distribution
  • LL: a loss such as squared error
  • A(D;λ)A(D;\lambda): the fitted model returned by the learning algorithm on training data DD with setting λ\lambda
  • XX: a new input feature vector drawn from the data-generating distribution
  • A(D;λ)(X)A(D;\lambda)(X): the fitted model's prediction at the new input XX

and the squared-error loss is

L(y,y^)=(y−y^)2,L(y,\hat y)=(y-\hat y)^2,

where:

  • L(y,y^)L(y,\hat y): the squared-error loss for a true target yy and prediction y^\hat y
  • yy: the observed target
  • y^\hat y: the model's predicted value

The new observation must be independent of the training data. In this conditional expression, fitting randomness is fixed; the expectation averages over new evaluation observations. A procedure-level risk additionally averages this conditional risk over fresh training samples of a specified size and over any fitting randomness. These are different targets: cross-validation evaluates fits trained on fewer rows than a fit on all nn observations. Below, R(λ)R(\lambda) abbreviates the procedure-level risk at the training size being evaluated, with that size held fixed across candidates. We estimate risk with held-out data, once per candidate.

For KK-fold cross-validation, partition the training indices into folds V1,…,VKV_1,\ldots,V_K. Let D(−k)D^{(-k)} be the data with fold VkV_k removed, and let

fλ(−k)=A(D(−k);λ)f_\lambda^{(-k)}=A\left(D^{(-k)};\lambda\right)

be the model fitted without fold kk. The cross-validation estimate averages the loss over all folds and, within each fold, over the held-out observations, so that every observation contributes once to the estimate:

R^CV(λ)=1K∑k=1K1∣Vk∣∑i∈VkL(yi,fλ(−k)(xi))\hat R_{\mathrm{CV}}(\lambda) = \frac{1}{K}\sum_{k=1}^{K} \frac{1}{|V_k|} \sum_{i\in V_k} L\left(y_i,f_\lambda^{(-k)}(x_i)\right)

where:

  • R^CV(λ)\hat R_{\mathrm{CV}}(\lambda): the KK-fold cross-validated estimate of the risk at hyperparameters λ\lambda
  • KK: the number of folds
  • kk: the index of the fold currently held out
  • VkV_k: the index set of observations in fold kk
  • ∣Vk∣|V_k|: the number of observations in fold kk
  • fλ(−k)f_\lambda^{(-k)}: the model fitted on all folds except kk, with hyperparameters λ\lambda
  • LL: the per-observation loss
  • yiy_i: the observed target for observation ii
  • xix_i: the feature vector for observation ii

The inner sum averages loss within held-out fold kk, and the outer sum gives each fold equal weight. If fold sizes differ, this need not equal the pooled per-observation mean loss. The superscript (−k)(-k) is important: the model used to predict observations in VkV_k never saw those observations during fitting. For a fixed λ\lambda, this is a standard validation estimate. The subtlety arises because we will compare many such estimates and keep the smallest one.

Parameters, hyperparameters, and search spaces

Parameters are the numbers that the fitting algorithm optimizes. In a linear model, they are the regression coefficients; in a neural network, they are the weights and biases. Hyperparameters are the numbers or structural choices that control how that optimization is set up. They include the polynomial degree, the ridge penalty, the number of folds in cross-validation, the learning rate of gradient descent, the number of trees in a forest, and the kernel width in a kernel method. The distinction is practical: parameters are estimated by minimizing a training objective, while hyperparameters are chosen by comparing validation performance or by using prior knowledge.

A useful way to keep the distinction straight is to ask what changes when a value changes:

  • A parameter changes during fitting on a fixed training set. The fitting rule itself stays the same.
  • A hyperparameter changes the fitting rule, the model family, or the search protocol. It is fixed while the parameters are optimized.
  • A search space specifies which hyperparameter values are allowed. It is part of the procedure and must be fixed before the final evaluation.

The search space Λ\Lambda can contain discrete values, continuous intervals, categorical choices, or conditional choices. For a polynomial ridge model we might use the degree and the penalty:

d∈{1,2,…,8},α∈[10−3,1],d\in\{1,2,\ldots,8\}, \qquad \alpha\in[10^{-3},1],

where:

  • dd: the polynomial degree (a discrete hyperparameter)
  • α\alpha: the ridge penalty strength (a continuous hyperparameter)

For a positive penalty spanning several orders of magnitude, a logarithmic search allocates resolution to relative changes in α\alpha. Moving from 0.0010.001 to 0.010.01 changes the penalty by a factor of ten, just as moving from 0.10.1 to 11 does. The interval [0,0.01][0,0.01] occupies only 1% of the linear range [0,1][0,1]. A coarse linear grid can therefore miss substantial relative differences among small positive penalties. Search spaces should be chosen before looking at the final test result, and they should be wide enough to include reasonable models but not so wide that the budget is spread too thin.

Grid search and random search under equal budgets

Once the search space is defined, the next question is how to spend the evaluation budget. Grid search evaluates a Cartesian product of candidate values. If the search space has HH hyperparameters and the jj-th hyperparameter has mjm_j candidate values, the grid is

Λgrid={(λ1(a1),…,λH(aH)):a1∈{1,…,m1},…,aH∈{1,…,mH}},\Lambda_{\mathrm{grid}} = \left\{ \left(\lambda_1^{(a_1)},\ldots,\lambda_H^{(a_H)}\right) : a_1\in\{1,\ldots,m_1\},\ldots,a_H\in\{1,\ldots,m_H\} \right\},

where:

  • λj(aj)\lambda_j^{(a_j)}: the aja_j-th candidate value for the jj-th hyperparameter
  • mjm_j: the number of candidate values for the jj-th hyperparameter
  • HH: the number of hyperparameters being tuned
  • aja_j: the index selecting the candidate value along the jj-th hyperparameter dimension

Each element of Λgrid\Lambda_{\mathrm{grid}} is a single combination, chosen by fixing one candidate index aja_j per dimension. The number of candidates is the size of the Cartesian product, obtained by multiplying the number of candidate values along each hyperparameter dimension:

B=∏j=1Hmj,B=\prod_{j=1}^{H} m_j,

where:

  • BB: the total number of grid candidates
  • HH: the number of hyperparameters being tuned
  • mjm_j: the number of candidate values for the jj-th hyperparameter
  • ∏j=1H\prod_{j=1}^{H}: the product over all HH hyperparameters
  • jj: the index identifying the hyperparameter whose candidate count is multiplied

If we tune eight polynomial degrees and four ridge penalties, the budget is 8×4=328\times 4=32 candidate configurations. Each configuration is evaluated on the same inner folds. Grid candidate enumeration is deterministic and exhaustive over the specified grid. Randomness in model fitting or fold construction still needs to be controlled. Its weakness is the product: five hyperparameters with ten values each require 105=100,00010^5=100{,}000 candidates, which is often impractical. The grid also evaluates every combination, including combinations whose differences may be irrelevant to performance.

Random search draws candidates independently from a distribution p(λ)p(\lambda):

λ(b)∼p(λ),b=1,…,B.\lambda^{(b)}\sim p(\lambda), \qquad b=1,\ldots,B.

where:

  • λ(b)\lambda^{(b)}: the bb-th candidate hyperparameter vector drawn by the search
  • p(λ)p(\lambda): the search distribution over the hyperparameter space
  • BB: the total number of candidates (the budget)
  • bb: the index of the candidate draw

We then select

b∗=arg⁡min⁡b∈{1,…,B}R^CV(λ(b)),λ^=λ(b∗).b^*=\arg\min_{b\in\{1,\ldots,B\}}\hat R_{\mathrm{CV}}\left(\lambda^{(b)}\right), \qquad \hat\lambda=\lambda^{(b^*)}.

where:

  • b∗b^*: the selected candidate index, using the first index to break an exact tie
  • λ^\hat\lambda: the selected candidate vector at that index
  • R^CV(λ(b))\hat R_{\mathrm{CV}}\left(\lambda^{(b)}\right): the KK-fold cross-validation estimate of the risk for the bb-th candidate

For the positive ridge penalty in this chapter, we choose a log-uniform distribution because it gives equal probability to equal-width intervals on the logarithmic scale, including each full order of magnitude within its support. Random search does not enumerate combinations. Independent draws often produce many different values along continuous dimensions; discrete values can repeat, and distinctness is not guaranteed. If only one or two hyperparameters strongly affect performance, random search can cover their important ranges much faster than a grid that also varies irrelevant dimensions. It is stochastic, however, so the result depends on the seed, and two runs with the same budget can select different configurations.

An equal-budget comparison must hold the data, inner folds, loss, and number of candidate evaluations fixed. Grid search and random search should not be compared when one method receives more fits or different validation splits. For random search, we should report the seed or repeat the search across several seeds, because the candidate draw is part of the procedure. The fair question is not "which method found a lower score once?" but "how does each complete search procedure behave under the same budget and protocol?"

Selection bias and nested cross-validation

Let ΛB\Lambda_B denote the finite set of evaluated candidates within the larger allowed space Λ\Lambda. After evaluating those candidates, we choose the one with the smallest validation loss:

λ^=arg⁡min⁡λ∈ΛBR^CV(λ).\hat\lambda = \arg\min_{\lambda\in\Lambda_B} \hat R_{\mathrm{CV}}(\lambda).

The reported score of the winner is therefore

R^CV(λ^)=min⁡λ∈ΛBR^CV(λ).\hat R_{\mathrm{CV}}(\hat\lambda) = \min_{\lambda\in\Lambda_B} \hat R_{\mathrm{CV}}(\lambda).

This is a minimum of noisy estimates. Even if all candidates have the same true risk, the one that happens to receive a favorable validation sample will look better than the others. To see the mechanism, write the validation error of candidate λ\lambda as

R^CV(λ)=R(λ)+ελ,\hat R_{\mathrm{CV}}(\lambda) = R(\lambda)+\varepsilon_\lambda,

where:

  • R^CV(λ)\hat R_{\mathrm{CV}}(\lambda): the cross-validated estimate of the risk at hyperparameters λ\lambda
  • R(λ)R(\lambda): the true risk of the model fitted with hyperparameters λ\lambda
  • ελ\varepsilon_\lambda: the estimation error on these particular folds (the gap between the validation estimate and the true risk)

The selected candidate has

R^CV(λ^)=R(λ^)+ελ^,\hat R_{\mathrm{CV}}(\hat\lambda) = R(\hat\lambda)+\varepsilon_{\hat\lambda},

where:

  • R^CV(λ^)\hat R_{\mathrm{CV}}(\hat\lambda): the validation estimate of the selected candidate's risk
  • R(λ^)R(\hat\lambda): the true risk of the selected candidate
  • ελ^\varepsilon_{\hat\lambda}: the estimation error of the selected candidate on these folds, the gap between its validation estimate and its true risk (defined as R^CV(λ)−R(λ)\hat R_{\mathrm{CV}}(\lambda)-R(\lambda) evaluated at λ^\hat\lambda)

Selection favors candidates with favorable estimation errors. Under the unbiased-candidate assumptions stated below, the resulting optimism is nonnegative in expectation; this is not a claim about every realized score. Defining optimism as the expected amount by which the selected model's validation estimate falls below its true risk (equivalently, the expected overstatement of performance), we have

optimism=E[R(λ^)]−E[R^CV(λ^)]=−E[ελ^]\begin{aligned} \mathrm{optimism} &= \mathbb{E}\left[R(\hat\lambda)\right] - \mathbb{E}\left[\hat R_{\mathrm{CV}}(\hat\lambda)\right] \\ &= -\mathbb{E}\left[\varepsilon_{\hat\lambda}\right] \end{aligned}

where:

  • optimism\mathrm{optimism}: the expected overstatement of performance caused by selecting the best candidate
  • λ^\hat\lambda: the selected hyperparameters (a random quantity, depending on the validation folds)
  • R(λ^)R(\hat\lambda): the true risk of the model chosen by the search
  • R^CV(λ^)\hat R_{\mathrm{CV}}(\hat\lambda): the validation estimate of the selected model's risk
  • E[⋅]\mathbb{E}[\cdot]: the expectation over the randomness of the validation folds

For a fixed finite candidate set, suppose each candidate estimate is unbiased for its fixed target risk: E[R^CV(λ)]=R(λ)\mathbb{E}[\hat R_{\mathrm{CV}}(\lambda)]=R(\lambda). The minimum is a concave function of its arguments. Applying Jensen's inequality to this concave function gives E[min⁡λR^CV(λ)]≤min⁡λE[R^CV(λ)]\mathbb{E}[\min_\lambda \hat R_{\mathrm{CV}}(\lambda)]\le\min_\lambda \mathbb{E}[\hat R_{\mathrm{CV}}(\lambda)], and substituting the unbiasedness E[R^CV(λ)]=R(λ)\mathbb{E}[\hat R_{\mathrm{CV}}(\lambda)]=R(\lambda) yields E[min⁡λR^CV(λ)]≤min⁡λR(λ)\mathbb{E}[\min_\lambda\hat R_{\mathrm{CV}}(\lambda)]\le\min_\lambda R(\lambda). Also, over the fixed finite candidate set ΛB\Lambda_B, min⁡λ∈ΛBR(λ)≤R(λ^)\min_{\lambda\in\Lambda_B} R(\lambda)\le R(\hat\lambda) for every realization (since λ^∈ΛB\hat\lambda\in\Lambda_B), so min⁡λ∈ΛBR(λ)≤E[R(λ^)]\min_{\lambda\in\Lambda_B} R(\lambda)\le\mathbb{E}[R(\hat\lambda)]. Combining these gives E[min⁡λ∈ΛBR^CV(λ)]≤E[R(λ^)]\mathbb{E}[\min_{\lambda\in\Lambda_B}\hat R_{\mathrm{CV}}(\lambda)]\le\mathbb{E}[R(\hat\lambda)], so the expected optimism is nonnegative. Independence across candidates is unnecessary for this inequality. Actual CV estimates need not be unbiased for the risk of a model refitted on all data; the training-size difference is another source of discrepancy. The inequality is not a guarantee that a realized outer score exceeds its inner score.

A simple calculation makes the size of the effect concrete. Suppose two candidates have the same true risk, and their validation estimates are independent normal random variables with the same mean R0R_0 and positive standard deviation σ\sigma. The normality and independence assumptions are stated explicitly because the exact value below depends on them; normality is an illustrative model assumption rather than a general property of validation estimates, and shared folds can make candidate estimates correlated. Write the standardized estimates as Z1,Z2∼N(0,1)Z_1, Z_2 \sim \mathcal{N}(0,1), independently. The expected minimum is

E[min⁡(Z1,Z2)]=∫−∞∞z⋅2 φ(z) Φ(−z) dz=−1π≈−0.564\begin{aligned} \mathbb{E}[\min(Z_1, Z_2)] &= \int_{-\infty}^{\infty} z \cdot 2\,\varphi(z)\,\Phi(-z)\, dz \\ &= -\frac{1}{\sqrt{\pi}} \\ &\approx -0.564 \end{aligned}

where:

  • zz: the value at which we evaluate whether one draw is the smaller
  • φ(z)\varphi(z): the standard normal density
  • Φ(z)\Phi(z): the standard normal cumulative distribution function, the probability that a standard normal draw is at most zz; its exceedance probability is 1−Φ(z)=Φ(−z)1-\Phi(z)=\Phi(-z)
  • the factor 2 φ(z) Φ(−z)2\,\varphi(z)\,\Phi(-z): the density that zz is the smaller of the two draws (one draw at zz, the other above it, in either order)

To evaluate the integral, use the identity E[min⁡(Z1,Z2)]=−E∣Z1−Z2∣/2\mathbb{E}[\min(Z_1, Z_2)] = -\mathbb{E}\lvert Z_1 - Z_2\rvert / 2. With W=Z1−Z2∼N(0,2)W = Z_1 - Z_2 \sim \mathcal{N}(0, 2), we have σW=2\sigma_W = \sqrt{2} and E∣W∣=2/π σW\mathbb{E}\lvert W\rvert = \sqrt{2/\pi}\,\sigma_W for W∼N(0,σW2)W \sim \mathcal{N}(0, \sigma_W^2). This follows from the half-normal expectation

E∣W∣=2∫0∞w⋅12πσWe−w2/(2σW2) dw=2π σW(half-normal mean for W∼N(0,σW2))=2π 2(substitute σW=2)=2π.\begin{aligned} \mathbb{E}|W| &= 2\int_0^\infty w \cdot \frac{1}{\sqrt{2\pi}\sigma_W} e^{-w^2/(2\sigma_W^2)} \, dw \\ &= \sqrt{\frac{2}{\pi}}\,\sigma_W && \text{(half-normal mean for } W\sim\mathcal{N}(0,\sigma_W^2)\text{)} \\ &= \sqrt{\frac{2}{\pi}}\,\sqrt{2} && \text{(substitute } \sigma_W=\sqrt{2}\text{)} \\ &= \frac{2}{\sqrt{\pi}}. \end{aligned}

where:

  • ww: the integration variable running over nonnegative values
  • σW\sigma_W: the standard deviation of the zero-mean normal WW (equal to 2\sqrt{2} here, since W=Z1−Z2W = Z_1 - Z_2)
  • e−w2/(2σW2)e^{-w^2/(2\sigma_W^2)}: the Gaussian kernel evaluated at ww, with the normalizing factor 1/(2πσW)1/(\sqrt{2\pi}\sigma_W) outside
  • the factor 22: accounts for the two symmetric halves of the normal density when integrating only over w≥0w \ge 0

Therefore

E[min⁡(Z1,Z2)]=−E∣Z1−Z2∣2=−12⋅2π⋅2=−12⋅2π=−1π.\begin{aligned} \mathbb{E}[\min(Z_1, Z_2)] &= -\frac{\mathbb{E}|Z_1 - Z_2|}{2} \\ &= -\frac{1}{2} \cdot \sqrt{\frac{2}{\pi}} \cdot \sqrt{2} \\ &= -\frac{1}{2} \cdot \frac{2}{\sqrt{\pi}} \\ &= -\frac{1}{\sqrt{\pi}}. \end{aligned}

Rescaling back to the candidates' units, the winner's validation score is about 0.564σ0.564\sigma below the common mean even though neither candidate is better. With more candidates, the minimum is pushed even lower. More precisely, if MM candidates share the same true risk and their validation estimates have standard deviation σ\sigma, the expected minimum score is

R0+σ E[min⁡(Z1,…,ZM)],R_0+\sigma\, \mathbb{E}[\min(Z_1,\ldots,Z_M)],

where:

  • R0R_0: the common true risk shared by all MM candidates
  • MM: the number of candidates sharing that common true risk
  • σ\sigma: the standard deviation of each candidate's validation estimate
  • ZmZ_m: the standardized validation error of candidate mm, defined as Zm=(R^m−R0)/σZ_m=(\hat R_m-R_0)/\sigma, an independent standard normal draw

This expression is obtained by writing each estimate as R^m=R0+σZm\hat R_m = R_0 + \sigma Z_m with Zm=(R^m−R0)/σZ_m=(\hat R_m-R_0)/\sigma standard normal, so the minimum is R0+σmin⁡mZmR_0 + \sigma \min_m Z_m and linearity of expectation gives the expression above. Since E[min⁡(Z1,…,ZM)]<0\mathbb{E}[\min(Z_1,\ldots,Z_M)]<0 for M≥2M\ge 2 under these assumptions, the expected minimum lies below the common risk R0R_0.

This expression decreases as MM grows because the standardized minimum E[min⁡(Z1,…,ZM)]\mathbb{E}[\min(Z_1,\ldots,Z_M)] decreases with MM. This is the same "winner's curse" that can arise when we select the maximum of noisy measurements.

The winner's curse can be quantified without fitting a model. For MM independent candidate estimates with the same true risk, the expected best observed score is R0R_0 plus σ\sigma times the expected minimum of MM standard normal draws. The next cell approximates that expected minimum by numerical integration over [−8,8][-8,8], and the figure plots the negative value as expected selection optimism in standard-deviation units.

PythonIn [3]
CollapseExpand
import numpy as np
from scipy.integrate import quad
from scipy.stats import norm

candidate_counts = np.arange(2, 31)
# Computation of expected minima is intentionally kept outside the plot cell.
expected_minima = np.array(
    [
        quad(
            lambda z, m=m: z * m * norm.pdf(z) * norm.cdf(-z) ** (m - 1),
            -8.0,
            8.0,
            limit=200,
        )[0]
        for m in candidate_counts
    ]
)
selection_optimism = -expected_minima
VisualizationOut [4]
CollapseExpand
Line curve shows expected selection optimism rising with candidate count.
Numerical approximation to expected selection optimism in validation-score standard deviations as the number of equally good candidates increases. The curve shows the negative expected minimum of independent standard normal validation errors, revealing how the best of many noisy candidates appears progressively better than it truly is.

Nested cross-validation addresses this by adding an outer loop. Partition the data into outer folds V1(o),…,VJ(o)V_1^{(o)},\ldots,V_J^{(o)}, and let D(−j)D^{(-j)} denote the data with outer fold Vj(o)V_j^{(o)} removed. For each outer fold jj, run the entire inner search on D(−j)D^{(-j)} and obtain

λ^j=arg⁡min⁡λ∈ΛBR^CV(j)(λ),\hat\lambda_j = \arg\min_{\lambda\in\Lambda_B} \hat R_{\mathrm{CV}}^{(j)}(\lambda),

where:

  • λ^j\hat\lambda_j: the hyperparameters selected by the inner search when outer fold jj is held out
  • R^CV(j)(λ)\hat R_{\mathrm{CV}}^{(j)}(\lambda): the KK-fold inner cross-validation estimate of candidate λ\lambda computed only on D(−j)D^{(-j)}

For random search, ΛB\Lambda_B here means the candidates drawn for this outer training run. Candidate generation must also exclude the outer test targets.

Then fit the selected model on the outer training set,

fj=A(D(−j);λ^j),f_j=A\left(D^{(-j)};\hat\lambda_j\right),

and evaluate it on the outer test fold. The nested estimate averages the outer-fold losses, each computed with the model whose hyperparameters were selected by that fold's inner search:

R^nested=1J∑j=1J1∣Vj(o)∣∑i∈Vj(o)L(yi,fj(xi))\hat R_{\mathrm{nested}} = \frac{1}{J}\sum_{j=1}^{J} \frac{1}{|V_j^{(o)}|} \sum_{i\in V_j^{(o)}} L\left(y_i,f_j(x_i)\right)

where:

  • R^nested\hat R_{\mathrm{nested}}: the nested cross-validation estimate of the procedure's risk
  • JJ: the number of outer folds
  • D(−j)D^{(-j)}: the data with outer fold jj removed, used to run the inner search and select λ^j\hat\lambda_j
  • Vj(o)V_j^{(o)}: the index set of observations in outer fold jj
  • ∣Vj(o)∣|V_j^{(o)}|: the number of observations in outer fold jj
  • fjf_j: the model refitted on the outer training set using the selected hyperparameters λ^j\hat\lambda_j
  • LL: the per-observation loss
  • yiy_i: the observed target for observation ii
  • xix_i: the feature vector for observation ii
  • ii: the index running over observations within an outer test fold
  • jj: the index of the outer fold

The outer test fold was not used to choose λ^j\hat\lambda_j, so it gives a cleaner view of how the selection procedure performs on unseen data. Notice that λ^j\hat\lambda_j can differ from fold to fold. The nested estimator is not the cross-validation score of one fixed model; it is an estimate of the risk of the complete procedure that takes a training set, runs a search, and returns a fitted model. With independent identically distributed observations and a procedure fixed before inspecting outer results, outer held-out losses evaluate that procedure at the outer-training sample size, approximately (1−1/J)n(1-1/J)n. They do not directly estimate the conditional risk of the final model refitted on all nn rows. Finite data and overlapping outer training sets still create variability. To see why the distinction matters, note that R^nested\hat R_{\mathrm{nested}} averages over outer folds each of which selected its own λ^j\hat\lambda_j; keeping each outer test fold out of its entire selection process is what avoids reusing its scores for selection, but it also means the nested score is not the score of any single deployable model.

Refitting, final testing, and reporting variability

After nested cross-validation, we usually want a final model for deployment. The standard recipe is to run the search on all available development data, obtain λ^\hat\lambda, and refit

f^=A(D;λ^).\hat f=A(D;\hat\lambda).

The nested estimate describes the procedure; the final model is the procedure applied to all development data. If an untouched test set exists, we evaluate f^\hat f on it once. That test score is often the cleanest estimate of final performance, and in that situation nested cross-validation is not mandatory. Nested cross-validation is the appropriate tool when we need to estimate the procedure using the same data that were available for development, or when we want to compare several complete procedures under a common protocol.

Reporting should include the search method, the search space, the budget, the inner and outer fold counts, the metric, the random seeds, and the selected hyperparameters across outer folds. A single number hides too much. It is useful to report the mean outer score, the standard deviation across outer folds, and a standard error across repeated nested runs. If we repeat the entire nested procedure M≥2M\ge2 times with different outer splits, we can summarize the repetition-level scores with a mean and an estimated standard error. The mean of the per-repetition nested estimates is

Rˉ=1M∑m=1MR^m,\bar R=\frac{1}{M}\sum_{m=1}^{M}\hat R_m,

and the estimated standard error of that mean is

SE^(Rˉ)=1M1M−1∑m=1M(R^m−Rˉ)2\widehat{\mathrm{SE}}(\bar R) = \frac{1}{\sqrt{M}} \sqrt{\frac{1}{M-1} \sum_{m=1}^{M} \left(\hat R_m-\bar R\right)^2}

where:

  • MM: the number of repeated nested runs (each with a fresh outer split)
  • mm: the index of the repetition
  • R^m\hat R_m: the nested estimate produced by the mm-th repetition
  • Rˉ\bar R: the mean nested estimate across repetitions
  • SE^(Rˉ)\widehat{\mathrm{SE}}(\bar R): the estimated standard error of Rˉ\bar R across repetitions
  • (R^m−Rˉ)2\left(\hat R_m-\bar R\right)^2: the squared deviation of repetition mm's estimate from the mean
  • 1M−1∑m=1M(R^m−Rˉ)2\sqrt{\frac{1}{M-1}\sum_{m=1}^{M}\left(\hat R_m-\bar R\right)^2}: the sample standard deviation of the repetition-level scores

The formula is the sample standard deviation of the repetition-level scores divided by M\sqrt{M}: the inner square root is the sample standard deviation across repetitions, and dividing by M\sqrt{M} converts that spread into a standard error for their mean.

With independently drawn partition and search seeds, this is a Monte Carlo standard error for the mean over that randomization, conditional on this fixed dataset. It can decrease as we add repetitions without adding observations. The repetition-level standard deviation describes split/search variability; neither quantity measures how results vary over new datasets or supplies a population-risk confidence interval. If the selected degree or penalty changes drastically from fold to fold, the procedure is unstable, and a simpler model or more data may be preferable.

Mathematical properties

Grid and random search treat validation loss as a black-box objective and do not use derivatives. A discrete degree cannot be updated by an ordinary continuous gradient. Some continuous hyperparameters, including ridge penalties, admit differentiable optimization under suitable conditions, but that is a different method from the searches implemented here. A validation surface need not be convex, and finite-data noise can affect which candidate wins.

Random search has a simple coverage property. The following formula makes the probability of covering the good region explicit for an independent-draw search. Suppose the good region has probability mass qq under the chosen search distribution. Each independent draw then has probability qq of producing an acceptable candidate; the value of qq is simply the probability mass the search distribution assigns to the good region, and a uniform distribution over the search region makes it equal to the good region's volume (or length) divided by the total volume (or length). The probability that BB independent draws contain at least one good candidate is

P(at least one hit)=1−(1−q)B,P(\text{at least one hit})=1-(1-q)^B,

where:

  • P(at least one hit)P(\text{at least one hit}): the probability that at least one of the BB candidates falls in the good region
  • qq: the per-draw probability of an acceptable candidate under the search distribution
  • BB: the number of independent candidate draws
  • (1−q)B(1-q)^B: the probability that all BB independent draws miss the good region, since each draw misses with probability 1−q1-q and draws are independent

For a target hit probability pp with 0<p<10<p<1 and per-draw hit probability qq with 0<q<10<q<1, the smallest integer budget giving hit probability at least pp is

Bmin⁡=⌈log⁡(1−p)log⁡(1−q)⌉,B_{\min}=\left\lceil\frac{\log(1-p)}{\log(1-q)}\right\rceil,

where:

  • Bmin⁡B_{\min}: the smallest integer number of independent draws needed to reach hit probability at least pp, obtained by rounding the real-valued lower bound up to the next integer
  • pp: the target lower bound on the probability of at least one hit (with 0<p<10<p<1)
  • qq: the probability mass of the good region under the search distribution (with 0<q<10<q<1)
  • ⌈⋅⌉\lceil\cdot\rceil: the ceiling function, which rounds its argument up to the smallest integer greater than or equal to it

To derive the budget bound, start from the requirement that the hit probability reach pp and rearrange the steps one at a time:

1−(1−q)B≥p(require hit probability at least p)(1−q)B≤1−p(rearrange)Blog⁡(1−q)≤log⁡(1−p)(take natural log of both sides; log⁡ is increasing)B≥log⁡(1−p)log⁡(1−q)(divide by log⁡(1−q)<0, reversing the inequality)\begin{aligned} 1-(1-q)^B &\ge p && \text{(require hit probability at least } p \text{)} \\ (1-q)^B &\le 1-p && \text{(rearrange)} \\ B\log(1-q) &\le \log(1-p) && \text{(take natural log of both sides; } \log \text{ is increasing)} \\ B &\ge \dfrac{\log(1-p)}{\log(1-q)} && \text{(divide by } \log(1-q)<0 \text{, reversing the inequality)} \end{aligned}

Because 1−q∈(0,1)1-q\in(0,1), we have log⁡(1−q)<0\log(1-q)<0, so the division used in the last step reverses the inequality direction. Because 1−p∈(0,1)1-p\in(0,1) as well, log⁡(1−p)<0\log(1-p)<0, and the ratio of two negative quantities is positive, so the lower bound on BB is a positive number. The ceiling rounds the real-valued lower bound upward. The limiting cases confirm the bound: if q=0q=0, no finite positive budget can hit; if q=1q=1, one draw already suffices since 1−(1−q)B=1≥p1-(1-q)^B=1\ge p for any B≥1B\ge 1. This formula explains why random search can be effective when the good region is not too small. It also shows the limits: if qq is tiny, the required budget becomes enormous.

The coverage formula can be read as a budget-planning curve. The next cells evaluate 1−(1−q)B1-(1-q)^B over a range of budgets for three per-draw hit probabilities, then plot the resulting hit probabilities.

PythonIn [5]
CollapseExpand
import numpy as np

coverage_budgets = np.arange(0, 201)
coverage_qs = [0.01, 0.02, 0.05]
coverage_curves = {q: 1.0 - (1.0 - q) ** coverage_budgets for q in coverage_qs}
VisualizationOut [6]
CollapseExpand
Three curves show hit probability rising with search budget for different q values.
Probability of at least one acceptable random-search draw as the budget grows for three per-draw hit probabilities. Each curve follows 1-(1-q)^B, showing that smaller good-region probabilities require substantially larger budgets before a hit becomes likely.

Each outer fold performs BB candidates times KinnerK_{\mathrm{inner}} inner fits, plus one refit on the outer training set, giving

Nfits=J(BKinner+1)(total fits including one refit per outer fold)C≈Nfits Tfit(approximate total cost)=J(BKinner+1) Tfit(substitute Nfits)\begin{aligned} N_{\mathrm{fits}} &= J\left(BK_{\mathrm{inner}}+1\right) && \text{(total fits including one refit per outer fold)} \\ C &\approx N_{\mathrm{fits}}\,T_{\mathrm{fit}} && \text{(approximate total cost)} \\ &= J\left(BK_{\mathrm{inner}}+1\right)\,T_{\mathrm{fit}} && \text{(substitute } N_{\mathrm{fits}}\text{)} \end{aligned}

where:

  • NfitsN_{\mathrm{fits}}: the number of fits for nested assessment, including one outer refit per fold, given by J(BKinner+1)J(BK_{\mathrm{inner}}+1)
  • CC: the approximate fitting cost of the nested procedure, C≈NfitsTfitC\approx N_{\mathrm{fits}}T_{\mathrm{fit}}
  • JJ: the number of outer folds
  • BB: the number of candidate configurations searched per outer fold
  • KinnerK_{\mathrm{inner}}: the number of inner folds used to score each candidate
  • TfitT_{\mathrm{fit}}: the average time to fit one model
  • (BKinner+1)\left(BK_{\mathrm{inner}}+1\right): the per-outer-fold fit count, namely BB candidates times KinnerK_{\mathrm{inner}} inner fits plus one refit

The JBKinnerJBK_{\mathrm{inner}} search fits and JJ outer refits make up this count. A final search and refit on all development data add BKinner+1BK_{\mathrm{inner}}+1 fits. With J=5J=5, B=32B=32 and Kinner=4K_{\mathrm{inner}}=4, nested assessment uses 645645 fits per repetition and a final search/refit adds 129129. Different candidates can have different fit times, so equal fit counts need not mean equal wall-clock time. Whether this cost is practical depends on the candidate budget, fold counts, per-fit cost, available compute, and the value of assessing the complete selection procedure. Parallelizing over candidates or folds can reduce wall-clock time, but it does not reduce the total number of fits.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy