Skip to contents

This callback monitors the loss during training and terminates training when a NaN or Inf loss is detected. By default, training stops gracefully by setting the model's stop_training flag, which allows callback cleanup methods such as on_train_end() to run.

Set raise_error = TRUE to raise an error immediately when a NaN or Inf is detected. In this mode, on_train_end() is not called on other callbacks. This can preserve backup states or prevent unintended cleanup after a training failure.

Usage

callback_terminate_on_nan(raise_error = FALSE)

Arguments

raise_error

If FALSE, stop training gracefully. If TRUE, raise an error immediately when a NaN or Inf loss is detected, bypassing callback cleanup methods.

Value

A Callback instance that can be passed to fit.keras.src.models.model.Model().

Examples

# Graceful termination (default)
callback <- callback_terminate_on_nan()
model |> fit(x, y, callbacks = list(callback))

# Immediate error
callback <- callback_terminate_on_nan(raise_error = TRUE)
model |> fit(x, y, callbacks = list(callback))