2.6.13 · D4Model Evaluation & Selection

Exercises — Grid search and random search

2,985 words14 min readBack to topic

Before we begin, one picture fixes the whole vocabulary you need.


Level 1 — Recognition

L1·Q1 — Parameter or hyperparameter?

For each item say parameter (learned during training) or hyperparameter (set before training): (a) the weight in , (b) the learning rate , (c) the regularization strength , (d) the bias , (e) the number of trees in a random forest.

Recall Solution

What decides it: ask "does gradient descent update this from data, or did I type it in before training started?"

  • (a) parameter (updated each training step).
  • (b) hyperparameter (you pick it; it controls how updates).
  • (c) hyperparameter (see Regularization; you choose how hard to penalize big weights).
  • (d) parameter (learned like ).
  • (e) number of trees — hyperparameter (structural choice made before fitting).

L1·Q2 — Count the grid

Learning rate grid (3 values) and regularization grid (4 values). Grid search trains one model per combination. How many models?

Recall Solution

Rule: grid search takes the product of the counts — every paired with every . Picture a lattice of dots: 12 corners.

L1·Q3 — Grid vs random in one line

A friend says "random search is just grid search with sloppy spacing." State the one true structural difference.

Recall Solution

Grid search puts points on a fixed lattice — the values on each axis are reused across every combination. Random search draws each point independently from a distribution, so (in expectation) every trial uses a fresh, distinct value on every axis. That distinctness is the entire advantage, not "sloppiness."


Level 2 — Application

L2·Q1 — Full grid cost with cross-validation

You tune 3 values of , 4 of , and 5 of max-depth , using 5-fold cross-validation. How many total training runs?

Recall Solution

Step 1 — combinations: . Step 2 — each combination is trained once per fold, so multiply by folds : Why fold-multiply? In -fold CV each configuration is fit times (each time holding out a different slice), and the reported score is the average — that is what makes the score reliable.

L2·Q2 — Grid step size on a log axis

You want to try across . Are these evenly spaced? What kind of spacing is it, and why is that the right choice for ?

Recall Solution

They are not evenly spaced on a normal ruler ( to is a gap of ; to is a gap of ). They are evenly spaced in multiplication: each is the previous. This is log-uniform spacing (equal steps in ). It is right for because what matters is the order of magnitude: the difference between and matters as much as vs . A linear grid would waste almost all its points in the large-number region and never explore small properly.

L2·Q3 — Reading the grid heat-map

The figure below shows validation scores on a grid over . Read off the best cell and its score.

Recall Solution

Scan for the brightest amber cell. It sits at () and (), with validation score . Why this cell wins: moderate (not so large it overfits) with moderate (kernel neither too wide nor too spiky) balances fit vs generalization — see Overfitting and Underfitting.


Level 3 — Analysis

L3·Q1 — Unique values per axis

You have a budget of trials in dimensions. Compare unique values explored per hyperparameter for (a) a square grid, (b) random search.

Recall Solution

(a) Square grid: to get cells in 2D you use values per axis. So each hyperparameter is only ever tried at 10 distinct values (each value reused across a whole row/column). (b) Random search: each of the trials draws a fresh independent value on each axis, so in expectation 100 distinct values per hyperparameter. General rule: grid gives unique values per axis; random gives . In this case vs — a 10× coverage gain on the axis that might actually matter.

L3·Q2 — The low-effective-dimension argument

Suppose the true objective is where is important and is negligible noise. With a grid vs random points, how many distinct evaluations of the important function does each give?

Recall Solution

Because depends meaningfully only on , what matters is how many different values you sampled.

  • Grid: only distinct values → only useful evaluations of . The axis is wasted since barely moves the score.
  • Random: distinct values → useful evaluations of . Conclusion: when the objective secretly depends on few dimensions, random search is -times more informative. This is the reason random search dominates grid in high dimensions.

L3·Q3 — Where grid still wins

Give a concrete scenario where grid search is genuinely the better choice, and justify it.

Recall Solution

Scenario: tuning 2 discrete, categorical hyperparameters — e.g. optimizer and activation . Why grid wins here:

  1. Only combinations — cost is trivial, no dimensionality problem.
  2. Values are discrete with no "in-between" — there is no continuous distribution to sample from, so random search's distinctness advantage evaporates.
  3. Grid is exhaustive and reproducible — you can report every combination, which some publications require.

Level 4 — Synthesis

L4·Q1 — Design a fair comparison

You must compare grid vs random search fairly on an SVM with hyperparameters and . Design the budgets so the comparison is apples-to-apples, and specify the search domain.

Recall Solution

