Skip to main content
v2026.11,986 entries · CC-BY 4.0

Optuna: Hyperparameter Optimization Framework for Reproducible Research

How to install Optuna, run and read a study, choose samplers and pruners, and fix seeds and storage so hyperparameter tuning is reproducible.

Written and maintained by CASRAI Editorial Board

Published

On this page

Optuna is an open-source Python package for automatic hyperparameter optimization: you write an objective function that returns a score, and Optuna runs repeated trials, proposing new hyperparameter values from the results of earlier trials. By default it uses the Tree-structured Parzen Estimator (TPE) sampler, minimizes the objective, and keeps results in memory only, so a research workflow needs explicit settings for seeds, storage and pruning before its tuning runs can be repeated or audited.

This guide follows the official Optuna documentation: what the tool is for, how to install it, how to run and read a first study, how to add pruning, which defaults matter for reproducibility, and which problems come up most often. The data table after the body lists the documented defaults and rules in one place.

What Optuna is used for in research

Researchers use Optuna to search for good hyperparameters (learning rates, tree depths, regularization strengths and similar settings that are fixed before training) without hand-tuning each one. The Optuna paper (Akiba, Sano, Yanase, Ohta and Koyama, KDD 2019) describes the framework through three design points: a define-by-run API, efficient search and pruning strategies, and an architecture that scales from a laptop to distributed runs.

Define-by-run means the search space is built while the objective function executes, using calls such as trial.suggest_float inside ordinary Python code. A search space can therefore depend on earlier choices in the same trial, which suits experiments where the model type itself is a tunable choice.

For research practice the value is not only a better score. A study object records every trial, so the search itself becomes an artifact that can be reported, stored and re-examined. Treat that record as part of the methods: the reproducible AI experiment and reproducible research practices entries describe what a repeatable computational study should document, and Optuna’s seed, storage and study-name settings (covered below) are where that documentation starts.

What algorithm does Optuna use?

The default sampler is TPESampler, the Tree-structured Parzen Estimator, which the Optuna tutorial states directly: “The default sampler is TPESampler.” The create_study documentation confirms the same: when sampler is left as None, Optuna uses TPESampler. Optuna ships many other samplers, listed in the sampler table in the next section, and a separate set of pruners that stop unpromising trials early.

Is Optuna Bayesian?

Partly, depending on the sampler and on how strictly you define the term. Optuna’s documentation describes GPSampler as a sampler using “Gaussian process-based Bayesian optimization”, so that sampler is Bayesian optimization by the docs’ own wording. TPE, the default, fits probability models to the trials seen so far and uses them to pick the next values, which is why it is usually grouped with sequential model-based and Bayesian-style optimization; that grouping is an interpretation, not wording taken from the Optuna docs. RandomSampler, GridSampler and QMCSampler do not model earlier results in that way. If a methods section says “Bayesian optimization”, name the exact sampler class so readers know which one ran.

Is Optuna a Python package?

Yes. Optuna is a Python package installed with pip or conda, and you use it by importing optuna in your own scripts or notebooks. The installation page states that Optuna supports Python 3.10 or newer. Because it is a library rather than an application, the objective function that does your actual work is code you write and version yourself.

How to install or access Optuna

The installation page of the official documentation gives these routes:

  1. Recommended: pip install optuna
  2. With conda: conda install -c conda-forge optuna
  3. Development version: pip install git+https://github.com/optuna/optuna.git

Install into a dedicated virtual environment and record the installed version (for example with pip freeze) next to your results. The Optuna FAQ states that Optuna does not support saving and reloading across different Optuna versions with pickle, so the version is not a cosmetic detail: it decides whether a saved study can be reloaded at all.

How to run an Optuna study step by step

The first tutorial in the official documentation minimizes a simple quadratic. The steps below follow it and then add the settings a research run needs.

  1. Import the package. import optuna
  2. Define the objective. The function receives a trial and returns a number. The tutorial’s version is:
    def objective(trial):
        x = trial.suggest_float("x", -10, 10)
        return (x - 2) ** 2
  3. Create the study. study = optuna.create_study(). With no arguments this uses TPESampler, the median pruner, the minimize direction and in-memory storage (see the data table).
  4. Run the trials. study.optimize(objective, n_trials=100)
  5. Read the result. best_params = study.best_params returns a dictionary, so the tutorial reads the tuned value with found_x = best_params["x"].

Because the objective is (x – 2)2 and the default direction is minimize, the best possible value of x is 2, and a sensible run finds a value close to it. That known answer makes the tutorial a useful smoke test for a new environment before you point Optuna at an expensive model.

Choose the direction, sampler and pruner explicitly

The create_study documentation lists the arguments that matter. direction accepts “minimize” or “maximize” and defaults to minimize, so a metric such as accuracy needs direction="maximize". Passing sampler or pruner overrides the defaults. Writing these arguments out, even when they equal the defaults, makes a script self-documenting.

Samplers available in Optuna

The sampler reference lists these classes. Some live in Optuna itself, one in the Optuna-Integration package and one in OptunaHub.

Sampler What the documentation says it is
TPESampler Tree-structured Parzen Estimator; the default
RandomSampler random sampling
GPSampler Gaussian process-based Bayesian optimization
CmaEsSampler CMA-ES through the cmaes library; the docs state it does not support multi-objective optimization
NSGAIISampler and NSGAIIISampler evolutionary samplers named for the NSGA-II and NSGA-III algorithms
GridSampler grid search over values you specify
QMCSampler quasi-Monte Carlo sampling with low-discrepancy sequences
BruteForceSampler and PartialFixedSampler brute-force enumeration, and a wrapper that fixes some parameters while another sampler handles the rest
BoTorchSampler provided by the Optuna-Integration package
AutoSampler provided through OptunaHub

Add pruning to stop weak trials early

Pruning needs an objective that reports intermediate values, such as a validation score after each training epoch. The efficient-optimization tutorial uses three calls: trial.report(intermediate_value, step) to log the value, trial.should_prune() to ask whether to stop, and raise optuna.TrialPruned() to end the trial. Its example trains an SGDClassifier on the Iris data with 100 partial_fit steps across 20 trials and creates the study with optuna.create_study(pruner=optuna.pruners.MedianPruner()). Without trial.report calls, a pruner has nothing to compare, because pruning decisions use the intermediate values reported through Trial.report().

Pruner Documented basis
MedianPruner median stopping rule; the default when no pruner is given
PercentilePruner stops trials that fall below a chosen percentile
SuccessiveHalvingPruner Asynchronous Successive Halving
HyperbandPruner Hyperband; needs a fixed study name to be reproducible
WilcoxonPruner Wilcoxon signed-rank test
ThresholdPruner stops trials that cross a threshold
PatientPruner wraps another pruner and adds tolerance
NopPruner never prunes

The pruner reference states that pruners are intended only for single-objective optimization. A study with several objectives should not rely on them.

Make the run reproducible

Four documented rules decide whether a study can be repeated. First, give the sampler a seed: the FAQ example is sampler = optuna.samplers.TPESampler(seed=10), passed to create_study. Second, avoid parallelism when you need exact repeatability: with n_jobs other than 1 the samplers reseed, and the FAQ states parallel runs are not deterministic; for distributed runs use seed=None or a different seed per process. Third, when using HyperbandPruner, also fix the study_name. Fourth, an objective that is itself non-deterministic (unseeded model initialization, data shuffling) prevents exact reproduction no matter how the sampler is seeded, so seed the model and the data split too.

Report the Optuna version, the sampler and pruner classes with their arguments, the seed, the number of trials and the storage backend. If you also tune a gradient-boosted or scikit-learn model, the existing scikit-learn hyperparameter tuning guide and the XGBoost with scikit-learn guide cover the model side that Optuna would be wrapping.

Keep results between sessions

By default a study lives in memory and disappears when the process ends. The FAQ shows how to persist it: optuna.create_study(study_name="foo_study", storage="sqlite:///example.db"). The create_study reference says the storage argument takes a database URL handled through SQLAlchemy. Re-running that line with the same name raises a DuplicatedStudyError unless you pass load_if_exists=True, which returns the existing study so the search continues from its saved trials.

The FAQ is explicit about limits: it says it would never recommend SQLite for parallel optimization and points to the JournalFileBackend for file-based parallel runs. For an in-memory study, the FAQ describes saving and loading with joblib.dump and joblib.load, with the version caveat noted earlier.

Pass extra arguments to the objective

The objective takes only a trial, so the FAQ gives two ways to supply datasets or bounds: a callable class that stores them, or a lambda such as study.optimize(lambda trial: objective(trial, min_x, max_x), n_trials=100).

How to read the output of an Optuna study

The main result is study.best_params, a dictionary mapping each suggested parameter name to the best value found, as in the tutorial’s best_params["x"]. Treat it as one outcome of one search, not as the single true optimum: with a different seed, sampler or trial budget, the best parameters can differ.

When a pruner stops a trial, the efficient-optimization tutorial shows log lines such as “Trial 5 pruned.”, with the trial number in place of 5. A high share of pruned trials means the pruner is doing its job of saving compute; it does not mean the study failed. When you report results, say how many of the trials were completed versus pruned, because pruned trials never reached the final step and their scores are not comparable to completed ones.

For ML experiments that are later published, store the study (or an export of its trials) with the code release, and give the model-training code a fixed split so the objective values are comparable across trials. The CleanRL guide shows the same habit for reinforcement-learning runs, where seeds and logged results are central to comparing algorithms.

