Optuna

On this page 8

Optuna is an open-source Python framework for hyperparameter optimization that searches automatically for the model settings, such as learning rate, tree depth or layer count, that give the best validation score. Among AI frameworks & tools, it sits beside training libraries such as PyTorch, LightGBM and scikit-learn rather than replacing them: the training code stays the same, and Optuna decides which configuration to try next.

Developed at Preferred Networks and released under the MIT license, Optuna is known for its define-by-run API, in which the search space is written as ordinary Python code inside the objective function. Its combination of adaptive samplers, early pruning of weak trials and shared storage for parallel workers makes it a common default for tuning work in machine learning teams.

Optuna organizes every search as a study that repeatedly calls a user-written objective function. Each call is a trial: the function receives a trial object, asks it for parameter values, trains and evaluates a model, and returns a score that the study will minimize or maximize.

Parameters are requested with methods such as trial.suggest_float, trial.suggest_int and trial.suggest_categorical. Because these calls run inside normal Python, the space can be conditional: a trial that picks a gradient-boosted model asks for tree depth, while a trial that picks a neural network asks for the number of layers. This is the practical meaning of define-by-run, and it removes the need for a separate configuration language.

The following table lists the core objects and the role each plays during optimization.

ObjectRoleTypical call
StudyHolds all trials and the optimization directionoptuna.create_study(direction="maximize")
TrialOne evaluation of one parameter settrial.suggest_float("lr", 1e-5, 1e-1, log=True)
SamplerChooses the next parameter valuesTPESampler(seed=42)
PrunerStops unpromising trials earlyMedianPruner(n_warmup_steps=5)
StoragePersists results for resumption and sharingsqlite:///study.db
Core objects in an Optuna study

Samplers and the search strategy

A sampler decides which point in the search space each new trial evaluates, and the choice has the largest effect on how quickly good settings appear. The default is the Tree-structured Parzen Estimator (TPE), a Bayesian method that models the density of good and poor results separately and proposes values where the ratio favors good outcomes.

Most samplers begin with a short phase of random startup trials, often about ten, before their model has enough data to guide the search. The table below compares the main built-in samplers and when each fits.

SamplerMethodBest suited to
TPESamplerBayesian density estimationGeneral default, mixed and conditional spaces
CmaEsSamplerCovariance matrix adaptation evolution strategyContinuous spaces with many trials
GPSamplerGaussian process regressionSmall budgets of expensive trials
NSGAIISamplerGenetic multi-objective algorithmTrading accuracy against latency or size
RandomSamplerUniform random drawsBaselines and very wide early exploration
GridSamplerExhaustive gridSmall, fully discrete spaces
QMCSamplerQuasi-Monte Carlo sequencesEven coverage of continuous ranges
Built-in Optuna samplers compared

For multi-objective optimization, a study is created with several directions, and Optuna returns a Pareto front of trials in which no objective can improve without another getting worse. This is useful when a smaller, faster model may be preferable to a slightly more accurate one.

Pruning unpromising trials

Pruning stops a trial early when its intermediate results show it is unlikely to beat earlier trials, which saves the largest share of compute in deep learning and boosting work. The objective reports progress with trial.report(value, step) after each epoch or boosting round, then calls trial.should_prune(); if the answer is true, it raises optuna.TrialPruned.

Pruners differ in how aggressively they cut. The table summarizes the common options and their main risk.

PrunerDecision ruleMain risk
MedianPrunerStops a trial below the median of earlier trials at the same stepCuts slow starters too early without warm-up
PercentilePrunerSame idea with a configurable percentileToo strict a percentile discards good runs
SuccessiveHalvingPrunerKeeps the top fraction at each resource rungSensitive to the minimum resource setting
HyperbandPrunerRuns several halving brackets in parallelMore settings to understand
NopPrunerNever prunesNo savings, useful only as a control
Common pruners and their behavior

