diff --git a/monai/losses/focal_loss.py b/monai/losses/focal_loss.py index 1e7063e06f..03762ec7c8 100644 --- a/monai/losses/focal_loss.py +++ b/monai/losses/focal_loss.py @@ -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() diff --git a/tests/losses/test_ignore_index_losses.py b/tests/losses/test_ignore_index_losses.py index 20d512ed63..d861872554 100644 --- a/tests/losses/test_ignore_index_losses.py +++ b/tests/losses/test_ignore_index_losses.py @@ -141,6 +141,24 @@ 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 gives the same mean as cropping them away; an unused ignore_index changes nothing. + + 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_no_ignore = target.clone() + 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:])) + torch.testing.assert_close(loss_ign(input_data, target_no_ignore), loss_ref(input_data, target_no_ignore)) + if __name__ == "__main__": unittest.main()