Troubleshooting Optuna

  • DuplicatedStudyError on a second run. The study name already exists in the storage. create_study defaults to load_if_exists=False, which raises this error. Pass load_if_exists=True to continue the existing study, or choose a new name.
  • Results differ between runs despite a seed. Check n_jobs, parallel workers, a HyperbandPruner without a fixed study name, and a non-deterministic objective. The FAQ lists each as a cause.
  • An error inside the objective stops the whole run. The FAQ states that exceptions other than TrialPruned raised in the objective propagate out of study.optimize(), so handle expected failures inside the objective.
  • A saved study will not load after an upgrade. The FAQ says Optuna does not support saving and reloading across different versions with pickle. Use database storage, or reinstall the version that wrote the file.
  • SQLite is slow or errors with several workers. The FAQ advises against SQLite for parallel optimization; use the file-based JournalFileBackend or another database.
  • CmaEsSampler fails on a multi-objective study. The sampler reference says CmaEsSampler does not support multi-objective optimization; choose another sampler such as NSGAIISampler.
  • Pruners do nothing. The objective must call trial.report, and pruners are intended for single-objective studies only.

Free alternatives to Optuna

Optuna searches for hyperparameters by running many trials. When the search is small, or when you work inside scikit-learn, the scikit-learn model-selection tools cover simpler cases. The table lists the tools described in the scikit-learn user guide, plus the built-in Optuna samplers that reproduce the same strategies inside Optuna.

Option What its documentation says When it fits
scikit-learn GridSearchCV Exhaustively generates candidates from a grid of values given in param_grid A small, fully enumerable set of settings for a scikit-learn estimator
scikit-learn RandomizedSearchCV Randomized search where each setting is sampled from a distribution; budget set with n_iter A larger space where a fixed number of random candidates is acceptable
scikit-learn HalvingGridSearchCV and HalvingRandomSearchCV Successive-halving search; documented as experimental and needing an explicit import of enable_halving_search_cv Early elimination of weak candidates, with the caveat that the API may change
Optuna GridSampler or RandomSampler Grid and random strategies inside Optuna Keeping Optuna’s study record and storage while using a simple strategy

The scikit-learn tools work on scikit-learn estimators; Optuna’s define-by-run objective can wrap any code that returns a score. See the scikit-learn hyperparameter tuning guide for the scikit-learn side in depth.

Frequently asked questions

What algorithm does Optuna use?

TPE (Tree-structured Parzen Estimator) is the default sampler, used whenever create_study is called without a sampler. Other samplers, including random, grid, Gaussian-process, CMA-ES, NSGA-II, NSGA-III and quasi-Monte Carlo, can be selected through the sampler argument.

Is Optuna a Python package?

Yes. Install it with pip install optuna or conda install -c conda-forge optuna. The installation page states support for Python 3.10 or newer.

Is Optuna Bayesian?

GPSampler is documented as Gaussian process-based Bayesian optimization. The default TPESampler is a sequential model-based method often grouped with Bayesian-style optimization, but the Optuna documentation does not label it that way, so name the sampler in your methods section instead of the label alone.

Does Optuna minimize or maximize by default?

It minimizes. Set direction="maximize" in create_study for scores where higher is better.

How do I make an Optuna study reproducible?

Seed the sampler (for example TPESampler(seed=10)), avoid parallel workers when exact repetition matters, fix the study name when using HyperbandPruner, and make the objective deterministic.

Sources

Data: Optuna documented defaults and reproducibility rules

Compiled from the official Optuna documentation (create_study reference, FAQ, sampler and pruner references). Each row states one documented default or rule and what it means for a research run. Read 2026-12-03 against the stable documentation.

Optuna documented defaults and reproducibility rules
Setting or componentDocumented default or ruleEffect on a research runDocumentation page
samplerNone means TPESamplerDefault search algorithm is TPE unless a sampler is passedcreate_study reference
prunerNone means MedianPrunerTrials that report intermediate values can be stopped earlycreate_study reference
directionDefaults to minimizeScores where higher is better need direction maximizecreate_study reference
storageNone means in-memory storageStudy is not persisted after the process endscreate_study reference
load_if_existsFalse; a repeated study name raises DuplicatedStudyErrorTrue returns the existing study so the search can continuecreate_study reference
Sampler seedEach sampler accepts a seed; TPESampler(seed=10) is the FAQ exampleFixes the sampler's random choices for repeatable searchesFAQ and sampler reference
n_jobs other than 1Samplers reseed; parallel runs are not deterministicUse seed None or a different seed per process for distributed runsFAQ and sampler reference
HyperbandPrunerNeeds a fixed study_name for reproducibilitySet the study name explicitly when using this prunerFAQ
Pruner scopeIntended only for single-objective optimizationMulti-objective studies should not rely on prunersPruner reference
CmaEsSamplerDoes not support multi-objective optimizationChoose another sampler for several objectivesSampler reference
SQLite storageNot recommended for parallel optimization; JournalFileBackend suggested for file-based parallel runsChoose storage by worker countFAQ
Pickle of a studyNot supported across different Optuna versionsRecord the Optuna version and prefer database storageFAQ

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Optuna: Hyperparameter Optimization Framework for Reproducible Research

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →