Optuna Tutorial: Hyperparameter Optimization in Python, Step by Step
Optuna tutorial in Python: build a study, tune Random Forest and XGBoost, prune trials on a real run, read the results and resume a study, step by step.
This Optuna tutorial takes you from a first study to a pruned, resumable search, using the same dataset and seed as the rest of the hyperparameter tuning series. You will build a study, tune a Random Forest and an XGBoost model, watch pruning stop bad trials early on a real run, read the results, and save and resume your work. Every number comes from a run described in the article, so you can reproduce it. If you are choosing between methods first, read Optuna vs GridSearchCV. If grid search is new to you, start with GridSearchCV Explained.
What Optuna is: study, trial and objective
Optuna is a Python library for hyperparameter optimization. You describe how to score one set of hyperparameters, and Optuna decides which sets to try next. Three terms cover almost everything:
- Objective: a function you write. It receives a
trial, asks it for hyperparameter values, trains and scores a model, and returns one number. - Trial: one call of the objective, with one set of suggested values and its result.
- Study: the whole optimization session. It holds every trial, the direction (
"maximize"or"minimize"), the sampler that proposes values, and the pruner that stops weak trials.
Optuna is define-by-run: the search space is created while your objective executes, through calls like trial.suggest_float(...). That means the space can contain ordinary Python logic. You can suggest a kernel first, and only then suggest the parameters that kernel needs, with no pre-declared dictionary to keep in sync. It also means a typo in a parameter name creates a new parameter rather than an error, so keep names consistent.
Install and run your first study
pip install optuna scikit-learn xgboost plotly
The versions used for every run in this article: Python 3.12.3, Optuna 5.1.0, scikit-learn 1.9.1, XGBoost 3.4.1, Plotly 7.2.0, NumPy 2.5.4. The data setup is the same as in the earlier articles: the Breast Cancer Wisconsin dataset (569 samples, 30 features), an 80/20 stratified split with random_state=42, giving 455 training and 114 test samples. Run this once at the top of your script or notebook:
import time
import numpy as np
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
optuna.logging.set_verbosity(optuna.logging.WARNING) # quieter output
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
)
Now the first study. The model is the scaled SVC from the earlier articles, tuning C and gamma:
def objective(trial):
C = trial.suggest_float("C", 0.1, 100, log=True)
gamma = trial.suggest_float("gamma", 1e-3, 1, log=True)
model = make_pipeline(StandardScaler(), SVC(C=C, gamma=gamma))
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(direction="maximize",
sampler=optuna.samplers.TPESampler(seed=42))
study.optimize(objective, n_trials=30)
print(study.best_params, study.best_value)
Line by line:
trial.suggest_float("C", 0.1, 100, log=True)asks for a value between 0.1 and 100, sampled on a log scale. The string"C"is the parameter’s name in the study.- The model is built from the suggested values inside a pipeline, so the scaler is fitted per fold. This is the leakage-safe pattern from the GridSearchCV article.
cross_val_score(...).mean()is the single number the objective returns: mean 5-fold accuracy on the training set. The test set is never touched during tuning.create_study(direction="maximize")says higher is better. Forgetting this is the most common beginner mistake, because the default is"minimize".TPESampler(seed=42)fixes the sampler’s randomness so your run matches this one. TPE is already the default sampler; passing it only sets the seed.study.optimize(objective, n_trials=30)runs 30 trials.best_paramsandbest_valueread the winner.
Result of this run: 30 trials in 1.14 s. Best parameters C ≈ 80.886 and gamma ≈ 0.001329, best CV accuracy 0.9780, found at trial number 10 (the 11th trial, since numbering starts at 0). This is the same optimum the seed-42 Optuna run found in the comparison article, because the seed and the first trials are identical. No later trial in the 30 beat it.
Tuning a Random Forest step by step
Optuna has a suggest method for each kind of hyperparameter:
suggest_int(name, low, high, step=1, log=False)for whole numbers such asmax_depth.suggest_float(name, low, high, step=None, log=False)for continuous values.suggest_categorical(name, choices)for a fixed list such as["gini", "entropy"].
from sklearn.ensemble import RandomForestClassifier
def rf_objective(trial):
params = dict(
n_estimators=trial.suggest_int("n_estimators", 50, 300, step=50),
max_depth=trial.suggest_int("max_depth", 2, 20),
min_samples_leaf=trial.suggest_int("min_samples_leaf", 1, 10),
max_features=trial.suggest_float("max_features", 0.1, 1.0),
)
model = RandomForestClassifier(**params, random_state=42, n_jobs=1)
return cross_val_score(model, X_train, y_train, cv=5).mean()
rf_study = optuna.create_study(direction="maximize",
sampler=optuna.samplers.TPESampler(seed=42))
start = time.perf_counter()
rf_study.optimize(rf_objective, n_trials=40)
print(f"{time.perf_counter() - start:.2f}s", rf_study.best_params, rf_study.best_value)
Result: 40 trials in 45.90 s (forests are much slower than the SVC). Best parameters: n_estimators=100, max_depth=17, min_samples_leaf=2, max_features ≈ 0.306. Best CV accuracy 0.9670, found at trial 35. Retrained on the training set and scored once on the held-out test set, this forest scored 0.9561. That test figure is for information only. It was not used to choose anything, and you should not use a single 114-sample test score to pick between model families.
Notice that the tuned forest (0.9670) trails the tuned SVC (0.9780) on this dataset. Tuning moves a model within its own ceiling. Choosing a suitable model matters more than squeezing the last hyperparameter.
Why log=True matters
Many hyperparameters span orders of magnitude: learning rates, regularization strengths, C, gamma. Sampling them uniformly wastes the search. Take a learning rate between 0.001 and 0.3. Uniform sampling puts a fraction (0.01 − 0.001) / (0.3 − 0.001) ≈ 3.0% of its samples below 0.01, even though that decade is where many good small-step values live. Log-uniform sampling gives ln(10) / ln(300) ≈ 40.4% to the same region. We checked this by drawing 100,000 samples each way: 0.030 and 0.405. A rule of thumb: if the sensible range spans more than about one order of magnitude, use log=True. Two limits to remember: low must be above zero, and you cannot combine log=True with step.
Tuning XGBoost with cross-validation inside the objective
Gradient-boosted trees have more hyperparameters and several are log-scale, so this is where Optuna is typically used. Put the cross-validation inside the objective so that one number summarises five fits, as for the forest:
from xgboost import XGBClassifier
def xgb_objective(trial):
params = dict(
n_estimators=trial.suggest_int("n_estimators", 100, 400, step=50),
learning_rate=trial.suggest_float("learning_rate", 1e-3, 0.3, log=True),
max_depth=trial.suggest_int("max_depth", 2, 8),
subsample=trial.suggest_float("subsample", 0.5, 1.0),
colsample_bytree=trial.suggest_float("colsample_bytree", 0.5, 1.0),
reg_lambda=trial.suggest_float("reg_lambda", 1e-3, 10.0, log=True),
)
model = XGBClassifier(**params, tree_method="hist", random_state=42, n_jobs=1)
return cross_val_score(model, X_train, y_train, cv=5).mean()
xgb_study = optuna.create_study(direction="maximize",
sampler=optuna.samplers.TPESampler(seed=42))
xgb_study.optimize(xgb_objective, n_trials=40)
print(xgb_study.best_params, xgb_study.best_value)
Result: 40 trials in 20.12 s. Best parameters: n_estimators=100, learning_rate ≈ 0.1398, max_depth=6, subsample ≈ 0.854, colsample_bytree ≈ 0.510, reg_lambda ≈ 7.58. Best CV accuracy 0.9780, found at trial number 1. The test accuracy of this model, scored once, was 0.9474.
The honest reading is that the search found its best score almost immediately, and trials 2 to 39 never improved it. The running best was 0.9714 after trial 0 and 0.9780 after trial 1. On a small, easy dataset the landscape is flat, many settings score about the same, and extra trials buy nothing. Plot the best-so-far curve before you pay for more trials. Cross-validation inside the objective also makes every trial five times as expensive as a single validation split, which is exactly why pruning, next, needs a different setup.
Pruning: stopping bad trials early
Pruning means abandoning a trial before it finishes because its intermediate results already look worse than earlier trials at the same point. It only works for iterative models, where you can measure progress along the way: epochs of a neural network, or boosting rounds in XGBoost. A model that fits in one shot, like the SVC, has no intermediate results to report. The mechanism has three parts:
trial.report(value, step)tells Optuna the current score at a step (a boosting round here).trial.should_prune()asks the study’s pruner whether to stop.raise optuna.TrialPruned()ends the trial. Optuna records it as pruned, not failed.
Setup. For pruning we switch from 5-fold CV to a single validation split taken from the training set (341 train, 114 validation, random_state=42), and we minimise validation log loss. A smooth continuous metric gives the pruner cleaner signals than accuracy, which moves in steps. The test set stays untouched. We train for up to 300 rounds, and XGBoost lets us hook into each round with a callback:
import xgboost as xgb
X_tr, X_val, y_tr, y_val = train_test_split(
X_train, y_train, test_size=0.25, stratify=y_train, random_state=42
)
dtrain = xgb.DMatrix(X_tr, label=y_tr)
dval = xgb.DMatrix(X_val, label=y_val)
MAX_ROUNDS = 300
class PruningCallback(xgb.callback.TrainingCallback):
def __init__(self, trial):
self.trial = trial
def after_iteration(self, model, epoch, evals_log):
self.trial.report(evals_log["validation"]["logloss"][-1], step=epoch)
if self.trial.should_prune():
raise optuna.TrialPruned()
return False # False means: keep training
def pruned_objective(trial):
params = {
"objective": "binary:logistic", "eval_metric": "logloss",
"tree_method": "hist", "seed": 42, "nthread": 1,
"learning_rate": trial.suggest_float("learning_rate", 1e-3, 0.3, log=True),
"max_depth": trial.suggest_int("max_depth", 2, 8),
"subsample": trial.suggest_float("subsample", 0.5, 1.0),
"colsample_bytree": trial.suggest_float("colsample_bytree", 0.5, 1.0),
"reg_lambda": trial.suggest_float("reg_lambda", 1e-3, 10.0, log=True),
}
history = {}
xgb.train(params, dtrain, num_boost_round=MAX_ROUNDS,
evals=[(dval, "validation")], evals_result=history,
verbose_eval=False, callbacks=[PruningCallback(trial)])
return history["validation"]["logloss"][-1]
def run(pruner, seed=42, n_trials=50):
study = optuna.create_study(direction="minimize", pruner=pruner,
sampler=optuna.samplers.TPESampler(seed=seed))
start = time.perf_counter()
study.optimize(pruned_objective, n_trials=n_trials)
rounds = sum(t.last_step + 1 for t in study.trials if t.last_step is not None)
return study, time.perf_counter() - start, rounds
no_prune, t_np, r_np = run(optuna.pruners.NopPruner())
pruned, t_p, r_p = run(optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=20))
The pruner here is MedianPruner: it stops a trial if its value at a step is worse than the median of earlier trials at that step. Its two key settings:
n_startup_trials=5: the first five trials are never pruned, so the pruner has a baseline to compare with. (This is the pruner’s own setting. It is separate from the sampler’sn_startup_trials, described in the TPE section.)n_warmup_steps=20: no trial is pruned during its first 20 rounds, because early curves are noisy. The library default is 0; we chose 20 for this problem.
Results, seed 42, 50 trials each:
| Pruner | Time | Boosting rounds run | Pruned | Completed | Best validation log loss |
|---|---|---|---|---|---|
NopPruner (no pruning) |
8.54 s | 15,000 | 0 | 50 | 0.0896 (trial 44) |
MedianPruner(5, 20) |
6.27 s | 9,993 | 18 | 32 | 0.0923 (trial 42) |
Without pruning, 50 trials × 300 rounds = 15,000 rounds. With pruning, 18 trials were stopped early and the total fell to 9,993 rounds, about a third fewer, at the cost of a slightly worse best score.
One seed can mislead, so we repeated both setups across 10 seeds (0 to 9, the seed controlling the sampler):
| Pruner | Mean time | Mean rounds | Mean pruned trials | Mean best log loss | Range of best |
|---|---|---|---|---|---|
| None | 7.74 s | 15,000 | 0 | 0.0950 | 0.0913 to 0.1060 |
| MedianPruner(5, 20) | 4.88 s | 8,451 | 24.6 | 0.0961 | 0.0922 to 0.1025 |
Pruning cut the rounds trained by 43.7% and the wall-clock time by 37.0% (rounds are the more reliable figure, since timings vary run to run). The mean best log loss was 0.0011 worse with pruning.
When pruning hurts
Pruning is a bet that a trial’s early performance predicts its final performance. The bet can lose. In 5 of the 10 seeds the pruned search ended with a better or equal best score. In the other 5 it ended worse by more than 0.001, which is why the mean is slightly worse. The classic worry is a slow starter, for example a very low learning rate that looks poor at round 20 but would finish best. We checked this for seed 42 by re-running all 18 pruned trials to completion: none of them would have beaten the best score the pruned study found (the best of them reached 0.0945 against 0.0923), and pruned trials did not skew towards small learning rates here (4 of 18 pruned trials had a learning rate below 0.02, against 4 of 32 completed trials). So in this run the small loss was not caused by pruning a would-be winner. A likely explanation, which we did not test, is that the pruned study followed a different search path, because pruned trials give the sampler different information. The slow-starter risk is real in general, but we did not see it on this dataset. To reduce the risk, raise n_warmup_steps, use n_startup_trials to build a baseline, or skip pruning when each trial is cheap. Pruning pays off when trials are long, and this is a small example.
Reading the study
After optimize, the study object holds everything:
print(rf_study.best_params) # dict of the winning values
print(rf_study.best_value) # its score: 0.9670 here
print(rf_study.best_trial.number) # which trial: 35 here
df = rf_study.trials_dataframe()
print(df.columns.tolist())
print(df[["number", "value", "params_max_depth", "params_n_estimators", "state"]].head())
The dataframe has one row per trial. In this version its columns were number, value, datetime_start, datetime_complete, duration, one params_* column per hyperparameter, a system_attrs_* column from the sampler, and state. The first rows of the forest study:
| number | value | params_max_depth | params_n_estimators | state |
|---|---|---|---|---|
| 0 | 0.9560 | 20 | 150 | COMPLETE |
| 1 | 0.9495 | 4 | 50 | COMPLETE |
| 2 | 0.9582 | 15 | 200 | COMPLETE |
| 3 | 0.9582 | 6 | 250 | COMPLETE |
| 4 | 0.9604 | 11 | 100 | COMPLETE |
The state column is how you see pruned trials in a pruning study: COMPLETE, PRUNED or FAIL. Optuna also computes how much each hyperparameter mattered:
print(optuna.importance.get_param_importances(rf_study))
For the forest: min_samples_leaf 0.519, max_features 0.229, n_estimators 0.130, max_depth 0.123. For XGBoost: subsample 0.262, reg_lambda 0.225, learning_rate 0.149, n_estimators 0.141, max_depth 0.127, colsample_bytree 0.096. Read these as hints, not facts. They come from 40 trials on a flat landscape where most settings score within a point or two of each other, so the ranking is unstable. Importances are most useful on a large study with a real spread of scores, where they tell you which parameters to narrow next.
For plots, Optuna ships Plotly-based figures:
optuna.visualization.plot_optimization_history(xgb_study).show()
optuna.visualization.plot_param_importances(xgb_study).show()
The optimization history plots each trial’s value with the best-so-far line, the quickest way to see that a study has stopped improving, as the XGBoost study did after trial 1. The importance plot is a bar chart of the numbers above.
TPE explained simply
Optuna’s default sampler is the Tree-structured Parzen Estimator (TPE), introduced by Bergstra and colleagues in 2011. The idea needs no heavy maths:
- Start random. The first trials are sampled at random. In Optuna 5.1.0 the default is
n_startup_trials=10, which we confirmed from the library’s signature. This is why tiny budgets get little from TPE: with 16 trials, only the last 6 are guided. - Split the history. After the start-up phase, TPE sorts finished trials by score and divides them into a “good” group (the best fraction) and a “bad” group (the rest).
- Model each group. For each hyperparameter it fits a smooth density to the good trials, called l(x), and another to the bad ones, g(x). Picture two overlapping hills along the axis for, say,
log C: one where good trials sit, one where bad trials sit. - Propose where good is likely and bad is not. TPE draws candidate values from l(x) and keeps the one with the highest ratio l(x) / g(x). A high ratio means “this value looks like the good trials and unlike the bad ones”. Under TPE’s assumptions, maximising this ratio is equivalent to maximising expected improvement, the expected amount by which a new trial would beat the current threshold. That is the whole intuition.
The default draws 24 candidates (n_ei_candidates=24) per suggestion. The key consequence is that TPE concentrates trials near promising regions but still explores, because the density of good trials has spread. Early on it behaves almost randomly, and it improves as evidence accumulates. A full treatment, including how surrogate models and Gaussian processes relate to this, is reserved for a later article on Bayesian optimization.
Saving, loading and resuming a study
Give a study a name and a storage URL and it is saved to disk as it runs. SQLite needs no server:
URL = "sqlite:///tutorial.db"
study = optuna.create_study(study_name="svc-tutorial", storage=URL,
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=42))
study.optimize(objective, n_trials=20)
# Later, or in another process:
study = optuna.load_study(study_name="svc-tutorial", storage=URL,
sampler=optuna.samplers.TPESampler(seed=43))
study.optimize(objective, n_trials=10) # adds 10 more trials
print(len(study.trials), study.best_value, study.best_params)
Result: the first run finished with 20 trials and a best of 0.9780. Loading the study returned the same 20 trials. After 10 more, it held 30 trials, and the best improved to 0.9802 at C ≈ 78.20 and gamma ≈ 0.001029. I passed a new sampler seed when loading (43), because the sampler’s random state is not restored, so the continuation is not identical to one uninterrupted 30-trial run. The same 0.9802 score appeared as the best in the grid-search article at a different point, which is another sign of a broad plateau.
Common errors and fixes
These are the messages we reproduced in Optuna 5.1.0:
| Symptom | Cause | Fix |
|---|---|---|
DuplicatedStudyError: Another study with study_name=... already exists |
create_study with a name that is already in the storage |
Pass load_if_exists=True, or use load_study |
ValueError: CategoricalDistribution does not support dynamic value space |
Changed the list of choices of a categorical parameter inside one study | Keep the choices fixed, or start a new study |
ValueError: low > 0 must hold for log=True |
A log-scaled range that includes zero | Use a positive lower bound |
ValueError: The parameter step is not supported when log is true |
step combined with log=True |
Drop one of them |
Trial ends as FAIL, not a crash |
The objective returned nan or None |
Return a real number; check your metric for empty folds or divergence |
ValueError: No trials are completed yet |
Read best_value or best_params before any trial finished |
Run optimize first |
| Whole run stops on one exception | An error inside the objective propagates | Pass catch=(RuntimeError,) to optimize to mark such trials as failed and continue |
Two more habits that save time: set optuna.logging.set_verbosity(optuna.logging.WARNING) to quiet output, and for parallelism pass n_jobs to optimize (each trial’s model should then use n_jobs=1 to avoid oversubscribing cores).
FAQ
What is Optuna used for?
Optuna automates hyperparameter optimization: you define an objective that returns a score, and it searches for the settings that maximise or minimise it. It works with any library, including scikit-learn, XGBoost and PyTorch.
How many trials should I run?
There is no universal number. TPE starts with 10 random trials by default, so very small budgets are mostly random. Watch the optimization history, and stop when the best-so-far line stays flat for a long stretch, as it did for our XGBoost study.
Is Optuna better than GridSearchCV?
Not automatically. On a small, cheap problem, all methods performed within one training sample of each other in our same-dataset comparison. Optuna’s edge shows with larger spaces, expensive fits and pruning. See Optuna vs GridSearchCV for the timed comparison.
Can Optuna prune any model?
Only models that produce intermediate scores, such as epochs or boosting rounds, can be pruned. A model that fits in one step, like our SVC, cannot.
Should I use log=True?
Yes for parameters that span several orders of magnitude, such as learning rates and regularization strengths. Use plain sampling for parameters like subsample that live in a narrow range.
How do I keep tuning without losing my work?
Use a named study with storage="sqlite:///yourfile.db". You can reload it with load_study and continue with optimize.
Sources
- Bergstra, J., Bardenet, R., Bengio, Y. and Kégl, B. (2011). “Algorithms for Hyper-Parameter Optimization.” NeurIPS 24. (Tree-structured Parzen Estimator.)
- Akiba, T., Sano, S., Yanase, T., Ohta, T. and Koyama, M. (2019). “Optuna: A Next-generation Hyperparameter Optimization Framework.” KDD 2019. (Define-by-run and pruning.)
- Optuna documentation:
create_study,TPESampler,MedianPruner,Trial.report,Trial.should_prune, storage andoptuna.visualization. XGBoost documentation: training callbacks. scikit-learn documentation:cross_val_score.
