Sub topic 3
Writing an objective function
This chapter assumes you know basic Python, can train and validate a scikit-learn model, and understand the difference between parameters and hyperparameters. It also assumes you know what a study and a trial are from the previous chapter.
What the objective function does
The objective function is the one piece of code you write for Optuna. It takes a trial, builds and evaluates a model with the hyperparameters that trial suggests, and returns a number. Optuna calls it once per trial and uses the returned value to decide what to try next.
Three rules define the contract:
- The only argument is
trial. - It returns a float, or a tuple of floats in a multi-objective study.
- The direction ("minimize" or "maximize") is set on the study, not in the function.
A minimal example
This study minimises a one-variable function and then reads the best result from the study.
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 call trial.suggest_float("x", -10, 10) asks Optuna for a value of x in that range. The name "x" identifies the parameter across trials. The best x should be close to 2.
What goes inside
A realistic objective has four steps:
- Ask the trial for hyperparameter values.
- Build the model from them.
- Evaluate it on data the model was not fitted on, for example with cross-validation.
- Return one score.
Load the data once, outside the function. Reloading a dataset in every trial wastes time and does not change the result.
Choosing the score
The value you return is the only signal Optuna gets. Pick it carefully:
- Return a validation metric, never the training score. A training score rewards overfitting.
- Match the direction to the metric. Accuracy and F1 are maximised. Loss and error are minimised.
- Return a plain Python or NumPy float. An array,
None, or a string makes the trial fail.
A nan return value also marks the trial as failed, and Optuna does not count it toward the best result.
Common errors
| Symptom | Likely cause |
|---|---|
| The study "improves" a loss that was meant to go down, but the best trial is the worst model | `direction` is `"maximize"` for an error metric |
| `ValueError` about the return value | The function returned an array or `None` |
| Same parameter name with a different range in two places | A name is reused, so Optuna raises an error on the second suggestion |
| Trials get slower and slower | Data loading or model construction that should be outside the function |
If your code raises an exception, the trial is marked as failed and, by default, the exception stops optimize. Pass catch=(ValueError,) to study.optimize to continue past a specific exception type.
Exercise
A colleague writes an objective that fits a classifier and returns clf.score(X_train, y_train), with direction="maximize". What is wrong, and what should the function return instead?
Show answer
The training score measures how well the model fits data it has already seen, so the study will favour overfit settings. Return a score on held-out data, such as cross_val_score(model, X, y, cv=3).mean() or a score on a separate validation set.
Exercise
Your objective returns the validation log loss, but create_study() was called with no arguments. What happens, and how do you fix it?
Show answer
The default direction is "minimize", so for log loss it happens to be correct. If the metric were accuracy, the study would minimise it and pick the worst settings. Fix it by passing direction="maximize" to create_study when you return a score where higher is better.