Sub topic 13
Inspecting results and plotting
A finished study holds more than the best value. It records every trial's parameters, state, timing and intermediate values. This chapter shows how to read that record and turn it into plots. It assumes you can write an objective function, run study.optimize, and use trial.report for pruning, as covered in earlier chapters. Plots need plotly, and trials_dataframe needs pandas. Importance plots also need scikit-learn.
What a study records
Three kinds of data are available after optimize returns:
- Summary attributes:
study.best_value,study.best_paramsandstudy.best_trial. - Per-trial records:
study.trialsis a list ofFrozenTrialobjects. Each hasnumber,state,value,params,user_attrs,intermediate_values,datetime_startandduration. - Derived views: a pandas table from
study.trials_dataframe(), and parameter importances fromoptuna.importance.get_param_importances.
Trial states
Each trial ends in one state, and most mistakes in result reading come from ignoring the state.
| State | Meaning | Has a final value? |
|---|---|---|
| `COMPLETE` | The objective returned a value. | Yes |
| `PRUNED` | The objective raised `TrialPruned`. | No |
| `FAIL` | The objective raised another exception, or returned `nan`. | No |
| `RUNNING` | The trial is still in progress, possibly in another process. | No |
| `WAITING` | The trial is enqueued but not yet started. | No |
A pruned trial keeps the intermediate values it reported. These are useful for diagnosing why it was stopped, but they are not comparable with final values from completed trials.
A worked example
The script below runs a small study with pruning and a custom attribute, then reads the results three ways. trial.set_user_attr stores any JSON-serialisable value on the trial, such as a training time or a dataset hash.
import optuna
from optuna.trial import TrialState
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial):
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_float("y", -10, 10)
trial.set_user_attr("l1_norm", abs(x) + abs(y))
final = (x - 2) ** 2 + 0.1 * (y + 1) ** 2
for step in range(5):
trial.report(final + 1 / (step + 1), step)
if trial.should_prune():
raise optuna.TrialPruned()
return final
sampler = optuna.samplers.TPESampler(seed=0)
pruner = optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=1)
study = optuna.create_study(direction="minimize", sampler=sampler, pruner=pruner)
study.optimize(objective, n_trials=60)
complete = study.get_trials(deepcopy=False, states=(TrialState.COMPLETE,))
pruned = study.get_trials(deepcopy=False, states=(TrialState.PRUNED,))
print(f"complete={len(complete)} pruned={len(pruned)}")
best = study.best_trial
print("best number:", best.number)
print("best value:", best.value)
print("best params:", best.params)
print("best l1_norm:", best.user_attrs["l1_norm"])
df = study.trials_dataframe(attrs=("number", "value", "params", "state", "user_attrs"))
print(df.sort_values("value").head(5))Some points about this code:
get_trials(states=...)filters by state. Passingdeepcopy=Falseavoids copying every trial, which matters for studies with thousands of trials. Treat the returned objects as read-only in that case.trials_dataframenames columnsparams_<name>anduser_attrs_<name>. Pruned and failed trials haveNaNinvalue, so sort or filter by thestatecolumn first.best.user_attrsis the way to attach information that is not a hyperparameter, so you do not need a separate log file.
From records to plots
The optuna.visualization module turns a study into Plotly figures. Each function takes the study and returns a figure. Call .show() to open it in a browser or notebook. Call .write_html("name.html") to save a standalone file.
The common plots answer different questions:
| Function | Question it answers |
|---|---|
| `plot_optimization_history` | Is the best value still improving, or has the search stalled? |
| `plot_param_importances` | Which hyperparameters explain the most variation in the objective? |
| `plot_slice` | For each parameter alone, where do good and bad trials sit? |
| `plot_contour` | How do two parameters interact? |
| `plot_parallel_coordinate` | Which combinations of values lead to the best trials? |
| `plot_intermediate_values` | How did each trial's learning curve look, and where was it pruned? |
The next script draws these plots for a study without pruning. It saves them as HTML files so it also runs on a machine with no display.
import optuna
from optuna.visualization import (
plot_contour,
plot_optimization_history,
plot_param_importances,
plot_parallel_coordinate,
plot_slice,
)
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial):
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_float("y", -10, 10)
return (x - 2) ** 2 + 0.1 * (y + 1) ** 2
study = optuna.create_study(direction="minimize", sampler=optuna.samplers.TPESampler(seed=1))
study.optimize(objective, n_trials=80)
plot_optimization_history(study).write_html("history.html")
plot_param_importances(study).write_html("importances.html")
plot_slice(study, params=["x", "y"]).write_html("slice.html")
plot_contour(study, params=["x", "y"]).write_html("contour.html")
plot_parallel_coordinate(study, params=["x", "y"]).write_html("parallel.html")For this objective, x should have a much higher importance than y, because x has weight 1 and y has weight 0.1 over the same range. This gives you a check that the importance plot is believable.
Reading importances without a plot
plot_param_importances is built on a function you can call directly. It returns a dictionary of normalised scores that sum to 1, ordered from most to least important.
importances = optuna.importance.get_param_importances(study)
for name, score in importances.items():
print(f"{name}: {score:.3f}")The default evaluator is fANOVA, which fits a random forest to the completed trials. You can pass evaluator=optuna.importance.MeanDecreaseImpurityImportanceEvaluator() as a cheaper alternative. For multi-objective studies, pass target=lambda t: t.values[0] to choose which objective to explain.
Interpreting plots with care
Plots show what the sampler explored, and the sampler does not explore evenly.
- Sampling bias. TPE concentrates trials near good regions. A slice plot with many points clustered in one area reflects where the sampler looked, not a uniform survey of the space.
- Few trials. Importances from fewer than about 30 completed trials are noisy. Run the evaluation twice with different seeds. If the ranking changes, do not trust it.
- Pruned trials. History plots show only completed trials. If most trials are pruned, the history shows a small sample of the search.
- Interactions. Importance scores measure the effect of each parameter averaged over the others. Two parameters that only matter together may each look modest. Check the contour plot.
- Conditional spaces. A parameter that exists in only some trials, such as
svc_c, is analysed using only those trials. Importances for such parameters rest on fewer points.
Common errors
ImportErrororModuleNotFoundErrorforplotly: install it withpip install plotly. Importance plots also needscikit-learn, andtrials_dataframeneedspandas.ValueError: No trials are completed yet: the study has noCOMPLETEtrials, or you called a plot orbest_*too early.NaNin the dataframevaluecolumn: those rows are pruned, failed or running trials. Filter onstate == "COMPLETE".- A blank figure in a script:
.show()needs a browser or notebook. Use.write_htmlon servers.
Exercise
You run a study with 100 trials and 70 of them are pruned. A teammate sorts trials_dataframe() by value and takes the top row as the best trial. What is wrong with this, and what should they use instead?
Show answer
Pruned trials have NaN in value, so sorting can misplace or hide rows, and the dataframe mixes trials that never finished with completed ones. They should filter to rows where state is COMPLETE before sorting, or read study.best_trial directly. That property considers only completed trials and respects the study direction.