Skip to main content
LearnMLAcademy
Intermediate10 min read

Grid & Random Search

Compare Grid Search exhaustive exploration against fast Random Search sweeps, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Grid Search and Random Search

A Machine Learning model can behave very differently when we change settings such as tree depth, number of neighbors, regularization strength, or learning rate. These configurable settings are called hyperparameters.

Grid & Random Search in Simple Words

Choose settings

C, depth, K, etc.

Try candidates

Grid or random

Validate

Cross-validation

Keep the best candidate

Then test once

Grid Search

Try every combination in a finite list of candidate values.

C = [0.1, 1, 10]
gamma = [0.01, 0.1, 1]
3 × 3 = 9 candidates

Random Search

Sample only a fixed number of candidate settings from lists or distributions.

Search space = many possibilities
n_iter = 4
Only 4 candidates are evaluated

Key idea

Grid Search is exhaustive only inside the grid you defined. Random Search is not automatically better or worse—it simply gives you a direct search budget and can explore a broader space when exhaustive search would be expensive.


Parameters vs Hyperparameters

TypeHow it is obtainedExamples
Model parameterLearned during fittingRegression coefficients, tree split thresholds
HyperparameterConfigured outside the learned model parametersK in KNN, max_depth, C, learning rate

Hyperparameters influence model capacity, regularization, optimization, or computational cost. A useful value depends on the dataset, metric, model, and validation procedure—there is rarely one universal best setting.

Cooking analogy

The ingredients are the data, the recipe is the algorithm, and settings such as oven temperature or cooking time are like hyperparameters. You do not learn the correct oven temperature by tasting the final exam meal repeatedly—you experiment on development batches, choose a useful setting, and then evaluate the final result separately.




Grid Search vs Random Search

QuestionGrid SearchRandom Search
What gets tested?Every combination in the defined gridA fixed number of sampled settings
Budget controlIndirect—depends on grid sizeDirect through n_iter
Good starting caseSmall, carefully chosen search spaceLarger space or limited compute budget
Guaranteed best?Only best among candidates in the gridNo—sampled search may miss strong settings

Do not memorize “Random Search is always better.”

Grid Search can be perfectly reasonable for a small focused grid. Random Search is attractive when exhaustive evaluation becomes expensive. The right choice depends on the search space, computation budget, and how sensitive the model is to different hyperparameters.


Why Cross-Validation Is Used During Search

Choosing hyperparameters from one validation split can make the result depend heavily on that particular split. Cross-validation rotates the validation fold and averages the scores, reducing dependence on one partition of the data.

5-fold example

Round 1
VALIDATE
TRAIN
TRAIN
TRAIN
TRAIN
Round 2
TRAIN
VALIDATE
TRAIN
TRAIN
TRAIN
Round 3
TRAIN
TRAIN
VALIDATE
TRAIN
TRAIN
Round 4
TRAIN
TRAIN
TRAIN
VALIDATE
TRAIN
Round 5
TRAIN
TRAIN
TRAIN
TRAIN
VALIDATE

These are validation folds, not the final test set. Keep the final test set outside the tuning loop whenever you want an independent estimate after model selection.


Avoid Preprocessing Leakage

If preprocessing learns from the full dataset before cross-validation, validation folds can influence quantities such as means, standard deviations, imputations, feature selection, or PCA components.

Risky

X_scaled = scaler.fit_transform(X)
GridSearchCV(model, ...).fit(X_scaled, y)

Better

Pipeline([
    ("scale", StandardScaler()),
    ("svc", SVC())
])

The Pipeline ensures that preprocessing is fitted again inside each training fold. Pipeline parameters are addressed using names such as svc__C and svc__gamma.


Python: Grid and Random Search on the Same Model

This example uses Iris only as a small teaching dataset. We first hold out a final test set, then run both searches only on the training portion.

Leakage-safe SVM tuning

