Stop 10 · Model Evaluation & TuningTopics · 7/9

Bayesian Optimization With Optuna

Part of the Machine Learning Roadmap

In short

Grid search tries every combination blindly, and random search tries them at random. Bayesian optimisation learns from each trial and spends the next one where good results are most likely. Optuna makes it a few lines of code.

Bayesian optimisation uses the results of earlier trials to choose promising settings next, so it finds good hyperparameters in fewer runs. Optuna makes this easy with a simple objective function, pruning of bad trials and helpful plots.

The jaadu at a roadside chai stall tastes from a row of small clay cups, adjusting a pinch of ginger over a steaming kettle.

Think of it like this

Perfecting the chai

You're tuning your chai: amount of ginger, sugar, boiling time. Grid search would brew all 125 combinations. A smart chaiwala tastes one cup, notices 'more ginger was better', and tries the next cup in that direction. After 20 cups he's close to perfect. Optuna is that chaiwala: each result guides the next guess.

Watch it happen

Three ways to search hyperparameters

Grid and random search

  • Grid tries every combination: 5 × 5 × 5 = 125 runs.
  • Random search samples settings blindly, which is often better than grid.
  • Neither learns from earlier trials.

Bayesian (Optuna TPE)

  • Builds a model of which settings tend to score well.
  • Samples more often from promising regions, while still exploring.
  • Prunes trials that look bad early, saving compute.

For more than two or three hyperparameters, or slow models, Bayesian search usually finds good settings in far fewer trials.

The big ideas

What you need to know

An objective function

You write a function that takes a trial, suggests hyperparameters, trains, and returns a validation score.

Define the search space

trial.suggest_int, suggest_float (with log=True for learning rates) and suggest_categorical describe what to try.

Pruning saves time

Report intermediate scores and Optuna stops trials that are clearly worse than earlier ones.

Learn from the plots

Optimisation history and parameter importance plots show which settings matter and when the search levelled off.

See it in code

Walk through the code

python
1import optuna2from sklearn.datasets import load_breast_cancer3from sklearn.ensemble import GradientBoostingClassifier4from sklearn.model_selection import cross_val_score5 6X, y = load_breast_cancer(return_X_y=True)7 8def objective(trial):9    params = {10        "n_estimators": trial.suggest_int("n_estimators", 50, 500),11        "learning_rate": trial.suggest_float("learning_rate", 0.01, 0.3, log=True),12        "max_depth": trial.suggest_int("max_depth", 2, 6),13        "subsample": trial.suggest_float("subsample", 0.6, 1.0),14    }15    model = GradientBoostingClassifier(random_state=0, **params)16    return cross_val_score(model, X, y, cv=5, scoring="roc_auc").mean()17 18study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=0))19study.optimize(objective, n_trials=40)20 21print(study.best_value)22print(study.best_params)23optuna.visualization.plot_param_importances(study).show()

1/5The objective suggests a value for each hyperparameter. The learning rate is searched on a log scale.

Forty guided trials to tune four gradient boosting hyperparameters.

Save yourself the pain

Common mistakes

Oops

Reporting study.best_value as your final model score.

Do this instead

It's the best of many tries on the same folds, so it's slightly optimistic. Refit with the best params and score once on a held-out test set.

Oops

Searching learning rate on a linear scale from 0.001 to 1.

Do this instead

Use log=True. Most of a linear range is wasted on large values when the good region is near 0.01.

Your mission

Optuna vs grid search

~35 min

Quick check

What makes Bayesian optimisation different from random search?

Go deeper

  1. 1Write an Optuna objective that tunes three LightGBM parameters with cross-validation.
  2. 2Run 50 trials and plot the optimisation history.
  3. 3Compare the best score with your earlier random search.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge