Skip to content

Update to use log_sigmoid in FocalLoss #7534

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

Merged
merged 3 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
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
5 changes: 2 additions & 3 deletions monai/losses/focal_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,8 @@ def sigmoid_focal_loss(
"""
# computing binary cross entropy with logits
# equivalent to F.binary_cross_entropy_with_logits(input, target, reduction='none')
# see also https://github.com/pytorch/pytorch/blob/v1.9.0/aten/src/ATen/native/Loss.cpp#L231
max_val = (-input).clamp(min=0)
loss: torch.Tensor = input - input * target + max_val + ((-max_val).exp() + (-input - max_val).exp()).log()
# see also https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/Loss.cpp#L363
loss: torch.Tensor = input - input * target - F.logsigmoid(input)

# sigmoid(-i) if t==1; sigmoid(i) if t==0 <=>
# 1-sigmoid(i) if t==1; sigmoid(i) if t==0 <=>
Expand Down
2 changes: 1 addition & 1 deletion tests/test_focal_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def test_consistency_with_cross_entropy_2d_no_reduction(self):
error = np.abs(a - b)
max_error = np.maximum(error, max_error)

assert np.allclose(max_error, 0)
assert np.allclose(max_error, 0, atol=1e-6)

def test_consistency_with_cross_entropy_2d_onehot_label(self):
"""For gamma=0 the focal loss reduces to the cross entropy loss"""
Expand Down