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.
gamma = [0.01, 0.1, 1]
3 × 3 = 9 candidates
Random Search
Sample only a fixed number of candidate settings from lists or distributions.
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
| Type | How it is obtained | Examples |
|---|---|---|
| Model parameter | Learned during fitting | Regression coefficients, tree split thresholds |
| Hyperparameter | Configured outside the learned model parameters | K 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.
What Is Grid Search?
Grid Search evaluates the Cartesian product of the candidate values you explicitly provide. If the grid contains 3 values for one hyperparameter and 2 for another, there are:
3 × 2 = 6 configurations
Simple grid
| max_depth ↓ / trees → | 50 | 100 |
|---|---|---|
| 2 | Model 1 | Model 2 |
| 4 | Model 3 | Model 4 |
| 6 | Model 5 | Model 6 |
Grid Search evaluates every cell in this defined grid. It does not search values that are not listed.
How Grid Search Works
Define candidate values
Choose a small, meaningful grid of hyperparameter values.
Generate combinations
Create every combination in that grid.
Cross-validate each candidate
Train and validate the model across the selected folds.
Compare the chosen metric
For example accuracy, F1, ROC AUC, MAE, or RMSE.
Refit the selected candidate
With refit=True, scikit-learn fits the selected settings again on all data given to the search object.
Search-Cost Example
Suppose we search 3 values of C and 3 values of gamma:
3 × 3 = 9 candidate configurations
9 candidates × 5 CV folds = 45 candidate-validation fits
With refit=True: + 1 final refit of the selected candidate
This multiplication is why an exhaustive grid can become expensive when we add many hyperparameters or many candidate values.
What Is Random Search?
Random Search samples a fixed number of candidate settings from the search space rather than evaluating every combination. In Scikit-learn, n_iter controls how many parameter settings are tried.
Same 3 × 3 search space
If n_iter=4, only four sampled settings are evaluated. Which four depends on the sampling process and, when applicable, random_state.
Why Can Random Search Be Useful?
Not every hyperparameter influences performance equally. If one dimension matters a lot and another matters little, a rigid grid can spend many evaluations repeating the same few important values. Random sampling can explore more distinct values of important dimensions for the same evaluation budget.
But Random Search is not magic
A small random budget can simply miss a strong region. Results can vary with the sampled candidates. Use a sensible search space, enough iterations, cross-validation, and a fixed random_statewhen reproducibility matters.
Going Deeper — Lists vs distributions
RandomizedSearchCV can sample from lists or from probability distributions. Continuous distributions are often useful for continuous hyperparameters because the search is not restricted to only a few manually chosen points.
from scipy.stats import loguniform
param_distributions = {
"svc__C": loguniform(1e-2, 1e2),
"svc__gamma": loguniform(1e-4, 1e0)
}Grid Search vs Random Search
| Question | Grid Search | Random Search |
|---|---|---|
| What gets tested? | Every combination in the defined grid | A fixed number of sampled settings |
| Budget control | Indirect—depends on grid size | Direct through n_iter |
| Good starting case | Small, carefully chosen search space | Larger space or limited compute budget |
| Guaranteed best? | Only best among candidates in the grid | No—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
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.967How 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.