tf.keras.losses.sparse_categorical_focal_crossentropy

Computes the sparse categorical focal crossentropy loss.

y_true Tensor of integer true targets.
y_pred Tensor of predicted targets.
alpha A weight balancing factor for all classes. Defaults to 0.25. It can be a list of floats or a scalar. If a list is provided, it must have the same length as the number of classes.
gamma A focusing parameter. Defaults to 2.0. It gradually reduces the importance given to easy examples. When gamma=0, there is no focal effect on the crossentropy loss.
from_logits Whether y_pred is expected to be a logits tensor. By default, y_pred is expected to encode a probability distribution.
ignore_class Optional integer. The ID of a class to be ignored during loss computation. This is useful, for example, in segmentation problems featuring a "void" class (commonly -1 or 255). By default (ignore_class=None), all classes are considered.
axis The axis along which to compute crossentropy (the features axis). Defaults to -1.

Sparse categorical focal crossentropy loss value.

An out-of-range, non-ignored label produces a NaN loss value. An alpha vector with a statically known wrong length raises ValueError; if its length or the class dimension is only known at runtime, a mismatch produces NaN loss values. This prevents backend-dependent index selection in compiled and symbolic execution, where Keras does not have a portable runtime assertion primitive.

Example:

y_true = [1, 2]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
loss = keras.losses.sparse_categorical_focal_crossentropy(
    y_true, y_pred
)
assert loss.shape == (2,)
loss
array([3.2058e-05, 4.6627e-01], dtype=float32)