2.6.13Model Evaluation & Selection

Grid search and random search

3,427 words16 min readdifficulty · medium2 backlinks

The Hyperparameter Tuning Problem

The Goal: Find hyperparameter configuration h={h1,h2,,hk}\mathbf{h}^* = \{h_1, h_2, \ldots, h_k\} that maximizes validation performance:

h=argmaxhHscoreval(h)\mathbf{h}^* = \arg\max_{\mathbf{h} \in \mathcal{H}} \text{score}_{\text{val}}(\mathbf{h})

where H\mathcal{H} is the hyperparameter space.

Why This is Hard:

  • No gradient information (hyperparameters aren't differentiable w.r.t. validation loss)
  • Each evaluation requires full model training (expensive)
  • Space is high-dimensional and combinatorial
  • Interactions between hyperparameters are non-linear

Grid Search: Exhaustive Exploration

How Grid Search Works

Step-by-step:

  1. Define a grid for each hyperparameter:
    • Learning rate: α{0.001,0.01,0.1}\alpha \in \{0.001, 0.01, 0.1\}
    • Regularization: λ{0.01,0.1,1.0,10.0}\lambda \in \{0.01, 0.1, 1.0, 10.0\}
  2. Generate all combinations: (0.001,0.01),(0.001,0.1),,(0.1,10.0)(0.001, 0.01), (0.001, 0.1), \ldots, (0.1, 10.0)
  3. For each combination:
    • Train model with those hyperparameters on training set
    • Evaluate on validation set
    • Record validation score
  4. Select configuration with best validation score
  5. Retrain on full training+validation data with best config, test on hold-out test set

Computational Cost: If we have 3 values for α\alpha, 4 for λ\lambda, and 5 for max depth:

Total models=3×4×5=60 models\text{Total models} = 3 \times 4 \times 5 = 60 \text{ models}

With 5-fold CV, that's 60×5=30060 \times 5 = 300 training runs.

  1. Guarantees finding the best configuration in the grid (exhaustive)
  2. Simple to implement and understand
  3. Reproducible (deterministic)
  4. Good when hyperparameters have clear discrete choices (e.g., activation functions: ReLU, tanh, sigmoid)

Additional Limitation: Grid search wastes resolution. If you allocate 5 values to learning rate and 5 to batch size, you get 25 combinations. But if learning rate is much more important, you'd want15 values for learning rate and 3 for batch size (still 45 combinations, but better coverage of the important dimension).

Figure — Grid search and random search

Random Search: Efficient Sampling

How Random Search Works

Step-by-step:

  1. Define distributions for each hyperparameter:
    • Learning rate: αLogUniform(104,101)\alpha \sim \text{LogUniform}(10^{-4}, 10^{-1})
    • Regularization: λLogUniform(103,101)\lambda \sim \text{LogUniform}(10^{-3}, 10^{1})
    • Dropout: pUniform(0.1,0.5)p \sim \text{Uniform}(0.1, 0.5)
  2. Sample nn random configurations (e.g., 60 samples)
  3. For each sample:
    • Train model with those hyperparameters
    • Evaluate on validation set
  4. Select best configuration
  5. (Optional) Zoom in: narrow distributions around best region and sample more

Why Random? Derivation from first principles:

Consider a 2D hyperparameter space where hyperparameter h1h_1 is important and h2h_2 is unimportant.

Grid search with budget of 9 trials:

  • 3 values for h1h_1: {a,b,c}\{a, b, c\}
  • 3 values for h2h_2: {x,y,z}\{x, y, z\}
  • Tries: (a,x),(a,y),(a,z),(b,x),(b,y),(b,z),(c,x),(c,y),(c,z)(a,x), (a,y), (a,z), (b,x), (b,y), (b,z), (c,x), (c,y), (c,z)
  • Unique values tried for important h1h_1: Only 3 values (a,b,c)(a, b, c)

Random search with budget of 9 trials:

  • Sample 9 random (h1,h2)(h_1, h_2) pairs
  • Each sample independently choses h1h_1 from continuous distribution
  • Unique values tried for important h1h_1: 9 different values (all distinct)

The key insight: Random search gets more coverage in each dimension. For nn trials in kk dimensions:

  • Grid with n1/kn^{1/k} values per dimension: tries only n1/kn^{1/k} unique values per hyperparameter
  • Random: tries nn unique values per hyperparameter (in expectation)

Mathematical justification: If the objective function is:

f(h1,h2)=g(h1)+ϵ(h2)f(h_1, h_2) = g(h_1) + \epsilon(h_2)

where gg is important and ϵ\epsilon is noise, then sampling nn random points gives nn evaluations of different h1h_1 values, whereas a n×n\sqrt{n} \times \sqrt{n} grid only evaluates n\sqrt{n} different h1h_1 values.

  1. More efficient in high dimensions: Tries more unique values per hyperparameter
  2. Handles continuous spaces naturally: No need to discretize
  3. Easy to parallelize: All trials are independent
  4. Can stop anytime: If you have budget for 100 trials but results plateau at 60, you can stop
  5. Better for important/unimportant hyperparameter scenarios: Automatically gets more coverage on dimensions that matter

When to Use Which?

Use Grid Search when:

  • Few hyperparameters (≤3)
  • Discrete choices (e.g., optimizer type: 'adam' vs 'sgd')
  • Small, well-understood search space
  • You need to report every combination tried (reproducibility requirements)

Use Random Search when:

  • Many hyperparameters (≥4)
  • Continuous hyperparameters
  • Large or unknown search space
  • You suspect some hyperparameters are more important than others
  • Computational budget is limited

Practical Implementation Details

Cross-Validation Integration

Both methods should use cross-validation to estimate performance:

For configuration h\mathbf{h}:

score(h)=1ki=1kmetric(h,foldi)\text{score}(\mathbf{h}) = \frac{1}{k} \sum_{i=1}^k \text{metric}(\mathbf{h}, \text{fold}_i)

Why? A single train/val split can be lucky or unlucky. CV averages out this variance.

Log-uniform for hyperparameters spanning orders of magnitude:

hLogUniform(a,b)    loghUniform(loga,logb)h \sim \text{LogUniform}(a, b) \implies \log h \sim \text{Uniform}(\log a, \log b)

Example: Learning rate from 10510^{-5} to 10110^{-1}.

Why log-uniform? If we use uniform, we'd sample more values near 10110^{-1} (the upper end), but the space between 10510^{-5} and 10410^{-4} is just as important as between 10210^{-2} and 10110^{-1}. Log-uniform gives equal probability to each order of magnitude.

Uniform for bounded hyperparameters: Example: Dropout probability from 0.0 to 0.5.

Integer uniform for discrete counts: Example: Number of hidden units from 50 to 500.

Nested Cross-Validation for Unbiased Evaluation

Nested CV formula for unbiased performance estimate:

scoreunbiased=1Ki=1Kscoretest(hi)\text{score}_{\text{unbiased}} = \frac{1}{K} \sum_{i=1}^K \text{score}_{\text{test}}(\mathbf{h}_i^*)

where hi\mathbf{h}_i^* is the best configuration found using only outer fold ii's training data.

Bergstra & Bengio (2012) Theoretical Result

Theorem (informal): For a hyperparameter space where only kk out of dd dimensions are important, random search with nn trials samples O(n)\mathcal{O}(n) unique values per important dimension, while grid search with nn trials samples O(n1/d)\mathcal{O}(n^{1/d}) unique values per dimension.

Proof sketch:

  • Grid search with nn trials: allocate n1/dn^{1/d} values per dimension → O(n1/d)\mathcal{O}(n^{1/d}) coverage
  • Random search: each trial independently samples from each dimension → each dimension gets O(n)\mathcal{O}(n) unique samples

Implication: Random search is exponentially more efficient when dd is large and kdk \ll d.

Empirical Comparison

Study: Bergstra & Bengio tested on various ML tasks (neural nets, deep belief networks).

Result: Random search found configurations within 3% of optimal using 2-3× fewer evaluations than grid search.

Why? Most tasks had 1-3 important hyperparameters out of 5-10 total. Random search's better per-dimension coverage dominated.

Connections


Recall Explain to a 12-Year-Old

Imagine you're trying to find the best settings for a video game character (speed, strength, defense). You have a training mode where you can test different combinations and see your score.

Grid search is like trying every single combination: speed=1 with strength=1, then speed=1 with strength=2, etc. If you have 10 options for each of 3 settings, that's 10×10×10 = 1,000 tests! It takes forever but you'll definitely find the best combination that you tried.

Random search is like closing your eyes and randomly picking settings1,000 times. Sounds silly, but here's the trick: imagine speed matters a lot but defense doesn't matter much. With grid search, you might only try 10 different speeds (because you spread your tests across all settings). But with random search, all 1,000 tests use different random speeds! So you explore the important setting (speed) much better.

The lesson: When some things matter more than others, random trying can actually be smarter than systematic trying. It's like how exploring a new city by wandering randomly sometimes helps you find cool places that weren't on the map!

Flashcards

#flashcards/ai-ml

What are hyperparameters and how do they differ from model parameters? :: Hyperparameters are settings configured before training (learning rate, regularization strength, tree depth) that control the learning process. Model parameters are learned from data during training (weights, biases). Hyperparameters must be chosen, not learned.

What is grid search?
Grid search exhaustively evaluates every combination from a predefined grid of hyperparameter values. For k hyperparameters with n_i values each, it trains ∏n_i models and selects the configuration with the best validation score.
What is random search?
Random search samples hyperparameter combinations randomly from specified distributions (uniform, log-uniform) for n trials. It trains n models with random configurations and selects the best performer.
Why is random search often more efficient than grid search in high dimensions?
For n trials in dimensions, grid search tries only n^(1/d) unique values per hyperparameter, while random search tries approximately n unique values per hyperparameter. When d is large, n^(1/d) becomes very small (e.g., 256^(1/4)=4 vs 256).
When should you use log-uniform distribution for random search?
Use log-uniform for hyperparameters that span multiple orders of magnitude (learning rate: 10^-5 to 10^-1). It ensures equal sampling probability per order of magnitude, preventing bias toward larger values that would occur with uniform sampling.
What is nested cross-validation and why is it necessary?
Nested CV has an outer loop (K-fold CV for performance estimation) and inner loop (hyperparameter search with CV). It prevents test set leakage that occurs when reporting the best CV score from hyperparameter tuning, which is overly optimistic because validation sets influenced the model selection decision.
What is the computational cost of grid search with3 hyperparameters having 4, 5, and 6 values respectively with 5-fold CV?
Total models = 4 × 5 × 6 = 120configurations. With 5-fold CV: 120 × 5 = 600 training runs.
Why does grid search waste resolution in hyperparameter space?
Grid search allocates equal numbers of values to all hyperparameters regardless of importance. If learning rate is critical but batch size isn't, allocating 5 values to each wastes resolution on batch size. Better to allocate 15 values to learning rate and 3 to batch size.
What is the main advantage of grid search over random search?
Grid search guarantees finding the best configuration within the defined grid (exhaustive). It's deterministic and reproducible. Good for small discrete spaces (≤3 hyperparameters) with clear choices.
How many unique values does random search sample for an important hyperparameter with 100 trials?
Approximately 100 unique values (each trial independently samples). Compare to grid search with 100 trials in 4D space: only 100^(1/4) ≈ 3.16 values per dimension.

Concept Map

contrasts with

must tune to reach

difficult because

motivates

motivates

does

does

incurs

multiplied by

selects

selects

Hyperparameters set before training

Parameters learned during training

Find h star maximizing val score

Hard problem no gradient expensive

Grid Search

Random Search

Try all combinations

Sample randomly

Cost = product of value counts

Cross-validation runs

Best config retrain test on hold-out

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Jab ap ek machine learning model train karte ho, to bahut sare settings hote hain jo apko pehle se decide karni padti hain—jaise learning rate, regularization strength, ya tree depth. Yeh hyperparameters kehlate hain, aur inhe data se nahi seekha ja sakta, apko khud choose karna padta hai. Problem yeh hai ki agar aapne galat hyperparameters choose kar liye, to aapka model ya to underfit karega (kuch bhi nahi seekhega) ya overfit karega (training data ko ratt lega par nayi data pe fail karega).

To sahi hyperparameters dhoondhne ke liye do popular tarike hain: Grid Search aur Random Search. Grid search bilkul systematic hai—ap harek combination ko try karte ho. Suppose aapke pas 3 values hain learning rate ke liye aur 4 values hain regularization ke liye, to grid search 3×4=12 models train karega aur sabse best wala chun lega. Yeh guaranteed hai ki aapko best combination mil jayega jo aapne define kiya tha, lekin problem yeh hai ki jaise hi aap zyada hyperparameters add karte ho, combinations exponentially badh jate hain. Agar 5 hyperparameters hain aur har ek ke 5 values hain, to 5^5 = 3,125 models train karne padenge. Yeh bahut time-consuming aur expensive ho jata hai.

Random search ek smarter approach hai jab bahut sare hyperparameters ho. Isme ap systematic grid ki jagah randomly combinations sample karte ho. Matlabagar aapko 100 trials ka budget hai, to ap 100 random configurations try karoge. Surprisingly, yeh zyada efficient hota hai kyunki agar kuch hyperparameters important hain aur kuch nahi, to random search automatically important walon kozyada explore kar leta hai. Grid search meagar aapne 100 trials ko 4dimensions me divide kiya (10×10×10×10 ka kuch grid), to har dimension me sirf 10 unique values try hoti hain. Lekin random search me har trial unique hota hai, to apko har important hyperparameter ke liye 100 different values mil jate hain. Research studies (Bergstra & Bengio 2012) ne dikhaya hai ki random search aksar grid search se 2-3 guna kam trials me best configuration dhoodh leta hai jab dimensions zyada ho.

Practical advice: Agar aapke pas 3 ya usse kam hyperparameters hain aur discrete choices hain (jaise optimizer type: Adam ya SGD), to grid search thek hai. Lekin agar 4 ya zyada hyperparameters hain, continuous values hain (jaise learning rate 0.001 se 0.1 tak), ya apko nahi pata ki kaun sa hyperparameter kitna important hai, to random search use karo. Aur hamesha cross-validation ke sath search karo taki ek lucky/unlucky split ki wajah se aapka result biased na ho. Yeh tuning process model development ka critical part hai kyunki best hyperparameters ka matlab hai best performance aur production me success.

Go deeper — visual, from zero

Test yourself — Model Evaluation & Selection

Connections