Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 3 additions & 2 deletions monai/losses/focal_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,9 @@ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:

elif self.reduction == LossReduction.MEAN.value:
if mask is not None:
# Sum loss over valid (non-ignored) elements, then divide by mask count
loss = loss.sum() / mask.sum().clamp(min=torch.finfo(mask.dtype).eps)
# Sum loss over valid (non-ignored) elements, then divide by the number of valid elements;
# the mask has a single channel, so count it once per channel of the loss
loss = loss.sum() / mask.expand_as(loss).sum().clamp(min=torch.finfo(mask.dtype).eps)
else:
loss = loss.mean()

Expand Down
16 changes: 16 additions & 0 deletions tests/losses/test_ignore_index_losses.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,22 @@ def test_loss_ignore_masked_mean(self, loss_class, kwargs):
loss2 = loss_ign(input_alt, target)
torch.testing.assert_close(loss1, loss2, atol=1e-5, rtol=1e-5)

@parameterized.expand([(True, True), (False, True), (True, False)])
def test_focal_loss_masked_mean_scale(self, use_softmax, include_background):
"""Ignoring voxels with FocalLoss gives the same mean as cropping them away.

Args:
use_softmax: whether FocalLoss uses softmax instead of sigmoid.
include_background: whether the background channel is included in the loss.
"""
kwargs = {"to_onehot_y": True, "use_softmax": use_softmax, "include_background": include_background}
input_data = torch.randn(2, 3, 4, 4)
target = torch.randint(0, 3, (2, 1, 4, 4))
target[:, :, :2] = 255
loss_ign = FocalLoss(ignore_index=255, **kwargs)
loss_ref = FocalLoss(**kwargs)
torch.testing.assert_close(loss_ign(input_data, target), loss_ref(input_data[:, :, 2:], target[:, :, 2:]))


if __name__ == "__main__":
unittest.main()