Home/ Machine Learning/ Optuna vs GridSearchCV: Which Should You Use? (With the Same Dataset, Timed)
Machine Learning

Optuna vs GridSearchCV: Which Should You Use? (With the Same Dataset, Timed)

Optuna vs GridSearchCV on one dataset: same model, seed and budget, timed. See the results, a verdict table, the budget rule, and a decision flowchart.

Optuna vs GridSearchCV is the choice between a smart search and an exhaustive one. We ran GridSearchCV, RandomizedSearchCV and Optuna on the same dataset, model, scoring and trial budget, and timed all three. The honest result: on this small problem, all three land within one training sample of each other. The case for Optuna rests on situations this experiment is not big enough to show, and we say where those are.

The short answer: which should you use?

Situation Use Why
1–3 hyperparameters, a few values each, cheap fits GridSearchCV Complete, reproducible map of the space; simple to explain
4+ hyperparameters, or wide continuous ranges RandomizedSearchCV or Optuna Cost no longer multiplies with every parameter you add
Expensive fits, tight time budget Optuna Learns from earlier trials; supports pruning of unpromising runs
Iterative models (epochs, boosting rounds) Optuna with pruning Stops bad trials early
You need every combination reported GridSearchCV It is the only one that guarantees full coverage

Quick rule: estimate trials × folds × seconds per fit. If that is affordable and your space is small, a grid is fine. If it is not, or the space is large, use Optuna. The full decision flowchart is further down.

If you need the grid-search basics first, start with GridSearchCV Explained.

How each method searches

Grid search lays a lattice over the search space and tries every point. Cost is the product of the list lengths, and it has no memory: trial 10 learns nothing from trials 1–9.

Random search draws each trial independently from ranges you define. It also has no memory, but your budget no longer depends on how many hyperparameters you have, and it can sample values a coarse grid would skip. Bergstra and Bengio (2012) argue that this is why it often beats grids when only a few hyperparameters really matter.

Optuna defaults to the Tree-structured Parzen Estimator (TPE), a sequential method. After some initial random trials, it splits past trials into “good” and “bad” by score, models where each group’s parameter values tend to fall, and proposes new points that look more like the good group and less like the bad. It concentrates trials near promising regions. The mechanism is explained step by step in the Optuna tutorial.

One practical detail matters for what follows: Optuna’s TPE sampler starts with a number of purely random trials before it begins guiding the search. In the version we used, the default is 10. With a budget of only 16 trials, just the last 6 are model-guided.

Three side-by-side scatter panels of one two-parameter space: 16 evenly spaced grid points, 16 random points spread across the area, and 16 TPE points with the last six clustered around the starred optimum.
The same two-parameter space searched three ways: a fixed 4 × 4 grid, uniform random draws, and TPE points concentrating near the optimum.

The experiment

Everything matches GridSearchCV Explained:

  • Data: Breast Cancer Wisconsin (load_breast_cancer): 569 samples, 30 features. Split 80/20, stratified, random_state=42: 455 training samples, 114 test.
  • Model: Pipeline([StandardScaler, SVC(kernel="rbf")]), tuning C and gamma.
  • Scoring: 5-fold cross-validated accuracy on the training set. The folds are identical for all three methods.
  • Search ranges: C from 0.1 to 100 and gamma from 0.001 to 1, on a log scale. The grid uses log-spaced values over the same bounds.
  • Budgets: two, both with the grid sized to match. 16 trials (grid 4 × 4, the grid from the GridSearchCV article) and 48 trials (grid 8 × 6).
  • Seeds: search seed 42 for the headline run. We then repeated the Random and Optuna arms across 20 seeds (0–19), because a single seed can mislead. The grid is deterministic and needs no repeats.
  • Timing: time.perf_counter() around the search call only. These are single runs on a sandbox machine, and they are noisy (see the results).

Shared setup (run once)

