Hyperparameter Search and Nested Cross-Validation › Formula
Machine Learning from ScratchAll chapters 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
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
where is a feature vector and is a target. A learning algorithm takes a training set and a hyperparameter vector and returns a fitted model . The hyperparameters live in a search space , where:
- : a hyperparameter vector, an element of the search space
- : the search space, the set of all allowed hyperparameter values
- : the learning algorithm that maps a training set and to a fitted model
- : the fitted model returned by for hyperparameters
In a polynomial ridge pipeline, for example,
where:
- : the polynomial degree (a discrete hyperparameter)
- : the ridge penalty strength (a continuous hyperparameter)
The degree controls the feature map
where:
- : the polynomial feature map that sends a scalar input to a vector of its powers up to degree
- : the polynomial degree, the highest power included in the feature map
- : a scalar input feature value
Note that is a -dimensional vector for scalar input , with components , so the coefficient vector also has length , ensuring the inner product is well defined:
The dot product is a scalar prediction, where:
- : the -dimensional polynomial feature vector for observation , with components
- : the coefficient vector of length that weights each power
- : the coefficient associated with the -th power of the input
- : the feature value for observation (a scalar in this univariate polynomial case)
- : 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 and positive scales . Write the standardized power as and the standardized feature vector as , where:
- : the standardized version of the -th power of input
- : the mean of computed on the training fold only
- : the positive scale of (typically its standard deviation) computed on the training fold only
- : the vector of standardized polynomial features for observation
For a constant column, use scale one. Ridge trades residual error against coefficient size on this standardized scale:
where:
- : the unpenalized intercept estimate, a function of the degree and penalty
- : the fitted (penalized) coefficient vector at penalty strength ; it implicitly depends on the standardized feature basis determined by
- : the coefficient vector being optimized over, of dimension (the same length as the standardized feature vector )
- : the number of training observations
- : the observed target for observation
- : the unpenalized intercept, not penalized by the ridge term
- : the polynomial features standardized using only the training observations
- : the model's predicted value for observation
- : the ridge penalty strength (controls the size of the shrinkage)
- : the squared L2 norm of the coefficients,
We will study linear regression and polynomial regression in detail later; for now, the important point is that changes the model family and changes the fitting objective, but neither is learned by the inner least-squares step. Changing changes the model family or the fitting rule. Note that the ridge objective above shows the unpenalized intercept alongside the penalized coefficients, so the prediction used in the loss includes both.
The quantity we would like to know is the generalization risk
where:
- : the expected loss of the particular model fitted on with setting , where is a hyperparameter vector in the search space
- : the training data, held fixed in this conditional risk
- : a new observation drawn from the data-generating distribution
- : the data-generating distribution
- : a loss such as squared error
- : the fitted model returned by the learning algorithm on training data with setting
- : a new input feature vector drawn from the data-generating distribution
- : the fitted model's prediction at the new input
and the squared-error loss is
where:
- : the squared-error loss for a true target and prediction
- : the observed target
- : 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 observations. Below, 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 -fold cross-validation, partition the training indices into folds . Let be the data with fold removed, and let
be the model fitted without fold . 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:
where:
- : the -fold cross-validated estimate of the risk at hyperparameters
- : the number of folds
- : the index of the fold currently held out
- : the index set of observations in fold
- : the number of observations in fold
- : the model fitted on all folds except , with hyperparameters
- : the per-observation loss
- : the observed target for observation
- : the feature vector for observation
The inner sum averages loss within held-out fold , 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 is important: the model used to predict observations in never saw those observations during fitting. For a fixed , 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 can contain discrete values, continuous intervals, categorical choices, or conditional choices. For a polynomial ridge model we might use the degree and the penalty:
where:
- : the polynomial degree (a discrete hyperparameter)
- : 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 . Moving from to changes the penalty by a factor of ten, just as moving from to does. The interval occupies only 1% of the linear range . 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 hyperparameters and the -th hyperparameter has candidate values, the grid is
where:
- : the -th candidate value for the -th hyperparameter
- : the number of candidate values for the -th hyperparameter
- : the number of hyperparameters being tuned
- : the index selecting the candidate value along the -th hyperparameter dimension
Each element of is a single combination, chosen by fixing one candidate index 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:
where:
- : the total number of grid candidates
- : the number of hyperparameters being tuned
- : the number of candidate values for the -th hyperparameter
- : the product over all hyperparameters
- : the index identifying the hyperparameter whose candidate count is multiplied
If we tune eight polynomial degrees and four ridge penalties, the budget is 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 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 :
where:
- : the -th candidate hyperparameter vector drawn by the search
- : the search distribution over the hyperparameter space
- : the total number of candidates (the budget)
- : the index of the candidate draw
We then select
where:
- : the selected candidate index, using the first index to break an exact tie
- : the selected candidate vector at that index
- : the -fold cross-validation estimate of the risk for the -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 denote the finite set of evaluated candidates within the larger allowed space . After evaluating those candidates, we choose the one with the smallest validation loss:
The reported score of the winner is therefore
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 as
where:
- : the cross-validated estimate of the risk at hyperparameters
- : the true risk of the model fitted with hyperparameters
- : the estimation error on these particular folds (the gap between the validation estimate and the true risk)
The selected candidate has
where:
- : the validation estimate of the selected candidate's risk
- : the true risk of the selected candidate
- : the estimation error of the selected candidate on these folds, the gap between its validation estimate and its true risk (defined as evaluated at )
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
where:
- : the expected overstatement of performance caused by selecting the best candidate
- : the selected hyperparameters (a random quantity, depending on the validation folds)
- : the true risk of the model chosen by the search
- : the validation estimate of the selected model's risk
- : 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: . The minimum is a concave function of its arguments. Applying Jensen's inequality to this concave function gives , and substituting the unbiasedness yields . Also, over the fixed finite candidate set , for every realization (since ), so . Combining these gives , 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 and positive standard deviation . 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 , independently. The expected minimum is
where:
- : the value at which we evaluate whether one draw is the smaller
- : the standard normal density
- : the standard normal cumulative distribution function, the probability that a standard normal draw is at most ; its exceedance probability is
- the factor : the density that is the smaller of the two draws (one draw at , the other above it, in either order)
To evaluate the integral, use the identity . With , we have and for . This follows from the half-normal expectation
where:
- : the integration variable running over nonnegative values
- : the standard deviation of the zero-mean normal (equal to here, since )
- : the Gaussian kernel evaluated at , with the normalizing factor outside
- the factor : accounts for the two symmetric halves of the normal density when integrating only over
Therefore
Rescaling back to the candidates' units, the winner's validation score is about below the common mean even though neither candidate is better. With more candidates, the minimum is pushed even lower. More precisely, if candidates share the same true risk and their validation estimates have standard deviation , the expected minimum score is
where:
- : the common true risk shared by all candidates
- : the number of candidates sharing that common true risk
- : the standard deviation of each candidate's validation estimate
- : the standardized validation error of candidate , defined as , an independent standard normal draw
This expression is obtained by writing each estimate as with standard normal, so the minimum is and linearity of expectation gives the expression above. Since for under these assumptions, the expected minimum lies below the common risk .
This expression decreases as grows because the standardized minimum decreases with . 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 independent candidate estimates with the same true risk, the expected best observed score is plus times the expected minimum of standard normal draws. The next cell approximates that expected minimum by numerical integration over , and the figure plots the negative value as expected selection optimism in standard-deviation units.
PythonIn [3]Expand
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_minimaVisualizationOut [4]Expand