from sklearn.datasets import load_iris
from sklearn.model_selection import (
    train_test_split,
    GridSearchCV,
    RandomizedSearchCV,
    StratifiedKFold,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

X, y = load_iris(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.20,
    random_state=42,
    stratify=y,
)

pipeline = Pipeline([
    ("scale", StandardScaler()),
    ("svc", SVC()),
])

cv = StratifiedKFold(
    n_splits=5,
    shuffle=True,
    random_state=42,
)

search_space = {
    "svc__C": [0.1, 1, 10],
    "svc__gamma": ["scale", 0.1, 0.01],
}

# Grid Search: all 3 x 3 = 9 combinations
grid = GridSearchCV(
    estimator=pipeline,
    param_grid=search_space,
    cv=cv,
    scoring="accuracy",
    refit=True,
    n_jobs=-1,
)
grid.fit(X_train, y_train)

# Random Search: sample only 4 combinations
random_search = RandomizedSearchCV(
    estimator=pipeline,
    param_distributions=search_space,
    n_iter=4,
    cv=cv,
    scoring="accuracy",
    random_state=42,
    refit=True,
    n_jobs=-1,
)
random_search.fit(X_train, y_train)

print("Grid candidates:", len(grid.cv_results_["params"]))
print("Grid best:", grid.best_params_)
print("Grid CV accuracy:", round(grid.best_score_, 3))
print("Grid test accuracy:", round(
    accuracy_score(y_test, grid.predict(X_test)), 3
))

print()
print("Random candidates:", len(random_search.cv_results_["params"]))
print("Random best:", random_search.best_params_)
print("Random CV accuracy:", round(random_search.best_score_, 3))
print("Random test accuracy:", round(
    accuracy_score(y_test, random_search.predict(X_test)), 3
))
Grid candidates: 9
Grid best: {'svc__C': 1, 'svc__gamma': 0.1}
Grid CV accuracy: 0.975
Grid test accuracy: 0.967

Random candidates: 4
Random best: {'svc__gamma': 0.1, 'svc__C': 10}
Random CV accuracy: 0.967
Random test accuracy: 0.967

How to read this result

  • Grid Search evaluated 9 candidates; Random Search evaluated only 4.
  • The best CV settings were different in this run.
  • Both happened to score 0.967 on this tiny held-out test set.
  • This does not prove the methods are equivalent or that Random Search always needs fewer trials.

Common Mistakes

Calling the best grid value “the optimal hyperparameter” without saying “among the values tested.”

Building an enormous grid just because many hyperparameters exist.

Assuming Random Search is always faster or always better.

Fitting scaling, imputation, feature selection, or PCA before cross-validation.

Using the final test set repeatedly to decide which search result to keep.

Using accuracy as the only tuning metric when the real problem cares more about recall, precision, cost, or another measure.

Quick Recap

If a grid has 4 values for A and 3 for B, how many configurations?

4 × 3 = 12 configurations.

What does n_iter=20 mean in RandomizedSearchCV?

The search evaluates 20 sampled parameter settings.

Why keep a final test set outside the search?

So the final evaluation is not repeatedly used to choose hyperparameters.

Final Summary

Grid Search exhaustively checks every combination in a defined finite grid. Random Search samples a fixed number of candidate settings, giving direct control over the search budget.

Neither method guarantees the universally best model. Good hyperparameter search also depends on a sensible search space, the right validation strategy, the right metric, leakage-safe preprocessing, and an untouched final evaluation when needed.

One sentence to remember

Grid = try all listed combinations; Random = try a fixed sample of combinations.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Grid & Random Search"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

  • Grid search evaluates listed combinations; random search samples distributions.
  • Grid suits small spaces; random search covers high-dimensional spaces broadly.
  • Use logarithmic scales for rates and penalties where appropriate.
  • Evaluate every candidate with leakage-safe pipeline cross-validation.
  • Confirm the selected candidate on untouched test data.
  • Compare performance with computation and reproducibility.
Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
Grid search with 4 hyperparameters each having 5 values and 5-fold CV requires how many model trainings?
Question 2 of 4
Bergstra & Bengio (2012) showed random search outperforms grid search when only 2 of 6 hyperparameters actually matter. Why?
Question 3 of 4
When does grid search have a genuine advantage over random search?
Question 4 of 4
What is Halving Search (HalvingGridSearchCV in sklearn) and why is it more efficient?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Grid search with 4 hyperparameters each having 5 values and 5-fold CV requires how many model trainings?▼

Correct Answer: 3,125 trainings: 5⁴=625 configurations × 5 folds

Grid search is exhaustive: 5⁴=625 combinations × 5 folds = 3,125 total trainings. Adding a 5th hyperparameter makes this 5⁵×5=15,625. This combinatorial explosion is why grid search is practical for at most 2-3 hyperparameters with few values.

2Bergstra & Bengio (2012) showed random search outperforms grid search when only 2 of 6 hyperparameters actually matter. Why?▼

Correct Answer: Grid search tries a fixed grid — if only 2 parameters matter, grid search wastes 4/6 of its budget varying unimportant parameters while keeping important ones fixed across groups. Random search samples all 6 parameters independently each trial, giving every trial a unique value for the 2 important parameters — far more efficient for finding the good region in the important dimensions

If learning_rate and max_depth matter but num_trees, subsample, colsample, and reg_lambda don't, grid search wastes 4/6 of its diversity budget on irrelevant parameters. Random search automatically uses all budget more effectively on the important dimensions.

3When does grid search have a genuine advantage over random search?▼

Correct Answer: Grid search guarantees complete coverage of a small, discrete search space. For example: kernel=['linear','rbf','poly'] × C=[0.1, 1, 10] — 9 combinations, each meaningful, all equally worth evaluating. For small discrete spaces where all combinations are plausible, grid search's exhaustiveness is valuable. For large or continuous spaces, random search wins

The crossover point: if the search space has fewer than ~20-30 total meaningful combinations, grid search's exhaustiveness provides value. Above that, random search's efficiency dominates.

4What is Halving Search (HalvingGridSearchCV in sklearn) and why is it more efficient?▼

Correct Answer: Halving search starts with many configurations evaluated on a small budget (small training set or few CV folds). The worst half are eliminated. Survivors are evaluated with double the budget. This continues until one configuration remains. Poor configurations are identified cheaply and eliminated early; compute is concentrated on promising configurations. Often achieves similar results to standard search with 5-10x less total compute

Successive halving is a bandit-style algorithm: spend a little to identify and eliminate bad options, then spend more on the remaining promising ones. sklearn implements HalvingGridSearchCV and HalvingRandomSearchCV.

Keep moving through the path

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next