Warm-up settings such as n_startup_trials and n_warmup_steps matter in practice. Learning curves often cross, so a model with a slow first few epochs can still finish best, and pruning before the curves stabilize can remove it.

Storage, parallelism and analysis

By default a study lives in memory and disappears when the process ends. Passing a database URL creates a relational storage backed by SQLite, PostgreSQL or MySQL, and a journal storage writes an append-only log file; both allow a study to be resumed after a crash and shared by several workers.

Parallel search works in two ways. The n_jobs argument runs threads in one process, which helps mainly when training releases the Python lock. For real scale, many processes or machines connect to one storage and call study.optimize independently, each loading the study by name. Optuna also integrates with cluster tools, including Ray, when scheduling is handled elsewhere.

Results can be inspected with built-in visualization functions and the separate optuna-dashboard web application. The table shows what each common view answers.

ViewQuestion answeredTypical use
Optimization historyIs the search still improving?Deciding when to stop
Parameter importancesWhich settings change the score most?Shrinking the space for the next study
Contour plotHow do two parameters interact?Spotting coupled settings such as learning rate and batch size
Parallel coordinatesWhich combinations produce good trials?Explaining results to a team
Intermediate valuesHow did pruned trials behave?Checking pruner aggressiveness
Analysis views and the questions they answer

Optuna is a dedicated optimization engine, while many neighboring tools treat tuning as one feature among others. Grid and random search classes in scikit-learn are simple but do not learn from past results. Ray Tune focuses on distributed scheduling and can use Optuna as its search algorithm. Experiment trackers such as MLflow and Weights & Biases record runs; Weights & Biases also offers sweeps, but Optuna is often logged into these trackers rather than replacing them.

Integration callbacks for PyTorch Lightning, XGBoost, LightGBM and Keras report intermediate values automatically, and the integration package also provides a stepwise LightGBM tuner that tunes the most influential parameters first.

Limitations and common mistakes

Optuna improves the search, but it cannot correct a flawed evaluation. The most damaging mistakes concern data and statistics rather than the library itself:

  • Tuning on the test set leaks information and produces optimistic scores; keep a separate holdout that the study never sees.
  • Noisy objectives from a single small validation split let the sampler chase luck; cross-validation or repeated seeds reduce this.
  • Linear scales for wide ranges waste trials; learning rates and regularization strengths usually need log=True.
  • Oversized search spaces with dozens of parameters dilute the budget; importance plots help remove weak dimensions.
  • SQLite under heavy parallel load causes lock contention; a server database or journal storage scales better.

Finally, the best trial is itself a noisy estimate. Retraining the chosen configuration with several seeds before deployment confirms that the gain is real.

Stripped to the essentials

Every machine learning model has dials that someone must set before training. Examples are how fast it learns or how large it grows. Optuna turns those dials for you. It tries a setting, checks the score, and uses what it learned to choose the next setting.

It also quits bad attempts early. Think of a cooking contest where the judges taste each dish halfway through and stop the ones that are clearly failing. The kitchen saves time and ingredients for better recipes. The result is a good model in fewer tries.

Where it is applied

A data science team at an online retailer trains a LightGBM model to forecast product returns. Hand tuning had reached an area under the curve of about 0.81, and each training run takes roughly four minutes on a full year of orders. The team defines an objective that suggests learning rate on a log scale from 0.005 to 0.3, the number of leaves from 16 to 256, and feature and row sampling fractions, then scores each trial with five-fold cross-validation.

They create a study with the TPE sampler and a median pruner stored in PostgreSQL, and four cloud machines run trials in parallel overnight. Of 400 trials, about 60 percent are pruned after the first folds, so the full search costs far less than 400 complete runs. The best configuration reaches roughly 0.84, and the importance plot shows that the number of leaves and the learning rate explain most of the gain. After confirming the result on an untouched holdout month, the team deploys the model and keeps the study database for the next quarterly retraining.