-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Add Dice Loss #6960
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
pri1311
wants to merge
11
commits into
pytorch:main
Choose a base branch
from
pri1311:dice
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add Dice Loss #6960
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
6532e35
add `dice_loss`
pri1311 248f50a
change formatting
pri1311 7dca543
add fixes
pri1311 636b7a7
Merge branch 'main' into dice
datumbox 8bf7638
change implementation for dice_loss
pri1311 fb8cefd
change documentation
pri1311 fcabd6a
add basic tests
pri1311 d7cafec
add addtional tests
pri1311 f087fc6
Merge branch 'main' into dice
pmeier fc39ee4
change input dimension from (B, H, W, C) to (B, C, H, W)
pri1311 dbb8aaa
add ref + fix linting
pri1311 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import torch | ||
import torch.nn.functional as F | ||
|
||
from ..utils import _log_api_usage_once | ||
|
||
|
||
def dice_loss(inputs: torch.Tensor, targets: torch.Tensor, reduction: str = "none", eps: float = 1e-8) -> torch.Tensor: | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
r"""Criterion that computes Sørensen-Dice Coefficient loss. | ||
|
||
We compute the Sørensen-Dice Coefficient as follows: | ||
|
||
.. math:: | ||
|
||
\text{Dice}(x, class) = \frac{2 |X \cap Y|}{|X| + |Y|} | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Where: | ||
- :math:`X` expects to be the scores of each class. | ||
- :math:`Y` expects to be thess tensor with the class labels. | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
the loss, is finally computed as: | ||
|
||
.. math:: | ||
|
||
\text{loss}(x, class) = 1 - \text{Dice}(x, class) | ||
|
||
Args: | ||
inputs: (Tensor): A float tensor of arbitrary shape. | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
The predictions for each example. | ||
targets: (Tensor): A float tensor with the same shape as inputs. Stores the binary | ||
classification label for each element in inputs | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
(0 for the negative class and 1 for the positive class). | ||
eps: (float, optional): Scalar to enforce numerical stabiliy. | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
reduction (string, optional): ``'none'`` | ``'mean'`` | ``'sum'`` | ||
``'none'``: No reduction will be applied to the output. | ||
``'mean'``: The output will be averaged. | ||
``'sum'``: The output will be summed. Default: ``'none'``. | ||
|
||
Return: | ||
Tensor: Loss tensor with the reduction option applied. | ||
""" | ||
|
||
if not torch.jit.is_scripting() and not torch.jit.is_tracing(): | ||
_log_api_usage_once(dice_loss) | ||
|
||
# compute softmax over the classes axis | ||
p = F.softmax(inputs, dim=1) | ||
|
||
# compute the actual dice score | ||
dims = (1, 2, 3) | ||
pri1311 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
intersection = torch.sum(p * targets, dims) | ||
cardinality = torch.sum(p + targets, dims) | ||
|
||
dice_score = 2.0 * intersection / (cardinality + eps) | ||
|
||
loss = 1.0 - dice_score | ||
|
||
# Check reduction option and return loss accordingly | ||
if reduction == "none": | ||
pass | ||
elif reduction == "mean": | ||
loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() | ||
elif reduction == "sum": | ||
loss = loss.sum() | ||
else: | ||
raise ValueError( | ||
f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" | ||
) | ||
|
||
return loss |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.