Skip to content
E
Educatum

Grid Search vs. Random Search

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Grid search exhaustively evaluates every point on a fixed Cartesian grid of hyperparameter values, whereas random search samples a specified budget of combinations from prior distributions. Random search is generally far more sample-efficient in higher dimensions—especially when only a subset of hyperparameters strongly affects validation performance—because every trial tests distinct values along important axes.

Direct Answer

Grid search and random search are black-box hyperparameter optimization strategies evaluated via cross-validation. Grid search tests all Cartesian combinations of manually chosen discrete values—simple and reproducible for 1–2 low-cardinality hyperparameters, but suffering exponential blowup (kdk^d evaluations for dd parameters with kk values each). Random search draws nn independent combinations from continuous or discrete distributions (commonly log-uniform for scale parameters like learning rate, CC, or γ\gamma). As Bergstra & Bengio (2012) demonstrated, when only a few hyperparameters matter most (low effective dimensionality), nn random trials explore nn distinct values along every important hyperparameter, whereas an m×mm \times m grid (n=m2n = m^2) tests only n\sqrt{n} distinct values per axis—wasting compute on redundant coordinates along unimportant dimensions.

Key Terms

  • Hyperparameters: Configuration settings chosen before training (e.g., learning rate, SVM CC, kernel γ\gamma, tree depth) rather than learned from data via gradient descent or MLE.
  • Grid Search: Exhaustive search over every point in a predefined Cartesian hyperparameter grid.
  • Random Search: Monte Carlo sampling of hyperparameter tuples from specified prior distributions for a fixed trial budget n_iter.
  • Log-Uniform Sampling (loguniform): Sampling uniformly in log space so orders of magnitude (e.g., [10−3,10−2,10−1,1][10^{-3}, 10^{-2}, 10^{-1}, 1]) receive equal sampling density rather than clustering near the upper bound.
  • Cross-Validation: Evaluates each hyperparameter candidate cleanly across training folds without touching the held-out test set.

Example

Suppose we tune an RBF SVM’s regularization C ∈[0.1,100]\in [0.1, 100] and kernel scale gamma ∈[0.001,1.0]\in [0.001, 1.0] with a budget of 16 evaluations. Grid search tests a 4×44 \times 4 mesh (C in [0.1, 1, 10, 100], gamma in [0.001, 0.01, 0.1, 1]), meaning if gamma dominates accuracy on a dataset, the grid only examines 4 distinct values of gamma. Random search with n_iter=16 over log-uniform priors tests 16 unique values of gamma (and 16 unique values of C), dramatically increasing the chance of hitting a high-performing region within the same budget.

Code Implementation

from scipy.stats import loguniform
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

# Generate synthetic dataset
X, y = make_classification(
    n_samples=500, n_features=4, n_informative=3, n_redundant=0, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Wrap scaling and SVC in a Pipeline to avoid data leakage across CV folds
pipe = make_pipeline(StandardScaler(), SVC(kernel='rbf', random_state=42))

# 1. Grid Search (4 x 4 = 16 combinations)
param_grid = {
    'svc__C': [0.1, 1, 10, 100],
    'svc__gamma': [1.0, 0.1, 0.01, 0.001],
}
grid_search = GridSearchCV(pipe, param_grid, cv=5, refit=True)
grid_search.fit(X_train, y_train)
print("Grid search best params:", grid_search.best_params_)

# 2. Random Search with matching budget (n_iter=16) and log-uniform priors
param_distributions = {
    'svc__C': loguniform(1e-1, 1e2),
    'svc__gamma': loguniform(1e-3, 1e0),
}
random_search = RandomizedSearchCV(
    pipe, param_distributions, n_iter=16, cv=5, random_state=42, refit=True
)
random_search.fit(X_train, y_train)
print("Random search best params:", random_search.best_params_)

# Evaluate both tuned models on the held-out test set
grid_acc = accuracy_score(y_test, grid_search.best_estimator_.predict(X_test))
rand_acc = accuracy_score(y_test, random_search.best_estimator_.predict(X_test))
print(f"Grid Search Test Accuracy:   {grid_acc:.4f}")
print(f"Random Search Test Accuracy: {rand_acc:.4f}")
  • Bayesian Optimization (TPE / Gaussian Processes): Builds a probabilistic surrogate model of validation score vs. hyperparameters (using acquisition functions like Expected Improvement) to focus evaluations on promising regions—often outperforming random search when evaluations are expensive.
  • Successive Halving & Hyperband: Multi-fidelity algorithms that allocate small training budgets to many random configurations and promote only the top performers to full training.
  • Coarse-to-Fine Tuning: Commonly combines broad random search in log space followed by localized grid or Bayesian refinement around promising regions.
  • Nested Cross-Validation: Prevents optimistic bias from tuning hyperparameters on the same CV score used to report final model generalization.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.