Module 14 · Intermediate · Building reliable models

Hyperparameter tuning with Optuna in Python

Hyperparameter tuning with Optuna in Python: objective functions, log-scale search spaces, TPE vs random search, pruning bad trials and honest test scores.

By theprogrammers team · · 12 min read

Grid search tries every combination on a list, even after the first few results make it obvious that half the list is hopeless. A cook adjusting a sauce doesn't work like that: after each taste, they change what seems to need changing. Optuna tunes a model's settings the same way. It tries a combination, looks at the score, and uses everything it has seen so far to choose the next one. It can also give up on a combination halfway through when it's clearly doing badly.

Hyperparameter tuning with Optuna needs three things: a function that trains a model and returns its score, a description of which settings to try and over what range, and a number of attempts. Here it tunes gradient boosting on California house prices, and an experiment checks whether Optuna's guided search actually beats plain random guessing on the same budget.

What you need first: hyperparameter tuning with grid search, cross-validation and gradient boosting explained.

Key terms

  • Trial: one attempt: one combination of settings, trained and scored.
  • Study: the whole search, a series of trials with the history of their scores.
  • Objective function: your function that takes a trial, trains a model with the settings it suggests, and returns a score to minimise or maximise.
  • Sampler: the rule that picks the next trial's settings; Optuna's default, TPE, learns from earlier trials.
  • Pruning: stopping an unpromising trial early to save time.

Optuna is a separate package: pip install optuna.

The data and the baseline

California house prices again: 20,640 districts, values in units of $100,000, scored by mean absolute error (MAE). A test set is set aside first and not touched until the very end.

Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("california-housing.csv").

import numpy as np
import optuna
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.ensemble import HistGradientBoostingRegressor

optuna.logging.set_verbosity(optuna.logging.WARNING)
X, y = fetch_california_housing(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
cv = KFold(n_splits=3, shuffle=True, random_state=0)

def cv_mae(**settings):
    model = HistGradientBoostingRegressor(max_iter=200, random_state=0, **settings)
    scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="neg_mean_absolute_error")
    return -scores.mean()

print(f"default settings: cross-validated MAE {cv_mae():.4f}")
default settings: cross-validated MAE 0.3146

set_verbosity(WARNING) stops Optuna printing a line for every trial. Scikit-learn's scores are "higher is better", so mean absolute error comes back negative, and cv_mae flips the sign. **settings passes any settings given to cv_mae on to the model.

The default model's error is the baseline: tuning must beat it to be worth the time.

Step 1: write the objective function

The objective function asks the trial for a value of each setting, then returns the score:

def objective(trial):
    return cv_mae(
        learning_rate=trial.suggest_float("learning_rate", 0.01, 0.5, log=True),
        max_leaf_nodes=trial.suggest_int("max_leaf_nodes", 4, 128, log=True),
        min_samples_leaf=trial.suggest_int("min_samples_leaf", 2, 200, log=True),
        l2_regularization=trial.suggest_float("l2_regularization", 1e-4, 10, log=True),
    )

suggest_float("learning_rate", 0.01, 0.5, log=True) means "pick a decimal between 0.01 and 0.5, spread evenly on a log scale". The log scale matters: without it, 98% of picks would land above 0.02, and values such as 0.01 to 0.02, where good learning rates often live, would hardly be tried. Use log=True for any setting whose sensible values span several powers of ten.

Unlike a grid, the search space is written as ordinary Python, so it can depend on earlier choices: for example, only suggesting a kernel's settings if that kernel was chosen.

Step 2: run the Optuna study

import time

start = time.perf_counter()
study = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=0))
study.optimize(objective, n_trials=20)
tpe_seconds = time.perf_counter() - start

print(f"best cross-validated MAE: {study.best_value:.4f}")
print("best settings:", {k: round(v, 4) for k, v in study.best_params.items()})
best cross-validated MAE: 0.3100
best settings: {'learning_rate': 0.1062, 'max_leaf_nodes': 59, 'min_samples_leaf': 29, 'l2_regularization': 0.002}

direction="minimize" because lower error is better. TPESampler(seed=0) makes the run repeatable. Each trial fits 3 models, one per fold, so this takes a minute or two.

The best settings bring the cross-validated error from 0.3146 to 0.3100, an improvement of about 1.5%. The search chose a learning rate of about 0.11, trees of up to 59 leaves, at least 29 rows per leaf, and almost no L2 penalty.

Step 3: look at the history

Every trial is stored in the study. Plot each trial's score, and the best score so far:

import matplotlib.pyplot as plt

values = [t.value for t in study.trials]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.scatter(range(1, len(values) + 1), values, label="Trial")
ax.plot(range(1, len(values) + 1), np.minimum.accumulate(values), color="tab:red", label="Best so far")
ax.axhline(cv_mae(), color="grey", linestyle="--", label="Default settings")
ax.set_xlabel("Trial")
ax.set_ylabel("Cross-validated MAE")
ax.legend()
plt.show()
Cross-validated MAE for each of 20 Optuna trials, with a red best-so-far line and a dashed grey line for the default settings at about 0.315. The first ten trials are scattered widely, from about 0.31 up to 0.39. From trial 11 onwards, every trial lies between about 0.31 and 0.32. The best-so-far line starts at about 0.310 with the first trial and dips very slightly at trial 12.

np.minimum.accumulate turns a list into its running minimum: the best score after each trial.

The history shows how TPE works. Its first 10 trials are random, to explore, and they're scattered: one scored 0.39, far worse than the defaults. From trial 11, TPE uses what it has seen, and every later trial lands between 0.31 and 0.32. It has stopped wasting trials on bad regions. The best-so-far line barely moves, though: the very first random trial happened to score 0.3104, already close to the best, and TPE improved on it only slightly, at trial 12. On this problem, many reasonable settings work about equally well.

Which settings mattered most? Optuna can estimate it from the trials:

importances = optuna.importance.get_param_importances(study)
for name, share in importances.items():
    print(f"{name:18} {share:.2f}")
min_samples_leaf   0.49
max_leaf_nodes     0.32
learning_rate      0.17
l2_regularization  0.02

min_samples_leaf explains about half of the variation in scores between trials, followed by the number of leaves and the learning rate; the L2 penalty hardly matters. That's useful for the next search: narrow down or fix the unimportant settings and spend the trials on the ones that count. With only 20 trials, treat these shares as rough.

Experiment: is guided search better than guessing?

Experiment: run the same 20 trials with RandomSampler, which picks every trial at random from the same ranges and learns nothing. Predict first: how much better will TPE's best score be?

random_study = optuna.create_study(direction="minimize", sampler=optuna.samplers.RandomSampler(seed=0))
random_study.optimize(objective, n_trials=20)

tpe_curve = np.minimum.accumulate([t.value for t in study.trials])
random_curve = np.minimum.accumulate([t.value for t in random_study.trials])
for n in [5, 10, 15, 20]:
    print(f"after {n:2} trials: TPE best {tpe_curve[n - 1]:.4f}   random best {random_curve[n - 1]:.4f}")
after  5 trials: TPE best 0.3104   random best 0.3104
after 10 trials: TPE best 0.3104   random best 0.3104
after 15 trials: TPE best 0.3100   random best 0.3104
after 20 trials: TPE best 0.3100   random best 0.3104

Barely better, and only in the fourth decimal place: 0.3100 against 0.3104. Both studies drew the same lucky first trial at 0.3104, because TPE's random start uses the same seed as the random sampler. After that, random search found nothing better, and TPE found one slightly better trial. With 4 settings and 20 trials, a well-chosen range gives random search plenty of good guesses. TPE's advantage grows with more settings, more trials and narrower good regions. Its clearer benefit here is the one in the history chart: fewer wasted trials once it has learned.

Step 4: prune bad trials early

Most trials are worse than the best, and many are obviously worse after the first fold. Pruning stops them there. The objective reports the running score after each fold; the pruner compares it with other trials at the same point and stops the trial if it's worse than their median.

