Sub topic 15
Tuning with Optuna
What you need first
This chapter assumes you can write Python, you have used scikit-learn's GridSearchCV or RandomizedSearchCV, and you know why a test set must stay untouched until the end. It also assumes you have seen cross-validation. You need pip install optuna scikit-learn.
Optuna is a library that runs a search loop for you. You write one function that trains a model and returns a score. Optuna calls that function repeatedly with different settings and chooses each new setting using the scores it has already seen.
Study, trial, and objective
Optuna uses three terms.
- A study is one whole tuning run. It stores every attempt and knows whether to maximize or minimize.
- A trial is one attempt, meaning one set of hyperparameter values and the score it produced.
- The objective is your function. It takes a trial, asks the trial for hyperparameter values, trains and scores a model, and returns a number.
The search space is not declared up front as in scikit-learn. It is defined by running code, with each trial.suggest_* call. This "define-by-run" style lets you use ordinary Python if statements, so a parameter can exist only when another parameter has a given value.
A first study
This study tunes a random forest. Every trial returns a 5-fold cross-validated accuracy computed on the training split only.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split
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, random_state=0, stratify=y
)
def objective(trial):
params = {
"n_estimators": trial.suggest_int("n_estimators", 50, 300),
"max_depth": trial.suggest_int("max_depth", 2, 16),
"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 10),
}
model = RandomForestClassifier(random_state=0, **params)
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
)
study.optimize(objective, n_trials=30)
print(study.best_params, study.best_value)direction="maximize" matters. The default is "minimize", which is correct for a loss and wrong for accuracy. If you forget it, Optuna will search for the worst model.
After the search, study.best_params holds only the winning settings. It does not hold a fitted model. You refit on the full training set and score the test set once:
best = RandomForestClassifier(random_state=0, **study.best_params)
best.fit(X_train, y_train)
print("Test accuracy:", best.score(X_test, y_test))Suggesting values
Each suggest_* call both declares a parameter and returns a value for this trial. The parameter name must be a unique string within the trial.
| Method | Use it for | Example |
|---|---|---|
| `suggest_int(name, low, high)` | Counts such as tree depth | `max_depth` from 2 to 16 |
| `suggest_float(name, low, high)` | Continuous values on a linear scale | `subsample` from 0.5 to 1.0 |
| `suggest_float(name, low, high, log=True)` | Values spanning orders of magnitude | `learning_rate` from 1e-4 to 1e-1 |
| `suggest_categorical(name, choices)` | Unordered options | `kernel` in `["rbf", "linear"]` |
Scale matters here for the same reason it does in random search. A learning rate between 1e-4 and 1e-1 sampled linearly puts about 90% of the draws above 1e-2. With log=True, each decade gets equal attention. Use log=True for learning rates, regularization strengths, and the SVM C and gamma. Log ranges must have a positive lower bound.
A conditional space is plain Python:
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
def build_model(trial):
name = trial.suggest_categorical("model", ["svm", "forest"])
if name == "svm":
C = trial.suggest_float("C", 1e-2, 1e2, log=True)
return SVC(C=C)
depth = trial.suggest_int("max_depth", 2, 16)
return RandomForestClassifier(max_depth=depth, random_state=0)Here C exists only in trials that pick the SVM. Optuna's samplers handle this without a fixed grid.
How the default sampler chooses
The default sampler is TPESampler (Tree-structured Parzen Estimator). The first trials, 10 by default, are random. After that, TPE splits the finished trials into a "good" group (the top fraction by score) and a "bad" group. It fits a density model to each group for every parameter and prefers values that are likely under the good group and unlikely under the bad group. The result is a search that concentrates on promising regions while still sampling elsewhere.
This is the sequential idea from the Bayesian optimization chapter, with a cheaper surrogate than a Gaussian process. It handles integers, categories, and conditional parameters well.
Sequential search has a cost. Trial 20 depends on trials 1 to 19, so parallelism helps less than it does with random search. With only a handful of trials, TPE is mostly random search anyway.
Pruning bad trials early
If your model trains in steps (epochs, boosting rounds, or partial fits), a trial can report intermediate scores. A pruner compares them with earlier trials and stops a trial that is clearly behind. This is the same idea as successive halving and Hyperband.
The three calls are trial.report(value, step), trial.should_prune(), and raise optuna.TrialPruned(). The example uses a held-out validation split carved from the training data, so the test set is untouched.
import numpy as np
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
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, random_state=0, stratify=y
)
X_tr, X_val, y_tr, y_val = train_test_split(
X_train, y_train, test_size=0.25, random_state=0, stratify=y_train
)
scaler = StandardScaler().fit(X_tr)
X_tr, X_val = scaler.transform(X_tr), scaler.transform(X_val)
classes = np.unique(y_tr)
def objective(trial):
alpha = trial.suggest_float("alpha", 1e-6, 1e-1, log=True)
clf = SGDClassifier(alpha=alpha, random_state=0)
score = 0.0
for step in range(20):
clf.partial_fit(X_tr, y_tr, classes=classes)
score = clf.score(X_val, y_val)
trial.report(score, step)
if trial.should_prune():
raise optuna.TrialPruned()
return score
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
pruner=optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=3),
)
study.optimize(objective, n_trials=30)
states = [t.state.name for t in study.trials]
print("complete:", states.count("COMPLETE"), "pruned:", states.count("PRUNED"))
print(study.best_params, study.best_value)MedianPruner stops a trial whose score at a step is worse than the median of earlier trials at that step. n_startup_trials=5 lets the first five trials finish unpruned, and n_warmup_steps=3 ignores the first steps, where scores are noisy. HyperbandPruner is a common alternative when you have a large number of trials.
Pruned trials are not failures. They have state PRUNED, and best_trial only considers completed trials.
Storage, parallel workers, and stopping
By default a study lives in memory and disappears when the process ends. Give it a database to keep it and to resume later:
import optuna
study = optuna.create_study(
study_name="rf-breast-cancer",
storage="sqlite:///tuning.db",
load_if_exists=True,
direction="maximize",
)Running the script again continues the same study and adds trials. Several processes can point at the same storage and share trials, though SQLite is fine only for light concurrency. Use PostgreSQL or MySQL for many workers.
You can set a budget by trials, by time, or both: study.optimize(objective, n_trials=100, timeout=600). Optuna stops at whichever limit is reached first. n_jobs=-1 runs trials in threads, which helps only when the objective releases the Python GIL (as most scikit-learn code does).
For inspection, study.trials_dataframe() returns one row per trial with its parameters, score, state, and duration.
Common errors
- Forgetting
direction. The study minimizes accuracy and returns the worst settings. - Scoring on the test set inside the objective. Every trial then selects against the test data, and the final test score is no longer an honest estimate.
- Preprocessing before splitting. Fit scalers and imputers inside a pipeline or inside each fold. The pruning example above fits the scaler on the training portion only.
- Trusting
best_valueas the final result. It is the maximum over many noisy scores, so it is biased upward. Report the one-time test score, or use nested cross-validation. - Expecting exact repeatability from
n_jobs > 1. A seed onTPESamplerfixes the sampler's randomness, but parallel trials finish in varying order, so the sequence of proposals can change. Also setrandom_stateon the model. - Reusing one study name with changed code. With
load_if_exists=True, old trials from a different objective or search space stay in the study. Change the study name when you change the objective.
Exercise
You tune a gradient boosting model's learning rate with trial.suggest_float("lr", 0.0001, 0.1), and the best trials all have a learning rate above 0.01. What is likely wrong with the search, and how do you fix it?
Show answer
The search samples linearly, so about 90% of the draws fall above 0.01 and small learning rates are barely tried. Add log=True, as in trial.suggest_float("lr", 1e-4, 1e-1, log=True), so each order of magnitude gets a similar share of trials. The result above 0.01 may then change.
Exercise
In a pruning study, study.trials has 30 entries but only 12 have state COMPLETE. Does this mean 18 trials crashed? Which trials can study.best_trial return?
Show answer
No. Pruned trials have state PRUNED, which means the pruner stopped them on purpose because their intermediate scores trailed earlier trials. Crashes appear as state FAIL. best_trial is chosen only from COMPLETE trials, so it is one of the 12.