Hyperparameter search: spend the budget before opening the test set
超参数搜索
Compare a nine-trial grid and random search, separate fitting from selection, and measure a locked test once.
hyperparameter-searchStart with the problem
A polynomial can fit a curve well and still be the wrong degree. Its coefficients are learned from training rows; its degree and penalty are choices about how to learn. Those outer choices are hyperparameters. Searching them means running a controlled collection of fits, not repeatedly changing settings until the test score looks good.
Imagine nine available training runs. A three-by-three grid spends three settings on each coordinate. Random sampling may examine more distinct penalty values, but can miss a useful degree. Bergstra and Bengio, especially Figure 1, explain why random search is a useful baseline when only some dimensions matter. That is a reason to compare methods, not a promise that every random draw beats a grid.
Definitions and derivation
Write h for a configuration and θ for fitted parameters. With B candidate configurations, the two levels are:
The inner fit sees training data. The outer comparison sees validation data. The test set appears in neither minimization. Because the winner was selected for a small validation error, that minimum is an optimistic estimate of its performance on fresh data. Cross-validation can make selection less dependent on one split; an untouched outer evaluation is still needed when reporting the selected procedure. Preprocessing must also be fitted within training folds. The scikit-learn search guide separates candidate generation, scoring and validation schemes.
Our inner model minimizes half mean squared error plus λ times half the squared non-intercept coefficients. Its zero-gradient condition gives:
The inverse denotes the mathematical solution; the program uses a linear solve. Positive λ regularizes all coefficients except the intercept. A nonempty design makes this system positive definite: the only unpenalized direction is a constant column with nonzero norm.
For random search, define the sampling distribution before running. Uniform log λ gives equal probability to equal-width intervals of log λ, rather than favoring large raw values. If a useful region has probability mass p under that distribution and B draws are independent, the chance of visiting it is:
This formula does not reveal p. It does not hold unchanged for adaptive, dependent draws. A grid with m values on each of d axes has mᵈ candidates; equal trial counts also do not imply equal elapsed time when model sizes differ.
Run the calculation
The complete Python 3.12 / NumPy 1.26.4 example uses five noisy training rows, four clean validation rows and four separately located test rows. Both search methods get nine fits. Random search uses seed 7. Each method locks its own winner before its test score is printed; the code never selects between methods using those test scores.
import numpy as np
from itertools import product
from random import Random
def fit(x,y,degree,penalty):
x,y=np.asarray(x,dtype=float),np.asarray(y,dtype=float)
if type(degree) is not int or not 1<=degree<=3 or not np.isfinite(penalty) or not 0<penalty<=10:raise ValueError('degree 1..3 and penalty in (0,10] required')
if x.ndim!=1 or y.shape!=x.shape or not 1<=len(x)<=32 or not np.isfinite(x).all() or not np.isfinite(y).all():raise ValueError('matched finite training vectors required')
X=np.vander(x,degree+1,increasing=True);D=np.diag([0.]+[1.]*degree)
return np.linalg.solve(X.T@X/len(x)+penalty*D,X.T@y/len(x))
def mse(coef,x,y):
x,y=np.asarray(x,dtype=float),np.asarray(y,dtype=float)
if x.ndim!=1 or x.size==0 or y.shape!=x.shape or not np.isfinite(x).all() or not np.isfinite(y).all():raise ValueError('matched finite evaluation vectors required')
return float(np.mean((np.vander(x,len(coef),increasing=True)@coef-y)**2))
def search(candidates,train_x,train_y,valid_x,valid_y):
if not 1<=len(candidates)<=64:raise ValueError('one to 64 trials required')
records=[]
for i,(degree,penalty) in enumerate(candidates):
coef=fit(train_x,train_y,degree,penalty)
records.append(dict(trial=i,degree=degree,penalty=penalty,score=mse(coef,valid_x,valid_y),coef=coef))
return min(records,key=lambda r:(r['score'],r['trial'])),records
if __name__=='__main__':
tx=np.array([-1.,-.5,0.,.5,1.]);ty=tx**2+np.array([.1,-.1,0,.1,-.1])
vx=np.array([-.75,-.25,.25,.75]);vy=vx**2
test_x=np.array([-.9,-.1,.1,.9]);test_y=test_x**2
rng=Random(7)
grid=list(product((1,2,3),(.001,.1,10.)))
random=[(rng.choice((1,2,3)),10**rng.uniform(-3,1)) for _ in range(9)]
for name,candidates in (('grid',grid),('random',random)):
winner,records=search(candidates,tx,ty,vx,vy)
print(name,'trials:',len(records),'winner:',winner['degree'],round(winner['penalty'],9))
print('validation / locked test MSE:',round(winner['score'],9),round(mse(winner['coef'],test_x,test_y),9))
print('training-mean baseline validation MSE:',round(float(np.mean((np.mean(ty)-vy)**2)),9))
Actual output:
grid trials: 9 winner: 2 0.001
validation / locked test MSE: 0.000501159 0.000658811
random trials: 9 winner: 2 0.001723622
validation / locked test MSE: 0.00050586 0.000667491
training-mean baseline validation MSE: 0.09765625
The grid slightly wins this particular validation comparison. Both beat the training-mean baseline. Neither outcome estimates population generalization from such a small, deliberately constructed dataset. Holding degree fixed, a fit with p coefficients costs O(np²+p³), and validation costs O(mp); multiply these by the number of trials. Keeping only the winning coefficients would reduce storage, but retaining the tiny trial table makes the selection auditable.
When the method fails
Search can fail before the optimizer starts: the useful region may be outside the declared bounds, a conditional parameter may be sampled for a model that does not use it, or the metric may reward the wrong behavior. Record rejected configurations and resource failures instead of quietly replacing them with extra successful trials.
Time series need splits that respect time; grouped observations need group separation. With noisy training, repeat promising configurations across seeds and report variability. Increasing the search budget can overfit validation even when every individual fit is regularized. A final test used repeatedly becomes another validation set. If fits are expensive, Bayesian optimization can choose subsequent candidates from observed results; it adds modeling assumptions and overhead.
Exercises with answers
- How many trials does a four-axis grid with five values per axis require?
Answer 1: 625, before repeats or cross-validation folds.
- With p=0.1 and B=10 independent draws, what is the hit probability?
Answer 2: 1−0.9¹⁰≈0.6513. The assumed 0.1 must come from the specified sampling distribution.
- Why is dividing the penalty range into equally spaced raw values different from log spacing?
Answer 3: Raw intervals get equal probability in the first scheme; equal multiplicative ranges get equal probability in the second.
- After choosing the grid winner, can you change its degree because its test score is disappointing?
Answer 4: You can start a new development round, but that test set has now influenced selection. Reserve new outer evaluation data for an honest final report.
Sources and next steps
Read Bergstra and Bengio’s effective-dimension illustration before treating random sampling as a theorem of superiority. Then use the fixed scikit-learn guide to map search spaces, scorers and validation splits onto an implementation. This chapter’s polynomial data, baseline, exact fit and nine-trial comparison are original teaching calculations. Continue with learning curves to diagnose data limitations and SGD to distinguish optimization randomness from search randomness.
Make a prediction, then check
Which data may select the candidate?
Learning objectives
- Separate fitting, validation selection and final testing.
- Compare grid and log-uniform random search at a fixed budget.
Prerequisites & connections
- Polynomial regression
- Cross-validation · Directory entry
References
- Random Search for Hyper-Parameter Optimization
James Bergstra; Yoshua Bengio · 2012 - Tuning the hyper-parameters of an estimator — scikit-learn 1.7
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. NumPy 1.26.4 is used in six programs; PBT and curriculum use standard-library exact fractions. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Random Search for Hyper-Parameter Optimization · Physical pages 3–4, practical random search and Figure 1 effective-dimensionality comparison.
- Tuning the hyper-parameters of an estimator — scikit-learn 1.7 · Section 3.2 introduction and 3.2.1: search components, GridSearchCV and RandomizedSearchCV.
Related topics