Hyperparameter Tuning with Optuna in Python

Tune a model with Optuna: write an objective function, run a study, read the optimization history, importance, slice, and contour plots, and prune slow trials.

To tune hyperparameters with Optuna, write an objective(trial) function that picks values with trial.suggest_float() or trial.suggest_int() and returns a score, then run study = optuna.create_study(direction="maximize") and study.optimize(objective, n_trials=50). The best settings are in study.best_params.

Quick Example

This example tunes a gradient boosting classifier on 1,500 synthetic rows, scoring each trial by 3-fold cross-validated ROC AUC. Install Optuna with pip install optuna. The full set of examples trains well over a thousand models, so expect it to take a few minutes.

import matplotlib.pyplot as plt
import numpy as np
import optuna
from optuna.visualization import matplotlib as optuna_plots
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score, train_test_split

optuna.logging.set_verbosity(optuna.logging.WARNING)

X, y = make_classification(n_samples=1500, n_features=20, n_informative=8,
                           flip_y=0.08, random_state=5)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=5)


def objective(trial):
    params = {
        "learning_rate": trial.suggest_float("learning_rate", 0.005, 0.5, log=True),
        "max_leaf_nodes": trial.suggest_int("max_leaf_nodes", 4, 64, log=True),
        "min_samples_leaf": trial.suggest_int("min_samples_leaf", 5, 100),
        "l2_regularization": trial.suggest_float("l2_regularization", 1e-3, 10,
                                                 log=True),
    }
    model = HistGradientBoostingClassifier(**params, early_stopping=False,
                                           random_state=5)
    return cross_val_score(model, X_train, y_train, cv=3, scoring="roc_auc").mean()


study = optuna.create_study(direction="maximize",
                            sampler=optuna.samplers.TPESampler(seed=5))
study.optimize(objective, n_trials=60)

print("best AUC:", round(study.best_value, 4), "in trial", study.best_trial.number)
print(study.best_params)

optuna_plots.plot_optimization_history(study)
plt.gcf().set_size_inches(8, 4.5)
plt.gcf().tight_layout()
plt.show()

Optuna optimization history over 60 trials, with the best cross-validated AUC rising from 0.916 to 0.944

Each dot is one trial, and the line is the best score so far. The first ten trials are random, then the sampler concentrates on promising regions. The best cross-validated AUC, 0.944, comes at trial 39, and most of the gain over the first trial arrives within 20 trials.

Optuna's Matplotlib plotting functions are marked experimental and print a warning. The same functions in optuna.visualization draw interactive Plotly charts.

Which Hyperparameters Matter? plot_param_importances

plot_param_importances estimates how much of the variation in trial scores each setting explains.

ax = optuna_plots.plot_param_importances(
    study, evaluator=optuna.importance.FanovaImportanceEvaluator(seed=5))
ax.figure.set_size_inches(8, 3.5)
ax.figure.tight_layout()
plt.show()

Optuna hyperparameter importance chart: learning rate 0.68, L2 regularization 0.19, minimum samples per leaf 0.11 and maximum leaf nodes 0.01

learning_rate accounts for most of the difference between trials, and max_leaf_nodes for very little. These figures describe the ranges you searched: a parameter given a narrow range will look unimportant. The fANOVA evaluator is random, so pass a seed to repeat the numbers.

See Where Good Values Are with plot_slice

A slice plot draws each trial's score against one parameter. Darker points are later trials.

axes = optuna_plots.plot_slice(study, params=["learning_rate", "min_samples_leaf"])
fig = plt.gcf()
fig.set_size_inches(10, 4.2)
plt.show()

Optuna slice plots showing the highest scores at learning rates between about 0.05 and 0.2 and at small leaf sizes

Low learning rates score poorly here, because 100 boosting iterations aren't enough for them. Scores level off between about 0.05 and 0.2. The points cluster where the sampler spent its trials, so sparse regions are less well explored.

Check Two Parameters Together with plot_contour

Some settings interact. A contour plot shows the score across two of them at once.

ax = optuna_plots.plot_contour(study, params=["learning_rate", "max_leaf_nodes"])
ax.figure.set_size_inches(8, 5.5)
plt.show()

Optuna contour plot of learning rate and maximum leaf nodes, darkest at learning rates above 0.05

The bands run mostly top to bottom, meaning the score changes with learning_rate far more than with max_leaf_nodes. The shading between dots is interpolated. Trust it near the points and not in empty areas.

Evaluate the Best Parameters

study.best_value was used to choose the settings, so confirm the result on data the search never saw. Refit on all the training rows with study.best_params.

from sklearn.metrics import roc_auc_score

for name, params in [("default", {}), ("tuned", study.best_params)]:
    model = HistGradientBoostingClassifier(**params, early_stopping=False,
                                           random_state=5).fit(X_train, y_train)
    auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
    print(f"{name} test AUC: {auc:.4f}")

