Skip to content

[Documentation] Updated Categorical Focal Crossentropy Loss Docstring #21044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions keras/src/losses/losses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2143,10 +2143,21 @@ def categorical_focal_crossentropy(

>>> y_true = [[0, 1, 0], [0, 0, 1]]
>>> y_pred = [[0.05, 0.9, 0.05], [0.1, 0.85, 0.05]]
>>> loss = keras.losses.categorical_focal_crossentropy(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> loss
>>> # In this instance, the second example is the 'harder' example.
>>> focal_loss = keras.losses.categorical_focal_crossentropy(y_true, y_pred)
>>> assert focal_loss.shape == (2,)
>>> focal_loss
array([2.63401289e-04, 6.75912094e-01], dtype=float32)
>>> # Compare with categorical_crossentropy
>>> cce_loss = keras.losses.categorical_crossentropy(
... y_true, y_pred)
>>> cce_loss
array([0.10536054, 2.9957323], dtype=float32)
>>> # Categorical focal crossentropy loss attributes more importance to the
>>> # harder example which results in a higher loss for the second example
>>> # when normalized by categorical cross entropy loss
>>> focal_loss/cce_loss
array([0.0025 , 0.225625], dtype=float32)
"""
if isinstance(axis, bool):
raise ValueError(
Expand Down Expand Up @@ -2367,19 +2378,19 @@ def binary_focal_crossentropy(
>>> # 'easier' example.
>>> focal_loss = keras.losses.binary_focal_crossentropy(
... y_true, y_pred, gamma=2)
>>> assert loss.shape == (2,)
>>> assert focal_loss.shape == (2,)
>>> focal_loss
array([0.330, 0.206], dtype=float32)
>>> # Compare with binary_crossentropy
>>> bce_loss = keras.losses.binary_focal_crossentropy(
>>> bce_loss = keras.losses.binary_crossentropy(
... y_true, y_pred)
>>> bce_loss
array([0.916, 0.714], dtype=float32)
>>> # Binary focal crossentropy loss attributes more importance to the
>>> # harder example which results in a higher loss for the first batch
>>> # when normalized by binary cross entropy loss
>>> focal_loss/bce_loss
array([0.360, 0.289]
array([0.360, 0.289], dtype=float32)
"""
y_pred = ops.convert_to_tensor(y_pred)
y_true = ops.cast(y_true, y_pred.dtype)
Expand Down