Nested cross-validation addresses this by adding an outer loop. Partition the data into outer folds , and let denote the data with outer fold removed. For each outer fold , run the entire inner search on and obtain
where:
- : the hyperparameters selected by the inner search when outer fold is held out
- : the -fold inner cross-validation estimate of candidate computed only on
For random search, 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,
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:
where:
- : the nested cross-validation estimate of the procedure's risk
- : the number of outer folds
- : the data with outer fold removed, used to run the inner search and select
- : the index set of observations in outer fold
- : the number of observations in outer fold
- : the model refitted on the outer training set using the selected hyperparameters
- : the per-observation loss
- : the observed target for observation
- : the feature vector for observation
- : the index running over observations within an outer test fold
- : the index of the outer fold
The outer test fold was not used to choose , so it gives a cleaner view of how the selection procedure performs on unseen data. Notice that 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 . They do not directly estimate the conditional risk of the final model refitted on all rows. Finite data and overlapping outer training sets still create variability. To see why the distinction matters, note that averages over outer folds each of which selected its own ; 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 , and refit
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 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 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
and the estimated standard error of that mean is
where:
- : the number of repeated nested runs (each with a fresh outer split)
- : the index of the repetition
- : the nested estimate produced by the -th repetition
- : the mean nested estimate across repetitions
- : the estimated standard error of across repetitions
- : the squared deviation of repetition 's estimate from the mean
- : the sample standard deviation of the repetition-level scores
The formula is the sample standard deviation of the repetition-level scores divided by : the inner square root is the sample standard deviation across repetitions, and dividing by 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 under the chosen search distribution. Each independent draw then has probability of producing an acceptable candidate; the value of 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 independent draws contain at least one good candidate is
where:
- : the probability that at least one of the candidates falls in the good region
- : the per-draw probability of an acceptable candidate under the search distribution
- : the number of independent candidate draws
- : the probability that all independent draws miss the good region, since each draw misses with probability and draws are independent
For a target hit probability with and per-draw hit probability with , the smallest integer budget giving hit probability at least is
where:
- : the smallest integer number of independent draws needed to reach hit probability at least , obtained by rounding the real-valued lower bound up to the next integer
- : the target lower bound on the probability of at least one hit (with )
- : the probability mass of the good region under the search distribution (with )
- : 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 and rearrange the steps one at a time:
Because , we have , so the division used in the last step reverses the inequality direction. Because as well, , and the ratio of two negative quantities is positive, so the lower bound on is a positive number. The ceiling rounds the real-valued lower bound upward. The limiting cases confirm the bound: if , no finite positive budget can hit; if , one draw already suffices since for any . This formula explains why random search can be effective when the good region is not too small. It also shows the limits: if is tiny, the required budget becomes enormous.
The coverage formula can be read as a budget-planning curve. The next cells evaluate over a range of budgets for three per-draw hit probabilities, then plot the resulting hit probabilities.
PythonIn [5]Expand
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]Expand

Each outer fold performs candidates times inner fits, plus one refit on the outer training set, giving
where:
- : the number of fits for nested assessment, including one outer refit per fold, given by
- : the approximate fitting cost of the nested procedure,
- : the number of outer folds
- : the number of candidate configurations searched per outer fold
- : the number of inner folds used to score each candidate
- : the average time to fit one model
- : the per-outer-fold fit count, namely candidates times inner fits plus one refit
The search fits and outer refits make up this count. A final search and refit on all development data add fits. With , and , nested assessment uses fits per repetition and a final search/refit adds . 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!