The tuned model scores 0.9294 on the test set and the default scores 0.9316. Tuning raised the cross-validation score but didn't help on new rows: the gap is tiny, and 375 test rows can't separate the two. This is common when the defaults are already good. Report the test result you get, and don't rerun the search until it wins.

Stop Bad Trials Early with Pruning

Pruning ends a trial whose partial score is behind the others. MedianPruner stops a trial when its score at some step is below the median of earlier trials at that step.

def pruned_objective(trial):
    rate = trial.suggest_float("learning_rate", 0.005, 0.5, log=True)
    leaves = trial.suggest_int("max_leaf_nodes", 4, 64, log=True)
    model = HistGradientBoostingClassifier(
        learning_rate=rate, max_leaf_nodes=leaves, warm_start=True,
        early_stopping=False, random_state=5)
    for step in range(10, 201, 10):
        model.set_params(max_iter=step).fit(X_fit, y_fit)
        auc = roc_auc_score(y_valid, model.predict_proba(X_valid)[:, 1])
        trial.report(auc, step)
        if trial.should_prune():
            raise optuna.TrialPruned()
    return auc


X_fit, X_valid, y_fit, y_valid = train_test_split(
    X_train, y_train, test_size=0.3, stratify=y_train, random_state=5)
pruned = optuna.create_study(
    direction="maximize", sampler=optuna.samplers.TPESampler(seed=5),
    pruner=optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=30))
pruned.optimize(pruned_objective, n_trials=40)

states = [t.state.name for t in pruned.trials]
print("completed:", states.count("COMPLETE"), "pruned:", states.count("PRUNED"))

ax = optuna_plots.plot_intermediate_values(pruned)
ax.figure.set_size_inches(8, 4.8)
ax.get_legend().remove()
ax.set_xlabel("Boosting iterations")
ax.set_ylabel("Validation ROC AUC")
ax.figure.tight_layout()
plt.show()

Validation AUC by boosting iteration for each trial, with many weak trials stopping at 30 or 40 iterations

Of 40 trials, 16 ran all 200 iterations and 24 were stopped early, most after 30 or 40. n_warmup_steps=30 keeps the pruner from judging a trial before 30 iterations, which gives slow learners a short grace period. A pruner can still discard a slow starter that would have caught up. This study scores on a single validation set, which keeps the loop short.

Pruning needs a score reported partway through training, with trial.report() followed by trial.should_prune(). It suits models trained in rounds, such as boosting and neural networks.

Optuna's default sampler, TPE, uses earlier trials to decide what to try next. To compare it with random sampling fairly, run each several times with different seeds, since one run of either can get lucky.

optuna.logging.set_verbosity(optuna.logging.ERROR)
history = {}
for name, sampler in [("TPE", optuna.samplers.TPESampler),
                      ("Random", optuna.samplers.RandomSampler)]:
    runs = []
    for seed in range(5):
        run = optuna.create_study(direction="maximize", sampler=sampler(seed=seed))
        run.optimize(objective, n_trials=40)
        runs.append(np.maximum.accumulate([t.value for t in run.trials]))
    history[name] = np.array(runs)

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
trials = np.arange(1, 41)
for name, color in [("TPE", "#7c3aed"), ("Random", "#64748b")]:
    runs = history[name]
    ax.plot(trials, np.median(runs, axis=0), color=color, lw=2.5,
            label=f"{name} (median of 5 runs)")
    ax.fill_between(trials, runs.min(axis=0), runs.max(axis=0), color=color,
                    alpha=0.18)
ax.set(title="Best score found so far", xlabel="Trial",
       ylabel="Cross-validated ROC AUC")
ax.legend(loc="lower right")
plt.show()

Best score found by trial for TPE and random search over five runs each, with TPE ahead after about 17 trials

Both samplers match for the first ten trials, because TPE starts with random draws. After that TPE pulls ahead, and at 40 trials its median best score is 0.944 against 0.941 for random search. The difference is real but small on this problem, with four settings and a fairly flat optimum.

Method How it picks the next trial Good fit
GridSearchCV Every combination in a fixed grid One or two settings with a few values each
RandomizedSearchCV Random draws A quick baseline, easy to run in parallel
Optuna (TPE) Draws guided by earlier results Several settings, expensive models, pruning

Practical Tips

  • Pass seed= to the sampler and run trials one at a time to get the same results again.
  • Use log=True for settings that span orders of magnitude, such as learning rates.
  • Save a study with storage="sqlite:///study.db" and load_if_exists=True, so you can stop and resume.
  • If the best value sits at the edge of a search range, widen the range. Here the best l2_regularization is near the lower limit of 0.001, and a wider range would be the next thing to try.
  • If trials are unexpectedly slow on small data, set the environment variable OMP_NUM_THREADS=1 before starting Python. HistGradientBoostingClassifier uses every core by default, and the coordination can cost more than it saves.
  • Tune inside the training data only. See train/test split and cross-validation.

Similar Topics