pip install optuna★Core library — few deps, pure-Python.pip install optuna-dashboardReal-time web UI for any study/storage.pip install optunahub cmaes scipy torchFeature hub (AutoSampler & more).import optuna★One import;optuna.__version__to check.optuna.logging.set_verbosity(optuna.logging.WARNING)Quiet the per-trial log spam.
def objective(trial): … return loss★Takes atrial, returns the number to optimize.study = optuna.create_study()★A fresh study; default direction is minimize.study.optimize(objective, n_trials=100)★Run the objective 100 times.study.best_params★The winning hyperparameter dict.study.best_valueIts objective value.
create_study(direction="maximize")★Optimize upward (accuracy, reward…).create_study(study_name=…, storage=…)Name + back it with a database.create_study(sampler=…, pruner=…)Swap the search & early-stop strategy.create_study(load_if_exists=True)★Reuse the study if it already exists — resumable.optuna.load_study(study_name=…, storage=…)Reopen a persisted study.optuna.delete_study · copy_studyRemove / duplicate by name.
trial.suggest_float("x", 0.0, 1.0)★Continuous value in[low, high].trial.suggest_float("lr", 1e-5, 1e-1, log=True)★log scale — for anything spanning orders of magnitude.trial.suggest_float("d", 0, 1, step=0.1)Discretized grid of floats.trial.suggest_uniform / loguniformdeprecatedSince v3.0 → usesuggest_float(log=…).
trial.suggest_int("n", 1, 100)Integer in[low, high], inclusive.trial.suggest_int("units", 16, 256, log=True)Log-spaced ints (layer sizes, estimators).trial.suggest_int("k", 0, 10, step=2)Stride the integer range.trial.suggest_categorical("opt", ["adam", "sgd"])★Pick from a fixed list (str/int/float/bool/None).
if opt == "adam": b1 = trial.suggest_float(…)★Conditional params — only sampled when relevant.for i in range(n_layers): trial.suggest_int(f"u{i}",…)Loop to build a variable-depth net; unique names per param.params = trial.paramsDict of values chosen so far this trial.trial.set_user_attr("n_params", m)Attach extra metadata to a trial.
optimize(obj, n_trials=100)★Stop after N trials.optimize(obj, timeout=600)★Stop after 600 s (combine withn_trials).optimize(obj, n_jobs=-1)Threads within one process (mind the GIL).optimize(obj, catch=(ValueError,))Mark trial FAILED & continue instead of crashing.optimize(obj, callbacks=[cb], show_progress_bar=True)Per-trial hooks + a tqdm bar.study.stop()Call inside a callback to halt early.
study.best_trial★FrozenTrial:.value .params .number .user_attrs.study.trials_dataframe()★Every trial as a pandas DataFrame (params_*cols).study.trialsList of allFrozenTrials.for t in study.trials: t.state.nameCOMPLETE · PRUNED · FAIL · RUNNING.study.get_trials(states=(TrialState.COMPLETE,))Filter by state.
samplers.TPESampler()★Default. Tree-structured Parzen — models good vs bad regions.samplers.RandomSampler()Independent random — the honest baseline.samplers.GridSampler(search_space)Exhaustive over a dict of value lists.samplers.CmaEsSampler()CMA-ES — strong for continuous spaces.samplers.GPSampler()Bayesian / Gaussian-process; great at low trial counts.samplers.NSGAIISampler()Evolutionary — the multi-objective workhorse.samplers.QMCSampler · BruteForceSamplerLow-discrepancy quasi-random · full enumeration.
create_study(sampler=samplers.TPESampler(seed=42))★Seed the sampler (not just numpy) for reproducibility.TPESampler(n_startup_trials=10)Random warm-up before the model kicks in.TPESampler(multivariate=True)Model param correlations jointly.module = optunahub.load_module("samplers/auto_sampler")hubThensampler=module.AutoSampler()— picks one for you.
pruners.MedianPruner()★Prune if below the running median at that step.pruners.SuccessiveHalvingPruner()ASHA — give survivors more budget.pruners.HyperbandPruner()★Runs several halving brackets; often the best.pruners.PercentilePruner(25.0)Prune below the p-th percentile.pruners.PatientPruner(wrapped, patience=3)Tolerate a few bad steps first.pruners.ThresholdPruner · WilcoxonPruner · NopPrunerHard cutoff · statistical · disable.
trial.report(interim_value, step)★Send the metric after each epoch/step.if trial.should_prune(): raise optuna.TrialPruned()★You must check and raise it yourself.create_study(pruner=pruners.MedianPruner())Wire the pruner in at study creation.# pruning is single-objective onlynotePruners don't apply to multi-objective studies.
create_study(directions=["minimize", "maximize"])★Objective returns a tuple of values.return loss, model_sizeOne value per direction.study.best_trials★The Pareto-optimal set (no singlebest_trial).optuna.visualization.plot_pareto_front(study)See the trade-off frontier.sampler=samplers.NSGAIISampler()Recommended for many objectives.
trial = study.ask()★Get a trial without an objective function.x = trial.suggest_float("x", -10, 10)Suggest as usual, run your code however you like.study.tell(trial, value)★Hand the result back to the study.study.tell(trial, state=TrialState.PRUNED)Report a failed/pruned outcome manually.
study.enqueue_trial({"lr": 1e-3})Force specific params to be tried first.study.add_trial(optuna.create_trial(…))Inject a fully-formed past result.samplers.PartialFixedSampler({"opt": "adam"}, base)Pin some params, tune the rest.study.set_user_attr("dataset", "v3")Tag study-level metadata.
storage="sqlite:///study.db"★Persist to a file DB — survives restarts.create_study(storage=…, load_if_exists=True)★The resume idiom — reopen & keep going.storages.RDBStorage("postgresql://…")Postgres/MySQL for teams & scale.storages.JournalStorage(…)File/Redis journal — great for NFS & parallel writes.storages.InMemoryStorage()Default — fast, but vanishes at exit.
# same script, many processes★Point them all at one sharedstorage— they cooperate.$ optuna create-study --study-name s --storage …Make the study once, then launch workers.optimize(obj, n_jobs=4)Thread-level parallelism inside one process.storages.GrpcStorageProxy(…)gRPC proxy to cut DB contention at scale.
plot_optimization_history(study)★Best-value-so-far over trials.plot_param_importances(study)★Which hyperparameters actually mattered.plot_slice · plot_contourPer-param sweeps · pairwise interactions.plot_parallel_coordinate(study)All params + value on parallel axes.plot_intermediate_values · plot_timelineLearning curves · when each trial ran.from optuna.visualization import matplotlibPlotly by default; this gives a Matplotlib backend.
optuna.importance.get_param_importances(study)★fANOVA / MDI importance as a dict.from optuna.integration import OptunaSearchCVDrop-in scikit-learn search estimator.LightGBMPruningCallback · XGBoostPruningCallbackPruning hooks for boosting libs (inoptuna-integration).callbacks=[MLflowCallback(…) / WeightsAndBiasesCallback(…)]Log every trial to your tracker.optuna.artifacts.upload_artifact(…)Attach files (models, plots) to a trial.
$ optuna-dashboard sqlite:///study.db★Live web UI: history, importance, tables.$ optuna studies --storage sqlite:///study.dbList studies from the shell.$ optuna create-study --direction maximize …Make a study without writing Python.storages.RetryFailedTrialCallback(…)Auto-retry trials killed by dead workers.