from sklearn.metrics import mean_absolute_error

def objective_with_pruning(trial):
    settings = dict(
        learning_rate=trial.suggest_float("learning_rate", 0.01, 0.5, log=True),
        max_leaf_nodes=trial.suggest_int("max_leaf_nodes", 4, 128, log=True),
        min_samples_leaf=trial.suggest_int("min_samples_leaf", 2, 200, log=True),
        l2_regularization=trial.suggest_float("l2_regularization", 1e-4, 10, log=True),
    )
    errors = []
    for fold, (fit_rows, val_rows) in enumerate(cv.split(X_train)):
        model = HistGradientBoostingRegressor(max_iter=200, random_state=0, **settings)
        model.fit(X_train[fit_rows], y_train[fit_rows])
        errors.append(mean_absolute_error(y_train[val_rows], model.predict(X_train[val_rows])))
        trial.report(np.mean(errors), step=fold)
        if trial.should_prune():
            raise optuna.TrialPruned()
    return np.mean(errors)

pruned_study = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=0),
                                   pruner=optuna.pruners.MedianPruner(n_startup_trials=5))
pruned_study.optimize(objective_with_pruning, n_trials=20)

states = [t.state for t in pruned_study.trials]
pruned = sum(s == optuna.trial.TrialState.PRUNED for s in states)
fits = sum(len(t.intermediate_values) for t in pruned_study.trials)
print(f"best MAE {pruned_study.best_value:.4f}, {pruned} of 20 trials pruned, {fits} model fits instead of 60")
best MAE 0.3100, 11 of 20 trials pruned, 43 model fits instead of 60

The loop does by hand what cross_val_score did, so it can report after each fold. trial.report(value, step) records the running score, and should_prune() asks the pruner whether to stop. MedianPruner(n_startup_trials=5) lets the first 5 trials finish, so there's something to compare against. intermediate_values holds one entry per fold a trial completed, so adding them up counts the models trained.

Pruning stopped 11 of the 20 trials early, and the study trained 43 models instead of 60, about 28% less work, while finding the same best score, 0.3100. Each saved fit is a full gradient boosting model, so on bigger data or slower models the saving is real time. Pruning shines with models that report progress often, such as neural networks after each epoch, where a bad trial can be stopped after a fraction of its training.

Step 5: the honest test

Train the best settings on all the training data and score the test set, once, next to the default model:

tuned = HistGradientBoostingRegressor(max_iter=200, random_state=0, **study.best_params).fit(X_train, y_train)
default = HistGradientBoostingRegressor(max_iter=200, random_state=0).fit(X_train, y_train)
print(f"test MAE, default settings: {mean_absolute_error(y_test, default.predict(X_test)):.4f}")
print(f"test MAE, tuned settings:   {mean_absolute_error(y_test, tuned.predict(X_test)):.4f}")
test MAE, default settings: 0.2978
test MAE, tuned settings:   0.2964

On the test set, the tuned model's error is 0.2964 against the default's 0.2978: better by about 0.5%, smaller than the 1.5% that cross-validation suggested. The best of 20 cross-validated scores was a little lucky, as the best of many noisy scores usually is. Gradient boosting's defaults are good, and on this data tuning buys little. That's worth knowing before spending a day on it: run a short search first, and only invest in a long one if the gain looks worthwhile.

Grid search, random search or Optuna?

SituationGood choiceWhy
1 or 2 settings, a few values eachGrid searchSimple, tries everything, easy to plot
3 or more settings, a small budgetRandom search or OptunaA grid explodes; random covers each setting well
Expensive trials (minutes each), many settingsOptuna with pruningLearns where to look and drops bad trials early
Settings that depend on other settingsOptunaThe search space is plain Python
You want to stop and resume a long searchOptuna with storageStudies can be saved to a database

Practice

  1. Without running code: a setting ranges from 0.0001 to 1. Without log=True, what share of random picks lands below 0.01?
Show the answer

