Sub topic 3
Writing an objective function
An objective function is the one piece of code you write for every Optuna study. It takes a trial, builds and evaluates a model using values the trial suggests, and returns a number. This chapter assumes you know basic Python, can train and validate a scikit-learn model, and understand the difference between parameters and hyperparameters. It covers the contract the function must satisfy, what to put inside it, and the errors that come up most often.
The contract
Optuna calls your function once per trial. The function must follow three rules:
- It accepts exactly one argument, a
Trialobject. - It asks that object for hyperparameter values with
trial.suggest_*calls. - It returns a float, or a tuple of floats for a multi-objective study.
Everything else is ordinary Python. Optuna does not care how you train the model, which library you use, or where the data comes from.
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=50)
print(study.best_params)
print(study.best_value)The direction argument tells Optuna whether smaller or larger returned values are better. The function itself never states this. The same function can be minimised or maximised depending on how the study was created. Here best_params should be close to {"x": 2.0} and best_value close to 0.
What happens on each call
The diagram shows the exchange between the study and your function during one trial.
The sampler chooses the value for each suggest_* call at the moment the call runs. That is why the search space is "define-by-run": the space is whatever your code asks for during execution.
Returning a good metric
The returned value is the only feedback the sampler gets. Three habits make it reliable.
- Return a validation metric, never a training metric. A model can reach a perfect training score by memorising the data, and the search would then favour overfit settings.
- Return one number that matches the study direction. Accuracy and F1 go with
maximize. Loss, error and RMSE go withminimize. - Keep the metric stable. If the score is noisy, for example because of a random split, the sampler may chase luck. Fix the split or use cross-validation.
The next example tunes a real model. It picks a classifier, then suggests only the hyperparameters that classifier uses.
import optuna
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
def objective(trial):
name = trial.suggest_categorical("classifier", ["svc", "rf"])
if name == "svc":
c = trial.suggest_float("svc_c", 1e-3, 1e3, log=True)
model = SVC(C=c, gamma="scale")
else:
depth = trial.suggest_int("rf_max_depth", 2, 16)
model = RandomForestClassifier(max_depth=depth, n_estimators=100, random_state=0)
return cross_val_score(model, X, y, cv=3).mean()
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=30)
print(study.best_trial.params)The function returns the mean cross-validated accuracy, so the study maximises it. Each trial only suggests parameters for the chosen branch, so a trial that picks svc never records rf_max_depth.
What belongs inside and outside the function
Optuna calls the function many times, so placement matters.
| Put inside the objective | Put outside the objective |
|---|---|
| `suggest_*` calls | Loading the dataset |
| Model construction with suggested values | Fixed preprocessing that does not depend on hyperparameters |
| Training and scoring | Creating the study and sampler |
| Pruning checks | Plotting and reporting |
Loading a large dataset inside the function repeats that work for every trial. If preprocessing does depend on a hyperparameter, such as the number of PCA components, it has to be inside.
Variables defined outside are reachable because Python closures work as usual. If you need extra arguments, wrap the function:
import optuna
def objective(trial, data_scale):
x = trial.suggest_float("x", -10, 10)
return data_scale * (x - 2) ** 2
study = optuna.create_study(direction="minimize")
study.optimize(lambda trial: objective(trial, data_scale=3.0), n_trials=20)
print(study.best_value)Using functools.partial works equally well.
Pruning inside the objective
For iterative training, the objective can report intermediate scores and stop early. This builds on the same function shape.
import numpy as np
import optuna
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=0)
classes = np.unique(y)
def objective(trial):
alpha = trial.suggest_float("alpha", 1e-6, 1e-1, log=True)
clf = SGDClassifier(alpha=alpha, random_state=0)
acc = 0.0
for step in range(20):
clf.partial_fit(X_train, y_train, classes=classes)
acc = clf.score(X_val, y_val)
trial.report(acc, step)
if trial.should_prune():
raise optuna.TrialPruned()
return acc
pruner = optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=5)
study = optuna.create_study(direction="maximize", pruner=pruner)
study.optimize(objective, n_trials=30)trial.report(value, step) records the score at a step. trial.should_prune() asks the pruner whether the trial is falling behind. Raising optuna.TrialPruned ends the trial and marks it as pruned. A pruned trial still appears in the study but has no final value. Chapter details on choosing pruners come later.
How failures are handled
A trial ends in one of several states.
| State | Cause |
|---|---|
| `COMPLETE` | The function returned a valid number |
| `PRUNED` | The function raised `TrialPruned` |
| `FAIL` | The function raised another exception, or returned `nan` |
By default, an uncaught exception stops the whole optimize call and propagates to you. The failed trial is recorded as FAIL. To keep going when some trials crash, pass catch:
import optuna
def objective(trial):
x = trial.suggest_float("x", -1, 1)
return 1 / x
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=20, catch=(ZeroDivisionError,))Only the listed exception types are swallowed. Catching everything hides real bugs, so list the specific errors you expect, such as out-of-memory errors for oversized models.
Common errors
- Wrong return type. Returning a string,
Noneor a list raises an error or produces a failed trial. Return a float, or a tuple for multi-objective studies. - Returning
nan. The trial fails and is excluded from the best-trial search. Guard against divergence in training, or return a large finite penalty such as a high loss. - Redefining a parameter with a different range. If one trial suggests
"x"from 0 to 1 and a later one suggests"x"from 0 to 10 in the same study, Optuna raises an error on resumed or shared studies, because a name must keep one distribution. Use new names for different spaces. - Suggesting the same name twice in one trial. The second call returns the same value as the first, which is rarely what you intended. Give each hyperparameter a unique name.
- Using test data. If the objective scores on the test set, the reported best value is optimistic. Tune on validation data and evaluate the final model once on test data.
- Doing slow setup per trial. Move data loading outside the function.
Checking your function before a long run
Run a small study first. Five trials reveal type errors, bad ranges and slow steps cheaply.
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=5)
for t in study.trials:
print(t.number, t.state, t.params, t.value)Each entry in study.trials shows the trial number, its state, the suggested parameters and the returned value. Look for unexpected FAIL states and for runtimes that make the full run impractical.
Exercises
Exercise
You wrote an objective that returns the validation error rate. You create the study with direction="maximize". What goes wrong, and how do you fix it?
Show answer
The study searches for the highest error rate, so it finds the worst hyperparameters. Create the study with direction="minimize", or return accuracy (1 minus error) and keep maximize. The objective never declares a direction, so the mismatch is easy to miss.
Exercise
Your objective loads a 2 GB CSV file at the top of the function, and each trial takes minutes before training starts. What change helps, and when would the change not be possible?
Show answer
Load the data once outside the function and let the objective read it as a closure variable, or pass it with a lambda or functools.partial. This is not possible for steps that depend on a suggested hyperparameter, for example a feature-selection threshold, because those must run inside each trial.