Skip to content

Callback

sklearn_optuna.optuna.Callback

Bases: BaseClassWrapper

Wrapper for Optuna callback classes invoked during optimization.

Parameters

Name Type Description Default
callback type

Optuna callback class to instantiate. The class must implement __call__(study, trial) to be invoked at the end of each trial.

required
**params dict

Parameters to pass to the callback constructor.

{}

See Also

sklearn_optuna.search.OptunaSearchCV : The main search class that uses callbacks. sklearn_optuna.optuna.Sampler : Wrapper for Optuna samplers.

Examples

>>> from optuna.study import MaxTrialsCallback
>>> callback = Callback(callback=MaxTrialsCallback, n_trials=100)

Source Code

Show/Hide source
class Callback(BaseClassWrapper):
    """Wrapper for Optuna callback classes invoked during optimization.

    Parameters
    ----------
    callback : type
        Optuna callback class to instantiate. The class must implement
        ``__call__(study, trial)`` to be invoked at the end of each trial.

    **params : dict
        Parameters to pass to the callback constructor.

    See Also
    --------
    sklearn_optuna.search.OptunaSearchCV : The main search class that uses callbacks.
    sklearn_optuna.optuna.Sampler : Wrapper for Optuna samplers.

    Examples
    --------
    >>> from optuna.study import MaxTrialsCallback
    >>> callback = Callback(callback=MaxTrialsCallback, n_trials=100)

    """

    _estimator_name = "callback"
    _estimator_base_class = object

    def __init__(self, callback: type, **params: dict[str, object]) -> None:
        if not isinstance(callback, type):
            raise TypeError(f"callback must be a class, got {type(callback)}")
        BaseClassWrapper.__init__(self, callback=callback, **params)

    def __call__(self, study: optuna.study.Study, trial: optuna.trial.FrozenTrial) -> None:
        """Invoke the callback by instantiating it and calling it.

        Parameters
        ----------
        study : optuna.study.Study
            The study object.

        trial : optuna.trial.FrozenTrial
            The completed trial.

        """
        return self.instance_(study, trial)

Methods

__call__(study, trial)

Invoke the callback by instantiating it and calling it.

Parameters
Name Type Description Default
study Study

The study object.

required
trial FrozenTrial

The completed trial.

required
Source Code
Show/Hide source
def __call__(self, study: optuna.study.Study, trial: optuna.trial.FrozenTrial) -> None:
    """Invoke the callback by instantiating it and calling it.

    Parameters
    ----------
    study : optuna.study.Study
        The study object.

    trial : optuna.trial.FrozenTrial
        The completed trial.

    """
    return self.instance_(study, trial)

Tutorials

The following example notebooks use this component:

  • How to Stop Optimization Early with Callbacks


    Stop unneeded work early by adding Optuna callbacks to your search.

    View · Open in marimo