Sub topic 9
Pruning with trial.report and trial.should_prune
This chapter assumes you can write an Optuna objective function and run a study. It also assumes you know what a validation score is and what an incremental training loop looks like.
Why prune
Most trials in a search are poor. If a trial trains for many steps, you can often tell after a few steps that it will not beat the best result so far. Pruning stops such a trial early and frees the time for new trials.
Pruning needs intermediate values. Your objective must therefore train in steps, such as epochs or boosting rounds. A model fitted in one call cannot be pruned.
The two calls
Two methods on the trial drive pruning:
trial.report(value, step)records an intermediate score at a step number.trial.should_prune()asks the study's pruner whether this trial should stop, based on the scores reported so far.
When should_prune() returns True, you raise optuna.TrialPruned. Optuna catches it and marks the trial as pruned.
A worked example
This objective trains an SGDClassifier for 20 steps with partial_fit. After each step it reports the validation accuracy and checks the pruner.
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)The MedianPruner stops a trial if its score at a step is worse than the median of other trials at the same step. Two settings keep it from pruning too early:
n_startup_trials=5lets the first five trials finish without pruning, so the median has data to compare against.n_warmup_steps=5ignores the first five steps of each trial, when scores are noisy.
Reading the outcome
Each trial ends in a state. You can count them from the study.
from optuna.trial import TrialState
pruned = study.get_trials(states=[TrialState.PRUNED])
complete = study.get_trials(states=[TrialState.COMPLETE])
print(len(pruned), "pruned,", len(complete), "complete")study.best_trial only considers completed trials. A pruned trial never wins, even if its last reported score was high.
Common errors
- Reporting without checking. Calling
trial.reportalone does nothing. You must also callshould_prune()and raise the exception. - Returning instead of raising. Returning the last score from a pruned trial records it as complete and corrupts the comparison. Always raise
TrialPruned. - Changing the metric between steps. Every step must report the same quantity, on the same scale, in the same direction as the study.
- Reusing a step number. Report each step once, in increasing order.
- Pruning on noisy early scores. Use warmup settings, or you will discard trials that would have improved.
Exercise
Your objective calls trial.report(acc, step) after every epoch, but no trial is ever pruned and every trial runs all epochs. What is missing?
Show answer
The objective never calls trial.should_prune() and raises optuna.TrialPruned when it returns True. Reporting only stores the value. The check and the raise are what stop the trial. Also confirm the study was created with a pruner, since the default can be too lenient early on.