class optuna.study.MaxTrialsCallback(n_trials, states=(TrialState.COMPLETE))[source]

Set a maximum number of trials before ending the study.

While the n_trials argument of optuna.optimize sets the number of trials that will be run, you may want to continue running until you have a certain number of successfullly completed trials or stop the study when you have a certain number of trials that fail. This MaxTrialsCallback class allows you to set a maximum number of trials for a particular TrialState before stopping the study.


import optuna
from optuna.study import MaxTrialsCallback
from optuna.trial import TrialState

def objective(trial):
    x = trial.suggest_float("x", -1, 1)
    return x ** 2

study = optuna.create_study()
    callbacks=[MaxTrialsCallback(10, states=(TrialState.COMPLETE,))],
  • n_trials – The max number of trials. Must be set to an integer.

  • states – Tuple of the TrialState to be counted towards the max trials limit. Default value is (TrialState.COMPLETE,).


Added in v2.8.0 as an experimental feature. The interface may change in newer versions without prior notice. See https://github.com/optuna/optuna/releases/tag/v2.8.0.