About 1%: the range 0.0001 to 0.01 is 0.0099 wide out of 0.9999. On a log scale, the same range covers 2 of the 4 powers of ten, so about half the picks land there.

  1. Add max_iter as a fifth setting, from 50 to 500 in steps of 50, and run 20 TPE trials. Does the best score improve?
Show the answer
def objective_5(trial):
    model = HistGradientBoostingRegressor(
        max_iter=trial.suggest_int("max_iter", 50, 500, step=50), random_state=0,
        learning_rate=trial.suggest_float("learning_rate", 0.01, 0.5, log=True),
        max_leaf_nodes=trial.suggest_int("max_leaf_nodes", 4, 128, log=True),
        min_samples_leaf=trial.suggest_int("min_samples_leaf", 2, 200, log=True),
        l2_regularization=trial.suggest_float("l2_regularization", 1e-4, 10, log=True))
    return -cross_val_score(model, X_train, y_train, cv=cv, scoring="neg_mean_absolute_error").mean()

study_5 = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=0))
study_5.optimize(objective_5, n_trials=20)
print(round(study_5.best_value, 4), study_5.best_params["max_iter"])
0.3099 350

Hardly: 0.3099 against 0.3100, with 350 trees chosen. A fifth setting gives the search more to explore with the same 20 trials, so gains are hard to find. More trees helped a touch here, which suggests the default 200 was slightly too few for the chosen learning rate.

  1. Why is the cross-validated MAE of the best trial an optimistic estimate of how the tuned model will do on new data?
Show the answer

It was chosen as the best of 20 noisy scores, and the best of many noisy numbers is usually a lucky one. The test set, untouched during the search, gives the honest estimate.

  1. Why does pruning compare a trial's running score with the median of other trials at the same fold, not with their final scores?
Show the answer

Scores after one fold aren't directly comparable with averages over three folds: one fold can be easier or harder than average. Comparing like with like, the same fold for every trial, makes the decision fair.

  1. Your study's best learning_rate is 0.0101, right at the bottom of the range 0.01 to 0.5. What should you do?
Show the answer

Widen the range downwards, for example to 0.001, and search again. A best value at the edge of a range suggests that the true best lies outside it.

Interview questions

How does Optuna differ from grid search?

Grid search evaluates every combination of a fixed list. Optuna samples combinations one at a time, by default with TPE, which models which regions of the search space gave good scores and samples there more often. It also supports pruning unpromising trials and search spaces defined in code.

What is the Tree-structured Parzen Estimator (TPE)?

A Bayesian-style sampler. It splits past trials into good and bad by score, fits a density to the settings of each group, and picks new settings where the ratio of "good" density to "bad" density is highest. The first several trials are random, to give it something to learn from.

What is pruning in hyperparameter optimisation?

Stopping a trial before it finishes when its intermediate results (after some epochs, trees or folds) are worse than other trials at the same stage, such as below the median. It saves the time that hopeless trials would waste.

Key takeaways

  • Optuna tunes by trial and error with memory: an objective function, a search space in code, and a number of trials.
  • Use log=True for settings that span several powers of ten, such as learning rates and regularisation.
  • Guided search beats random search mainly with many settings and large budgets; with 20 trials they can tie.
  • Pruning stops weak trials early and saves model fits without losing the best result.
  • Report the tuned model's score on an untouched test set; the best cross-validated score is optimistic.

Frequently asked questions

How many trials should I run?

Enough that the best-so-far line has flattened: often 50 to 200 for a few settings. Start small, look at the history plot, and continue the same study with more optimize calls if it's still improving.

Can Optuna tune any model?

Yes: the objective function is ordinary Python, so it can train scikit-learn models, XGBoost, neural networks or anything else, as long as it returns a number.

Can I save a study and continue later?

Yes: create it with storage="sqlite:///study.db" and a study_name, and load it again with optuna.load_study. Several processes can even share one study to search in parallel.

What to learn next

  1. Find out which features a model can do without in feature selection methods, the next lesson.
  2. Revisit the simpler methods in hyperparameter tuning with grid search.
  3. Check whether more data or a better model would help more in learning curves and validation curves.