Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement TverskyLoss

edgarribabe84cadae8c7
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index d7e7268b5..164e9ec68 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -5,9 +5,11 @@ torchgeometry.losses
.. autofunction:: one_hot
.. autofunction:: dice_loss
+.. autofunction:: tversky_loss
.. autofunction:: ssim
.. autofunction:: depth_smoothness_loss
.. autoclass:: DiceLoss
+.. autoclass:: TverskyLoss
.. autoclass:: SSIM
.. autoclass:: DepthSmoothnessLoss
diff --git a/mypy_files.txt b/mypy_files.txt
index 451337d22..61491692e 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -1,5 +1,6 @@
torchgeometry/image/gaussian.py
torchgeometry/losses/ssim.py
torchgeometry/losses/dice.py
+torchgeometry/losses/tversky.py
torchgeometry/losses/depth_smooth.py
torchgeometry/homography_warper.py
diff --git a/test/test_losses.py b/test/test_losses.py
index 8211badb0..dbbf592f4 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -8,8 +8,51 @@ import utils
from common import TEST_DEVICES
-class TestDiceLoss:
- def test_one_hot(self):
+class TestTverskyLoss:
+ def _test_smoke(self):
+ num_classes = 3
+ logits = torch.rand(2, num_classes, 3, 2)
+ labels = torch.rand(2, 3, 2) * num_classes
+ labels = labels.long()
+
+ criterion = tgm.losses.TverskyLoss(alpha=0.5, beta=0.5)
+ loss = criterion(logits, labels)
+
+ def _test_all_zeros(self):
+ num_classes = 3
+ logits = torch.zeros(2, num_classes, 1, 2)
+ logits[:, 0] = 10.0
+ logits[:, 1] = 1.0
+ logits[:, 2] = 1.0
+ labels = torch.zeros(2, 1, 2, dtype=torch.int64)
+
+ criterion = tgm.losses.TverskyLoss(alpha=0.5, beta=0.5)
+ loss = criterion(logits, labels)
+ assert pytest.approx(loss.item(), 0.0)
+
+ # TODO: implement me
+ def _test_jit(self):
+ pass
+
+ def _test_gradcheck(self):
+ num_classes = 3
+ alpha, beta = 0.5, 0.5 # for tversky loss
+ logits = torch.rand(2, num_classes, 3, 2)
+ labels = torch.rand(2, 3, 2) * num_classes
+ labels = labels.long()
+
+ logits = utils.tensor_to_gradcheck_var(logits) # to var
+ assert gradcheck(tgm.losses.tversky_loss,
+ (logits, labels, alpha, beta), raise_exception=True)
+
+ def test_run_all(self):
+ self._test_smoke()
+ self._test_all_zeros()
+ self._test_gradcheck()
+
+
+class TestOneHot:
+ def test_smoke(self):
num_classes = 4
labels = torch.zeros(2, 2, 1, dtype=torch.int64)
labels[0, 0, 0] = 0
@@ -25,6 +68,8 @@ class TestDiceLoss:
assert pytest.approx(one_hot[1, labels[1, 0, 0], 0, 0].item(), 1.0)
assert pytest.approx(one_hot[1, labels[1, 1, 0], 1, 0].item(), 1.0)
+
+class TestDiceLoss:
def _test_smoke(self):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2)
@@ -34,7 +79,6 @@ class TestDiceLoss:
criterion = tgm.losses.DiceLoss()
loss = criterion(logits, labels)
- # TODO: implement me
def _test_all_zeros(self):
num_classes = 3
logits = torch.zeros(2, num_classes, 1, 2)
diff --git a/torchgeometry/losses/__init__.py b/torchgeometry/losses/__init__.py
index 2e4350073..5a284f6e7 100644
--- a/torchgeometry/losses/__init__.py
+++ b/torchgeometry/losses/__init__.py
@@ -1,4 +1,5 @@
from .one_hot import one_hot
from .ssim import SSIM, ssim
from .dice import DiceLoss, dice_loss
+from .tversky import TverskyLoss, tversky_loss
from .depth_smooth import DepthSmoothnessLoss, depth_smoothness_loss
diff --git a/torchgeometry/losses/tversky.py b/torchgeometry/losses/tversky.py
index a2e69b27a..b56595329 100644
--- a/torchgeometry/losses/tversky.py
+++ b/torchgeometry/losses/tversky.py
@@ -4,80 +4,32 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-
-def one_hot(labels: torch.Tensor,
- num_classes: int,
- device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None) -> torch.Tensor:
- r"""Converts an integer label 2D tensor to a one-hot 3D tensor.
-
- Args:
- labels (torch.Tensor) : tensor with labels of shape :math:`(N, H, W)`,
- where N is batch siz. Each value is an integer
- representing correct classification.
- num_classes (int): number of classes in labels.
- device (Optional[torch.device]): the desired device of returned tensor.
- Default: if None, uses the current device for the default tensor type
- (see torch.set_default_tensor_type()). device will be the CPU for CPU
- tensor types and the current CUDA device for CUDA tensor types.
- dtype (Optional[torch.dtype]): the desired data type of returned
- tensor. Default: if None, infers data type from values.
-
- Returns:
- torch.Tensor: the labels in one hot tensor.
-
- Examples::
- >>> labels = torch.LongTensor([[[0, 1], [2, 0]]])
- >>> tgm.losses.one_hot(labels, num_classes=3)
- tensor([[[[1., 0.],
- [0., 1.]],
- [[0., 1.],
- [0., 0.]],
- [[0., 0.],
- [1., 0.]]]]
- """
- if not torch.is_tensor(labels):
- raise TypeError("Input labels type is not a torch.Tensor. Got {}"
- .format(type(labels)))
- if not len(labels.shape) == 3:
- raise ValueError("Invalid depth shape, we expect BxHxW. Got: {}"
- .format(labels.shape))
- if not labels.dtype == torch.int64:
- raise ValueError(
- "labels must be of the same dtype torch.int64. Got: {}" .format(
- labels.dtype))
- if num_classes < 1:
- raise ValueError("The number of classes must be bigger than one."
- " Got: {}".format(num_classes))
- batch_size, height, width = labels.shape
- one_hot = torch.zeros(batch_size, num_classes, height, width,
- device=device, dtype=dtype)
- return one_hot.scatter_(1, labels.unsqueeze(1), 1.0)
-
+from .one_hot import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
-class DiceLoss(nn.Module):
- r"""Criterion that computes Sørensen-Dice Coefficient loss.
- According to [1], we compute the Sørensen-Dice Coefficient as follows:
+class TverskyLoss(nn.Module):
+ r"""Criterion that computes Tversky Coeficient loss.
+
+ According to [1], we compute the Tversky Coefficient as follows:
.. math::
- \text{Dice}(x, class) = \frac{2 |X| \cap |Y|}{|X| + |Y|}
+ \text{S}(P, G, \alpha; \beta) =
+ \frac{|PG|}{|PG| + \alpha |P \ G| + \beta |G \ P|}
where:
- - :math:`X` expects to be the scores of each class.
- - :math:`Y` expects to be the one-hot tensor with the class labels.
-
- the loss, is finally computed as:
+ - :math:`P` and :math:`G` are the predicted and ground truth binary
+ labels.
+ - :math:`\alpha` and :math:`\beta` control the magnitude of the
+ penalties for FPs and FNs, respectively.
- .. math::
-
- \text{loss}(x, class) = 1 - \text{Dice}(x, class)
-
- [1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
+ Notes:
+ - :math:`\alpha = \beta = 0.5` => dice coeff
+ - :math:`\alpha = \beta = 1` => tanimoto coeff
+ - :math:`\alpha + \beta = 1` => F beta coeff
Shape:
- Input: :math:`(N, C, H, W)` where C = number of classes.
@@ -86,14 +38,20 @@ class DiceLoss(nn.Module):
Examples:
>>> N = 5 # num_classes
- >>> loss = tgm.losses.DiceLoss()
+ >>> loss = tgm.losses.TverskyLoss(alpha=0.5, beta=0.5)
>>> input = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = loss(input, target)
>>> output.backward()
+
+ References:
+ [1]: https://arxiv.org/abs/1706.05721
"""
- def __init__(self) -> None:
- super(DiceLoss, self).__init__()
+
+ def __init__(self, alpha: float, beta: float) -> None:
+ super(TverskyLoss, self).__init__()
+ self.alpha: float = alpha
+ self.beta: float = beta
self.eps: float = 1e-6
def forward(
@@ -123,10 +81,13 @@ class DiceLoss(nn.Module):
# compute the actual dice score
dims = (1, 2, 3)
intersection = torch.sum(input_soft * target_one_hot, dims)
- cardinality = torch.sum(input_soft + target_one_hot, dims)
+ fps = torch.sum(input_soft * (1. - target_one_hot), dims)
+ fns = torch.sum((1. - input_soft) * target_one_hot, dims)
- dice_score = 2. * intersection / (cardinality + self.eps)
- return torch.mean(1. - dice_score)
+ numerator = intersection
+ denominator = intersection + self.alpha * fps + self.beta * fns
+ tversky_loss = numerator / (denominator + self.eps)
+ return torch.mean(1. - tversky_loss)
######################
@@ -134,11 +95,13 @@ class DiceLoss(nn.Module):
######################
-def dice_loss(
+def tversky_loss(
input: torch.Tensor,
- target: torch.Tensor) -> torch.Tensor:
- r"""Function that computes Sørensen-Dice Coefficient loss.
+ target: torch.Tensor,
+ alpha: float,
+ beta: float) -> torch.Tensor:
+ r"""Function that computes Tversky loss.
- See :class:`~torchgeometry.losses.DiceLoss` for details.
+ See :class:`~torchgeometry.losses.TverskyLoss` for details.
"""
- return DiceLoss()(input, target)
+ return TverskyLoss(alpha, beta)(input, target)