Grid search and random search
The Hyperparameter Tuning Problem
The Goal: Find hyperparameter configuration that maximizes validation performance:
where 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:
- Define a grid for each hyperparameter:
- Learning rate:
- Regularization:
- Generate all combinations:
- For each combination:
- Train model with those hyperparameters on training set
- Evaluate on validation set
- Record validation score
- Select configuration with best validation score
- Retrain on full training+validation data with best config, test on hold-out test set
Computational Cost: If we have 3 values for , 4 for , and 5 for max depth:
With 5-fold CV, that's training runs.
Advantages of Grid Search
- Guarantees finding the best configuration in the grid (exhaustive)
- Simple to implement and understand
- Reproducible (deterministic)
- Good when hyperparameters have clear discrete choices (e.g., activation functions: ReLU, tanh, sigmoid)
Limitations of Grid Search
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).

Random Search: Efficient Sampling
How Random Search Works
Step-by-step:
- Define distributions for each hyperparameter:
- Learning rate:
- Regularization:
- Dropout:
- Sample random configurations (e.g., 60 samples)
- For each sample:
- Train model with those hyperparameters
- Evaluate on validation set
- Select best configuration
- (Optional) Zoom in: narrow distributions around best region and sample more
Why Random? Derivation from first principles:
Consider a 2D hyperparameter space where hyperparameter is important and is unimportant.
Grid search with budget of 9 trials:
- 3 values for :
- 3 values for :
- Tries:
- Unique values tried for important : Only 3 values
Random search with budget of 9 trials:
- Sample 9 random pairs
- Each sample independently choses from continuous distribution
- Unique values tried for important : 9 different values (all distinct)
The key insight: Random search gets more coverage in each dimension. For trials in dimensions:
- Grid with values per dimension: tries only unique values per hyperparameter
- Random: tries unique values per hyperparameter (in expectation)
Mathematical justification: If the objective function is:
where is important and is noise, then sampling random points gives evaluations of different values, whereas a grid only evaluates different values.
Advantages of Random Search
- More efficient in high dimensions: Tries more unique values per hyperparameter
- Handles continuous spaces naturally: No need to discretize
- Easy to parallelize: All trials are independent
- Can stop anytime: If you have budget for 100 trials but results plateau at 60, you can stop
- 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 :
Why? A single train/val split can be lucky or unlucky. CV averages out this variance.
Choosing Distributions for Random Search
Log-uniform for hyperparameters spanning orders of magnitude:
Example: Learning rate from to .
Why log-uniform? If we use uniform, we'd sample more values near (the upper end), but the space between and is just as important as between and . 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:
where is the best configuration found using only outer fold 's training data.
Comparing Grid and Random Search
Bergstra & Bengio (2012) Theoretical Result
Theorem (informal): For a hyperparameter space where only out of dimensions are important, random search with trials samples unique values per important dimension, while grid search with trials samples unique values per dimension.
Proof sketch:
- Grid search with trials: allocate values per dimension → coverage
- Random search: each trial independently samples from each dimension → each dimension gets unique samples
Implication: Random search is exponentially more efficient when is large and .
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
- Cross-Validation - Used to evaluate each hyperparameter configuration reliably
- Overfitting and Underfitting - Hyperparameters control model complexity, affecting bias-variance tradeoff
- Regularization - is a common hyperparameter searched
- Learning Rate Scheduling - Learning rate is often the most important hyperparameter to tune
- Bayesian Optimization - More advanced search that builds a surrogate model of the objective
- Ensemble Methods - Can reduce need for perfect hyperparameter tuning by averaging models
- Training-Validation-Test Split - Framework within which hyperparameter search operates
- Early Stopping - Another hyperparameter (patience) that can be tuned
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?
What is random search?
Why is random search often more efficient than grid search in high dimensions?
When should you use log-uniform distribution for random search?
What is nested cross-validation and why is it necessary?
What is the computational cost of grid search with3 hyperparameters having 4, 5, and 6 values respectively with 5-fold CV?
Why does grid search waste resolution in hyperparameter space?
What is the main advantage of grid search over random search?
How many unique values does random search sample for an important hyperparameter with 100 trials?
Concept Map
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.