← All AI/ML articles

Grid search and random search, visualised.

Two simple ways to choose hyperparameters: try every combination on a grid, or try randomly drawn ones. Run both on the same real validation landscape with the same budget and see what each one actually explores.

1. Same budget2. See what each tries3. Compare the winners
Real 5-fold cross-validation error of an elastic-net regression. Penalty strength α across (log axis), mixing ratio ρ (l1_ratio) up. Bright = low error. Amber squares = grid search points, pink circles = random search points, rings = each strategy’s best, cyan diamond = the lowest-CV cell of the 525 plotted cells (a benchmark, not necessarily the true optimum).
Grid best CV0
Random best CV0
Lower this draw-
Behind the scenes · 1

Grid search: every combination

Pick a short list of values for each hyperparameter and try the Cartesian product: every value of one with every value of the other. It is simple, systematic and reproducible, but the number of runs is the product of the list lengths, so it grows exponentially with the number of hyperparameters.


Behind the scenes · 2

Random search: sample from distributions

Instead of a list, describe each hyperparameter by a distribution (for example log-uniform for a penalty strength, uniform for a ratio) and draw B random combinations. The budget is set directly by B, not by a product, and each trial uses a fresh value of every hyperparameter.


Behind the scenes · 3

Why random can explore more

Look at each hyperparameter on its own. A k×k grid tries only k distinct values of each, repeated again and again. B random trials try B distinct values of each. If the score depends mostly on one hyperparameter, random search looks at that one more finely for the same cost. Each plot shows the best score reachable at each value (the other hyperparameter optimised away), with the values each strategy actually tried marked underneath.


α axis. Amber ticks = grid values, pink ticks = random values.
l1_ratio axis. Same markers.

Behind the scenes · 4

The scale matters

A penalty like α matters on a multiplicative scale: the difference between 0.0001 and 0.001 can matter as much as between 0.1 and 1. Spacing or sampling it linearly puts almost every value in the top decade. Switch the α scale above and watch how many values land in each decade.


Tried α values per decade. Amber = grid, pink = random.
Behind the scenes · 5

One draw proves little: repeat it

Grid search is deterministic here, but random search changes with its seed. This button runs 30 independent random searches at budgets 9, 16, 25 and 36 on the current landscape and scale, and compares each with a grid of the same size.


The result above depends on one landscape. To see how much it depends on the data, repeat the same comparison (budget 16) on six freshly generated datasets with the same settings. It takes a few seconds.

In practice

The same idea in scikit-learn

import numpy as np from scipy.stats import loguniform, uniform from sklearn.linear_model import ElasticNet from sklearn.model_selection import GridSearchCV, RandomizedSearchCV grid = GridSearchCV( ElasticNet(max_iter=10000), param_grid={"alpha": np.logspace(-4, 0, 5), "l1_ratio": np.linspace(0.05, 1.0, 5)}, # 25 fits per fold cv=5, scoring="neg_mean_squared_error") rand = RandomizedSearchCV( ElasticNet(max_iter=10000), param_distributions={"alpha": loguniform(1e-4, 1), "l1_ratio": uniform(0.05, 0.95)}, n_iter=25, cv=5, scoring="neg_mean_squared_error", random_state=0) # 25 fits per fold # grid.fit(X, y); rand.fit(X, y) # .best_params_, .best_score_ (negative MSE), .best_estimator_ (refit on all data)

Both refit the best setting on all the data by default. Keep a separate test set that was never used in the search for an honest final score.

The mathematics

The mathematics behind grid and random search

Numbers below update live from the current landscape, budget and scale.

A. Grid size

|grid| = k1 × k2 × … × kd

B. Chance that random search lands in a good region

P(at least one of B draws in a region of probability p) = 1 − (1 − p)B   ,   B95% = ⌈ ln 0.05 / ln(1 − p) ⌉

Here a “good region” is the set of settings whose CV error is within 10% of the lowest on the map, and p is its share under the sampling distribution you chose. A grid, by contrast, finds the region only if a grid point happens to fall inside it.


C. Distinct values tried per hyperparameter

D. How much does each hyperparameter matter?

Si = Varxi( E[ log10 CV | xi ] ) / Var( log10 CV )

Si is the share of the landscape’s variation explained by hyperparameter i alone, computed from the plotted cells (a first-order sensitivity). The remainder is interaction or other effects. Importance depends on the model and data.


E. Sampling on a log scale

log-uniform: α = exp( U(ln a, ln b) ), U uniform every decade between a and b is equally likely uniform: α = U(a, b) probability of a decade is proportional to its width, so most draws fall in the top decade
Reading it
  • Random search is not guaranteed to beat grid search. It tends to help when only a few hyperparameters matter much.
  • Both strategies ignore earlier results, so neither learns where the good region is.
  • The winner’s CV score is a minimum over noisy estimates and is optimistic: confirm on a separate test set.
Experiment

Break it on purpose

Tiny equal budget

Give both strategies exactly 9 evaluations and compare what each finds, how many distinct α values each tried, and the benchmark.

The wrong scale

Space and sample α linearly with 16 evaluations each, and compare with the log scale on the same data.

Many hyperparameters

See what a grid costs for six hyperparameters, and what random search with 25 trials still gives you.

Check yourself

Three quick questions

Key takeaways

  • Grid search tries the Cartesian product of chosen values. It is simple and reproducible, but its cost multiplies with every added hyperparameter.
  • Random search draws B combinations from distributions. The budget is free to choose, and every trial brings a new value of every hyperparameter.
  • When few hyperparameters matter, random search tends to cover the important ones more finely for the same budget, but that is a tendency, not a guarantee.
  • Use the right scale: log-spaced or log-uniform for hyperparameters that act multiplicatively, and set ranges wide enough to contain the good region.
  • No universal winner: the outcome depends on the data, the budget and where the grid’s fixed points happen to fall. Check the repeated-run and six-dataset tables rather than trusting one draw.
  • Practical recipe: a coarse random search to find the region, then a finer grid or another random search inside it, and a final check on untouched test data.
← Back to all articles