Fairness rule 1 — same total trainings. Give both methods exactly 16 model trainings (a grid = 16). Fairness rule 2 — same search domain. Both must explore the identical rectangle, otherwise you'd be comparing search strategies and domains at once. Fix the domain once:

  • Grid: place 4 log-spaced points per axis inside that domain: (geometric steps), . These are the log-evenly-spaced endpoints and interior points of the same interval.
  • Random: draw 16 samples with and — the log-uniform distribution defined above, whose support is exactly that rectangle. Why this is now fair: identical budget (16), identical domain (same rectangle, same log scaling). Any score difference is attributable to strategy alone. Report best validation score and number of distinct values explored: 16 for random vs only 4 for grid.

L4·Q2 — Probability of hitting a good region

Suppose the top-performing configurations occupy the best 5% of the hyperparameter space. Using random sampling, how many independent trials do you need so the probability of landing in that good region at least once is ?

Recall Solution

Setup: each trial independently lands in the good region with probability , so it misses with probability . Miss all trials: (independence lets us multiply). Hit at least once: . We want Solve: take logs (which turn the exponent into a multiplier): Round up: trials. This is why "~60 random trials" is a famous rule of thumb — it gives ~95% chance of hitting the best 5% of the space regardless of dimension.


Level 5 — Mastery

L5·Q1 — Full end-to-end budget with nested CV and early stopping

You tune 4 hyperparameters at values using grid search. You use nested cross-validation: an outer loop of folds gives an honest performance estimate, and inside each outer fold an inner loop of folds is used to pick the best configuration. Each training would take up to 100 epochs but Early Stopping cuts it to an average of 40 epochs. If one epoch costs 2 seconds, estimate total wall-clock time (assume serial execution).

Recall Solution

Why nested CV multiplies by both loops: for each of the outer folds we run a whole grid search scored by -fold inner CV, then retrain the chosen config. The inner search dominates the count, so we budget . Step 1 — combinations: . Step 2 — inner trainings per outer fold: each combination trained times → . Step 3 — times outer folds: trainings. Step 4 — epochs per training with early stopping: . Total epochs . Step 5 — time: hours. Contrast with a single (non-nested) 5-fold loop: that would be s h. Nested CV costs the extra outer/inner factor ( vs trainings) but buys a leakage-free performance estimate.

L5·Q2 — Random vs grid, decide with numbers

You have 8 continuous hyperparameters and a budget of trials. (a) How many unique values per hyperparameter would a full grid give? (b) What does random search give? (c) State your recommendation and why.

Recall Solution

(a) Grid: , so values per axis . Since , this is . Only 2 values per hyperparameter — barely "low vs high." Useless resolution. (b) Random: distinct values per hyperparameter (in expectation) — every trial a fresh value on every axis. (c) Recommendation: random search. At 8 continuous dimensions a grid collapses to a 2-level cube that cannot resolve any curve, while random search still explores 256 distinct settings per axis. If evaluations are very expensive, escalate to Bayesian Optimization, which learns where to sample next.

L5·Q3 — Synthesis: full tuning pipeline

Sketch (in words) a correct, leakage-free tuning pipeline that uses random search, cross-validation, and a final honest test estimate. Name each safeguard.

Recall Solution
  1. Split data into a train+validation pool and an untouched test set (Training-Validation-Test Split). The test set is locked away and touched exactly once, at the very end.
  2. Random search over the sampling distributions on the train+val pool — e.g. , , dropout .
  3. For each sampled configuration, score it with -fold cross-validation inside the pool (Cross-Validation): fit on folds, validate on the held-out fold, average the scores for a stable estimate.
  4. Select the configuration with the best mean CV score. (Optionally zoom in: narrow the distributions around this best region and sample again.)
  5. Retrain that single best config on the entire train+val pool, so the final model uses all non-test data.
  6. Evaluate once on the locked test set → this is your honest generalization estimate; do not tune anything after seeing it. Safeguards named: the locked test set prevents selection leakage (hyperparameters were never chosen using test data); cross-validation prevents lucky-split bias (one unlucky validation split can't dominate the average); retraining on the full pool uses all available data before the final report. For an even more honest estimate of the whole procedure, wrap steps 2–5 in an outer CV loop (the nested CV of L5·Q1). Optionally combine several strong configs via Ensemble Methods.

Recall One-line self-test

Random search's core advantage over grid ::: it explores distinct values per hyperparameter vs grid's , so it wins when the objective depends on few of many dimensions. Total training runs for grid with combos and -fold CV ::: . Random trials for ~95% chance of hitting the best 5% region ::: about 59 (the "~60 trials" rule).