Chapter 37 of 42 · ~16 min read & lab+60 XP
Chapter 37 · Machine Learning

Hyperparameter Tuning: Grid Search, Random Search & Bayesian Optimization (Optuna)

Parameters vs. Hyperparameters, why Random Search beats Grid Search in high dimensions, and how Bayesian TPE + Early Pruning find optimal models 10× faster

What Is It?

Hyperparameter Tuning systematically searches for the best configuration settings (like learning rate, tree depth, or regularization λ) that cannot be learned automatically from training data.

Why Is It Required?

Default hyperparameters are rarely optimal for your specific dataset — yet brute-force Grid Search wastes 90% of compute testing useless combinations.

Everyday Analogy: Parameters are the notes a pianist plays; Hyperparameters are the tempo, acoustics, and piano tuning set BEFORE the concert begins.
Why ML Engineers & Data Scientists Actually Need This

Smart hyperparameter tuning (Optuna + log-scale ranges + pruning) extracts the final +2%–5% metric lift while cutting cloud GPU/CPU bills by 10×.

ML / AI Engineer

Log-scale sampling (suggest_float('lr', 1e-4, 1e-1, log=True)) avoids spending 90% of trials in [0.01, 0.1] while ignoring [0.0001, 0.01].

Data Scientist

Nested Cross-Validation gives an unbiased performance estimate when heavily tuning hyperparameters on small datasets.

Interview & Debug Edge

Classic question: 'Why does Bergstra & Bengio (2012) show Random Search beats Grid Search for ML hyperparameter tuning?'

Step 0 · Test Your Gut Before Any Math!

You want to search learning_rate between 0.0001 and 0.1. Which sampling distribution explores every order of magnitude equally?

What You Will Master in This Chapter
  • Distinguish learned Parameters (weights w, tree split thresholds) from Hyperparameters (max_depth, lr, C, K).
  • Explain why Random Search explores dramatically more unique values of important hyperparameters than Grid Search.
  • Understand how Bayesian Optimization (Optuna TPE) learns from past trials to zoom into promising regions, and how Median/Hyperband Pruning kills bad runs early.
  • Use log-uniform search scales for learning rates and regularization strengths (1e-4 to 1e-1).
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
θ∗=arg⁡min⁡θLtrain(θ;λ)\theta^* = \arg\min_{\theta} \mathcal{L}_{\text{train}}(\theta; \lambda)Say aloud:“Inner training loop (parameters)”
Plain-English Meaning
Model fits weights θ on the training set for a fixed hyperparameter setting λ.
Everyday Example
SGD updates weights w and bias b.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Grid Search wastes trials re-testing the exact same values of important knobs; Random Search tests fresh values every single trial; Bayesian Optimization (Optuna) remembers which neighborhoods scored well and focuses future trials right around the peak!

1. Grid vs. Random vs. Bayesian (Optuna) Search

MethodHow It SearchesStrengthsBest For
Grid SearchExhaustive Cartesian productSimple, deterministic1–2 tiny discrete knobs only
Random SearchIndependent random drawsEmbarrassingly parallel; beats Grid in ≥3\ge 3 dimsFast initial exploration
Bayesian (Optuna TPE)Surrogate model guides next trial5×–10× fewer trials + Early PruningExpensive GBDT & Neural Net tuning!
Interactive Mini-Lab • Bergstra & Bengio (2012)

Why Random Search Explores Way More Values of the Important Hyperparameter

Budget = 9 runs
2D Grid Search
3
distinct Learning Rates tested
Random Search
9
distinct Learning Rates tested!
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Yes! If you run 1,000 Optuna trials on a tiny 500-row validation set, you will eventually get lucky by chance. Guard against this with K-Fold CV inside the objective and a sealed Test vault checked once at the end.

Interactive Visual Lab
Lab Challenge: Compare how optimizer & hyperparameter settings change convergence trajectories.
Interactive Animation • Ill-Conditioned Ravine f(x, y) = 0.5x² + 6y²

Live 60 FPS Optimizer Contour Race: Plain SGD vs. Momentum vs. AdamW

Watch Plain SGD bounce off the steep y-walls while AdamW adapts per-axis and glides to the bullseye!

● Plain SGD● Momentum● Adam / AdamW
0%
Step 0 / 36
SGD Loss: 21.43 · Momentum Loss: 21.43 · AdamW Loss: 21.435.
Intuition Takeaway: Sample learning rates and regularization on a log scale, ditch Grid Search for Random Search or Optuna Bayesian TPE with pruning, and always tune on CV — never on training or test data.
Production NumPy & PyTorch Code Patterns
import numpy as np

# Why Random Search Beats Grid Search When Only 1 of 2 Knobs Matters
rng = np.random.default_rng(7)
def val_loss(lr_log10: float, irrelevant_knob: float) -> float:
    return (lr_log10 - (-2.35)) ** 2 + 0.01 * abs(irrelevant_knob)  # optimum near 10^-2.35

# 3x3 Grid = 9 trials (only 3 distinct lr values!)
grid_lrs = np.linspace(-4, -1, 3)
grid_best = min(val_loss(lr, k) for lr in grid_lrs for k in [0.0, 0.5, 1.0])

# Random Search = 9 trials (9 distinct lr values!)
rand_lrs = rng.uniform(-4, -1, size=9)
rand_ks  = rng.uniform(0, 1, size=9)
rand_best = min(val_loss(lr, k) for lr, k in zip(rand_lrs, rand_ks))

print(f"9-trial Grid best loss:   {grid_best:.4f} (only 3 unique LRs tested)")
print(f"9-trial Random best loss: {rand_best:.4f} (9 unique LRs tested!)")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Tuning hyperparameters to minimize TRAINING loss instead of VALIDATION loss.
Best Practice: Training loss will just pick max_depth=∞ and reg_lambda=0 (100% overfitting). Always tune on Validation / CV loss!
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1Why does Random Search usually outperform Grid Search when tuning 5 hyperparameters with a fixed budget of 30 trials?

Apply What You Learned — Solve Matching Coding Problems