Sub topic 15
Optimising more than one objective
This chapter assumes you can write an Optuna objective function, run a study, and read study.best_trial. It also assumes you know what a sampler does. If any of that is unfamiliar, review the chapters on studies, trials and samplers first.
Why one number is sometimes not enough
Many tuning problems have competing goals. A model with higher accuracy is often larger or slower. A fraud detector that catches more fraud also raises more false alarms. If you fold these goals into one score, such as accuracy - 0.01 * latency, you must choose the weights before you see what trade-offs are available. A poor weight choice hides good options.
Multi-objective optimisation keeps the goals separate. Optuna returns a set of trials that are each a reasonable compromise. You then choose among them.
Pareto optimality
Suppose you minimise two values, A and B. Trial 1 dominates trial 2 if trial 1 is no worse on every objective and strictly better on at least one. A trial that no other trial dominates is Pareto-optimal. The set of all such trials is the Pareto front.
The front has no single winner. Moving along it improves one objective only by worsening another.
P is better than R on A, and R is better than P on B, so neither dominates the other. Q is worse than both on both objectives, so it is not on the front.
Running a multi-objective study
Create the study with directions (plural) instead of direction. The objective returns one value per direction, in the same order.
import optuna
def objective(trial):
x = trial.suggest_float("x", 0, 5)
y = trial.suggest_float("y", 0, 3)
return x ** 2 + y, (x - 2) ** 2 + (y - 1) ** 2
study = optuna.create_study(directions=["minimize", "minimize"])
study.optimize(objective, n_trials=50)
for t in study.best_trials:
print(t.values, t.params)Here the first objective prefers small x and y, while the second prefers the point (2, 1). No single point satisfies both, so the study returns a front.
You can mix directions. For example, directions=["maximize", "minimize"] maximises accuracy and minimises latency.
Reading the results
Several single-objective attributes behave differently once a study has more than one objective.
| Single objective | Multi-objective |
|---|---|
| `study.direction` | `study.directions` (a list) |
| `study.best_trial` | `study.best_trials` (a list, the Pareto front) |
| `study.best_value`, `study.best_params` | Not available. They raise an error. |
| `trial.value` | `trial.values` (a list) |
Calling study.best_trial on a multi-objective study raises a RuntimeError. Use best_trials and pick from it.
Each element of best_trials is a FrozenTrial. You can sort or filter the list yourself. This example picks the front member with the smallest first objective, subject to a limit on the second:
import optuna
def objective(trial):
x = trial.suggest_float("x", 0, 5)
y = trial.suggest_float("y", 0, 3)
return x ** 2 + y, (x - 2) ** 2 + (y - 1) ** 2
study = optuna.create_study(directions=["minimize", "minimize"])
study.optimize(objective, n_trials=50)
acceptable = [t for t in study.best_trials if t.values[1] <= 1.0]
choice = min(acceptable, key=lambda t: t.values[0])
print(choice.values, choice.params)If no trial meets the limit, acceptable is empty and min raises ValueError. Guard against that when the limit is strict.
Samplers for multi-objective studies
TPE with a single objective ranks trials as "good" or "bad" by value. With several objectives there is no total order, so the sampler needs another way to rank trials. Optuna's default sampler for multi-objective studies handles this by ranking with Pareto dominance, and it breaks ties using a measure of how much objective space a trial covers. You do not need to configure this for ordinary use.
Other samplers are available for multi-objective work. optuna.samplers.NSGAIISampler and optuna.samplers.NSGAIIISampler are evolutionary algorithms, and they tend to suit cheap objectives where you can afford many trials. optuna.samplers.RandomSampler is a useful baseline. Pass the sampler in as you would for a single-objective study:
import optuna
def objective(trial):
x = trial.suggest_float("x", 0, 5)
y = trial.suggest_float("y", 0, 3)
return x ** 2 + y, (x - 2) ** 2 + (y - 1) ** 2
sampler = optuna.samplers.NSGAIISampler(seed=0)
study = optuna.create_study(
directions=["minimize", "minimize"],
sampler=sampler,
)
study.optimize(objective, n_trials=100)
print(len(study.best_trials))Seeding the sampler follows the same reproducibility rules as before: a seed makes a single-process run repeatable, but parallel runs can still differ.
Pruning does not work with several objectives
Optuna does not support pruning in multi-objective studies. trial.report and trial.should_prune raise NotImplementedError when called there. If an expensive objective needs early stopping, you have two choices:
- Collapse the goals into one scalar and use a single-objective study with a pruner.
- Keep the two goals, and enforce your own cut-off inside the objective by raising
optuna.TrialPruned()when a cheap check fails. For example, skip training when the model's parameter count already exceeds your size limit.
A realistic example: accuracy against model size
This study tunes a random forest to maximise cross-validated accuracy while minimising the number of trees, which is a simple proxy for model size and prediction cost.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
X, y = load_breast_cancer(return_X_y=True)
def objective(trial):
n_estimators = trial.suggest_int("n_estimators", 5, 200, log=True)
max_depth = trial.suggest_int("max_depth", 2, 16)
model = RandomForestClassifier(
n_estimators=n_estimators,
max_depth=max_depth,
random_state=0,
)
accuracy = cross_val_score(model, X, y, cv=3).mean()
return accuracy, n_estimators
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(
directions=["maximize", "minimize"],
sampler=sampler,
)
study.optimize(objective, n_trials=40)
for t in sorted(study.best_trials, key=lambda t: t.values[1]):
print(f"trees={t.values[1]:>3} accuracy={t.values[0]:.3f} {t.params}")The printout lists the front from smallest to largest forest. Typically accuracy rises quickly with the first few trees and then flattens. The front shows where extra trees stop paying off, and you can pick the smallest forest whose accuracy you accept.
Visualising the front
optuna.visualization.plot_pareto_front draws the trials in objective space and highlights the front. Plotly must be installed.
import optuna
from optuna.visualization import plot_pareto_front
def objective(trial):
x = trial.suggest_float("x", 0, 5)
y = trial.suggest_float("y", 0, 3)
return x ** 2 + y, (x - 2) ** 2 + (y - 1) ** 2
study = optuna.create_study(directions=["minimize", "minimize"])
study.optimize(objective, n_trials=50)
plot_pareto_front(study, target_names=["cost", "distance"]).show()Pass target_names so the axes carry meaningful labels instead of "Objective 0" and "Objective 1".
Other plots need a single value to rank trials. For plot_param_importances and plot_optimization_history, pass a target function and a target_name:
import optuna
from optuna.visualization import plot_param_importances
def objective(trial):
x = trial.suggest_float("x", 0, 5)
y = trial.suggest_float("y", 0, 3)
return x ** 2 + y, (x - 2) ** 2 + (y - 1) ** 2
study = optuna.create_study(directions=["minimize", "minimize"])
study.optimize(objective, n_trials=50)
plot_param_importances(
study,
target=lambda t: t.values[0],
target_name="cost",
).show()Common errors
- Using
best_trialorbest_value. These fail with several objectives. Usebest_trials. - Returning the wrong number of values. The tuple length must equal the length of
directions. A mismatch fails the trial. - Mixing up the order. Values are matched to directions by position. If you list
["maximize", "minimize"], return accuracy first and cost second. - Calling
reportorshould_prune. Pruning is unsupported here, as described above. - Expecting one answer. The front is a menu. Decide your selection rule, such as a latency budget, and apply it to
best_trials. - Using different scales without thought. Objectives such as accuracy near 0.95 and latency in milliseconds are compared by dominance, not by magnitude, so scale does not distort the front. It matters only if you later combine them into one score.
Exercises
Exercise
A study is created with directions=["maximize", "minimize"]. The objective returns (latency_ms, accuracy). What goes wrong, and how do you fix it?
Show answer
Values are matched to directions by position, so Optuna would maximise latency and minimise accuracy, the opposite of the intent. The study runs without an error, so the mistake is silent. Fix it by returning (accuracy, latency_ms) to match the direction order, or by reordering directions to ["minimize", "maximize"].
Exercise
Trial A has values (0.90, 20) and trial B has values (0.92, 35) in a study with directions maximize accuracy and minimize latency. Does either dominate the other? Can both be on the Pareto front?
Show answer
Neither dominates. A has lower latency, which is better, and B has higher accuracy, which is better. Since each is better on one objective, both can be on the Pareto front, provided no other trial dominates them.
Exercise
Why does study.best_trial raise an error on a multi-objective study, and what do you use instead?
Show answer
With several objectives there is usually no single best trial, because the trials on the Pareto front trade one objective against another. Use study.best_trials, which returns the list of Pareto-optimal trials, and apply your own selection rule to it.