import time
import numpy as np
import optuna
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import (
    train_test_split, GridSearchCV, RandomizedSearchCV, cross_val_score
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

optuna.logging.set_verbosity(optuna.logging.WARNING)

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

pipe = Pipeline([("scaler", StandardScaler()), ("svc", SVC(kernel="rbf"))])

def make_model(C, gamma):
    return Pipeline([
        ("scaler", StandardScaler()),
        ("svc", SVC(kernel="rbf", C=C, gamma=gamma)),
    ])

Arm 1: GridSearchCV

def run_grid(n_c, n_gamma):
    grid = GridSearchCV(
        pipe,
        {"svc__C": list(np.logspace(-1, 2, n_c)),
         "svc__gamma": list(np.logspace(-3, 0, n_gamma))},
        cv=5, scoring="accuracy",
    )
    start = time.perf_counter()
    grid.fit(X_train, y_train)
    return grid, time.perf_counter() - start

grid, t = run_grid(4, 4)          # 16 combinations; use (8, 6) for 48
print(f"{t:.3f}s", grid.best_params_, round(grid.best_score_, 4))

Arm 2: RandomizedSearchCV

def run_random(n_trials, seed):
    rand = RandomizedSearchCV(
        pipe,
        {"svc__C": loguniform(1e-1, 1e2),
         "svc__gamma": loguniform(1e-3, 1e0)},
        n_iter=n_trials, cv=5, scoring="accuracy", random_state=seed,
    )
    start = time.perf_counter()
    rand.fit(X_train, y_train)
    return rand, time.perf_counter() - start

rand, t = run_random(16, seed=42)
print(f"{t:.3f}s", rand.best_params_, round(rand.best_score_, 4))

Arm 3: Optuna

def run_optuna(n_trials, seed):
    def objective(trial):
        C = trial.suggest_float("C", 1e-1, 1e2, log=True)
        gamma = trial.suggest_float("gamma", 1e-3, 1e0, log=True)
        # Same 5 stratified folds GridSearchCV uses for a classifier
        return cross_val_score(
            make_model(C, gamma), X_train, y_train, cv=5, scoring="accuracy"
        ).mean()

    study = optuna.create_study(
        direction="maximize", sampler=optuna.samplers.TPESampler(seed=seed)
    )
    start = time.perf_counter()
    study.optimize(objective, n_trials=n_trials)
    return study, time.perf_counter() - start

study, t = run_optuna(16, seed=42)
print(f"{t:.3f}s", study.best_params, round(study.best_value, 4))

Finally, the test set is evaluated once per final model, for information only. It was never used to choose anything:

best = make_model(**{"C": study.best_params["C"], "gamma": study.best_params["gamma"]})
print("Optuna test accuracy:", round(best.fit(X_train, y_train).score(X_test, y_test), 4))
print("Grid test accuracy:  ", round(grid.score(X_test, y_test), 4))   # grid is already refit

Results

Library versions: Python 3.12.3, scikit-learn 1.9.1, Optuna 5.1.0, SciPy 1.18.1, NumPy 2.5.4. Search seed 42 for Random and Optuna.

Budget 1: 16 trials

Method Trials Total fits Time Best CV accuracy Best parameters Test acc.
GridSearchCV 16 80 (+1 refit) 0.594 s 0.9802 C=10, gamma=0.01 0.9825
RandomizedSearchCV 16 80 (+1 refit) 0.540 s 0.9758 C≈31.43, gamma≈0.00434 0.9737
Optuna (TPE) 16 80 (no refit) 0.599 s 0.9780 C≈80.89, gamma≈0.00133 0.9825
Two bar panels and a summary table comparing GridSearchCV, RandomizedSearchCV and Optuna at 16 trials: best cross-validation accuracy on the left (0.9802, 0.9758, 0.9780), wall-clock time in seconds on the right (0.59, 0.54, 0.60), with 80 fits each in the table.
One run, three searches, same 16-trial budget: best CV accuracy on the left, wall-clock cost on the right, exact figures repeated in the table.

Budget 2: 48 trials

Method Trials Total fits Time Best CV accuracy Best parameters Test acc.
GridSearchCV (8 × 6) 48 240 (+1 refit) 1.881 s 0.9780 C≈13.90, gamma=0.004 0.9825
RandomizedSearchCV 48 240 (+1 refit) 1.906 s 0.9780 C≈20.60, gamma≈0.00170 0.9825
Optuna (TPE) 48 240 (no refit) 1.506 s 0.9780 C≈80.89, gamma≈0.00133 0.9825

Repeating Random and Optuna across 20 seeds

Budget Method Mean best CV acc. Range Mean time Matched or beat the grid’s best Strictly beat the grid’s best
16 Random 0.9777 0.9736–0.9802 0.579 s 4 of 20 0 of 20
16 Optuna 0.9787 0.9780–0.9802 0.538 s 6 of 20 0 of 20
48 Random 0.9786 0.9780–0.9802 1.755 s 20 of 20 5 of 20
48 Optuna 0.9795 0.9780–0.9802 1.509 s 20 of 20 13 of 20

How to read these numbers

The scores are almost indistinguishable. With 455 training samples, one extra correct prediction across the folds changes accuracy by 0.0022. The gap between 0.9780 and 0.9802 is exactly one sample. Fold-to-fold standard deviations in the GridSearchCV article were around 0.016, far larger. Treat every difference in the tables as noise unless it repeats consistently.

The grid won the 16-trial round. That is not a fluke to explain away. The 4 × 4 grid happens to include C=10, gamma=0.01, a good point in a space with a broad plateau, and neither randomised method hit it exactly. A budget of 16 is also too small for TPE to help much: with 10 random start-up trials, the best-so-far trajectory of the seed-42 Optuna run was identical to Random’s for the first six trials, and improved only once, at trial 11 (0.9758 to 0.9780).

At 48 trials the picture tilts slightly toward Optuna. Optuna strictly beat the grid’s best in 13 of 20 seeds, against 5 of 20 for Random. That is modest evidence that TPE focuses trials. But the grid’s own best score dropped from 0.9802 (4 × 4) to 0.9780 (8 × 6), purely because the lattice points landed elsewhere. A grid’s answer depends on where you place the lattice.

Timing is a weak signal here. Repeated runs of the same 80-fit grid, on the same machine, took anywhere from 0.59 s to 0.93 s across my runs. Optuna’s 1.506 s against 1.881 s for the grid at 48 trials may reflect that SVC fits are slower for some hyperparameter values, and the grid includes many of them, but I did not test that. Do not read it as “Optuna is faster.”

Why Optuna wins or loses here

Where it helps:

  • Focus. TPE spends later trials near good regions instead of spreading them evenly, which matters when the space is big and budget small. The 48-trial seed results hint at this.
  • Pruning. For iterative models (neural networks, gradient boosting), Optuna can stop a trial after a few epochs or rounds if it is lagging behind earlier ones. This often saves more time than smarter sampling does. SVC fits in one shot, so there is nothing to prune in this experiment, and we make no pruning claim here. The Optuna tutorial demonstrates pruning on a real iterative model.
  • Continuous ranges. Optuna samples any value in a range, so you are not limited to the points you thought to write down.

Where grid search is genuinely better:

  • Tiny, discrete spaces. If you only have kernel in {"linear", "rbf"} and C in {1, 10}, exhaustive coverage costs 4 combinations. A sampler adds nothing.
  • Full reproducibility. A grid is deterministic, with no seeds to fix and no sampler version to track.
  • Exhaustive reporting. The heatmap from cv_results_ in the GridSearchCV article shows the whole landscape. Optuna’s trials are concentrated by design, so they give a worse map.
  • Low setup cost. No objective function to write.

What this experiment cannot say. We tuned two hyperparameters on a dataset where a fit takes about five milliseconds. That is close to the best case for grid search. It tells you nothing about 8-dimensional spaces, hour-long fits, or pruning.

The budget rule

Before launching any search:

Cost ≈ trials × folds × seconds per fit ÷ parallel workers

Time one fit() first. In the GridSearchCV article’s run, a single fit of this pipeline took about 0.005 s. The 48-trial arms are 48 × 5 = 240 fits, so the estimate is about 1.2 s. The measured times were 1.5–1.9 s, so treat the formula as a lower bound: scoring, cross-validation overhead and, for Optuna, sampling all add time that matters most when fits are tiny.

Choose the budget from what you can afford, then pick the method:

  • Grid: its trial count is set by your lists (4 × 4 = 16, 8 × 6 = 48). You cannot set the budget independently.
  • Random and Optuna: you set n_iter or n_trials directly, or give Optuna a timeout. That is why they suit a fixed budget.

An illustrative example with made-up round numbers: 100 trials × 5 folds × 20 s per fit = 10,000 s, about 2.8 hours on one core. At that scale, pruning bad trials early becomes more valuable than anything about sampling.

Decision flowchart (text form)

Flowchart asking whether the search space is small, then whether the dataset and fits are cheap, then whether fits are expensive or an iterative model needs pruning, leading to GridSearchCV, RandomizedSearchCV or Optuna TPE with a one-line reason each.
Four questions — space size, dataset size, fit cost, pruning — decide between grid, random and TPE search.
START
 │
 ├─ How many hyperparameters, and how many values each?
 │    ├─ 1–3 params, few discrete values ─────────────► Is one fit cheap (seconds or less)?
 │    │                                                   ├─ Yes ─► GridSearchCV
 │    │                                                   └─ No  ─► go to "fit cost" below
 │    └─ 4+ params, or continuous ranges ─────────────► go to "fit cost" below
 │
 ├─ Fit cost and model type?
 │    ├─ Cheap fits, no iterative training ───────────► RandomizedSearchCV (or Optuna)
 │    ├─ Expensive fits, fixed time budget ───────────► Optuna (set n_trials or timeout)
 │    └─ Iterative model (epochs / boosting rounds) ──► Optuna + pruning
 │
 └─ Need every combination reported, or strict
    reproducibility without seeds? ───────────────────► GridSearchCV

This matches the verdict table, and it agrees with the results: on a cheap 2-parameter problem, the grid was as good as anything, and the methods separated only slightly at the larger budget.

FAQ

Is Optuna better than GridSearchCV?

Not automatically. In our run on a cheap, two-parameter problem, all three methods finished within one training sample of each other. Optuna’s advantages (focused search, pruning, continuous ranges) matter more as the search space and fit cost grow.

Is Optuna faster than GridSearchCV?

Not reliably here. For the same number of trials, the total number of fits is identical, so wall-clock times were close and noisy. Optuna saves time mainly through pruning and by needing fewer trials in larger spaces.

When should I use RandomizedSearchCV instead?

When you want a fixed budget over a larger space and prefer to stay inside scikit-learn. It needs no extra library and no objective function, but it does not learn from earlier trials.

Does Optuna replace cross-validation?

No. Optuna searches; you still need a validation method inside the objective. We used cross_val_score with 5 folds, the same as GridSearchCV.

How many trials does Optuna need?

It depends on the problem. By default it begins with random trials before guiding the search (10 in the version we used), so very small budgets get little benefit. Our 16-trial runs show this.

Which one should a beginner learn first?

GridSearchCV, because the results table makes the search space easy to see. Move to Optuna when grids become too expensive, or when you need pruning.

Sources

  • Bergstra, J. and Bengio, Y. (2012). “Random Search for Hyper-Parameter Optimization.” Journal of Machine Learning Research, 13.
  • Bergstra, J., Bardenet, R., Bengio, Y. and Kégl, B. (2011). “Algorithms for Hyper-Parameter Optimization.” NeurIPS 24.
  • Akiba, T., Sano, S., Yanase, T., Ohta, T. and Koyama, M. (2019). “Optuna: A Next-generation Hyperparameter Optimization Framework.” KDD 2019.
  • scikit-learn documentation: GridSearchCV, RandomizedSearchCV, cross_val_score, Pipeline, SVC. Optuna documentation: create_study, TPESampler, suggest_float.
Scroll to Top