Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

expose tgm.one_hot

edgarriba161a1c2f8102
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index 3f781c73f..826c6eb3b 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -3,7 +3,8 @@ torchgeometry.losses
.. currentmodule:: torchgeometry.losses
-.. autofunction:: ssim
+.. autofunction:: one_hot
+.. autofunction:: ssim
.. autofunction:: depth_smoothness_loss
.. autoclass:: SSIM
diff --git a/test/test_losses.py b/test/test_losses.py
index 1a8b5a642..84f2ba69a 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -9,7 +9,7 @@ from common import TEST_DEVICES
class TestDiceLoss:
- def test_make_one_hot(self):
+ def test_one_hot(self):
num_classes = 4
labels = torch.zeros(2, 2, 1, dtype=torch.int64)
labels[0, 0, 0] = 0
@@ -18,7 +18,7 @@ class TestDiceLoss:
labels[1, 1, 0] = 3
# convert labels to one hot tensor
- one_hot = tgm.losses.DiceLoss.make_one_hot(labels, num_classes)
+ one_hot = tgm.losses.one_hot(labels, num_classes)
assert pytest.approx(one_hot[0, labels[0, 0, 0], 0, 0].item(), 1.0)
assert pytest.approx(one_hot[0, labels[0, 1, 0], 1, 0].item(), 1.0)
diff --git a/torchgeometry/losses/__init__.py b/torchgeometry/losses/__init__.py
index 104770755..0b3d8bc32 100644
--- a/torchgeometry/losses/__init__.py
+++ b/torchgeometry/losses/__init__.py
@@ -1,3 +1,3 @@
from .ssim import SSIM, ssim
-from .dice import DiceLoss, dice_loss
+from .dice import DiceLoss, dice_loss, one_hot
from .depth_smooth import DepthSmoothnessLoss, depth_smoothness_loss
diff --git a/torchgeometry/losses/dice.py b/torchgeometry/losses/dice.py
index 44091cd62..e95e32164 100644
--- a/torchgeometry/losses/dice.py
+++ b/torchgeometry/losses/dice.py
@@ -4,12 +4,39 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-# Based on
-# https://github.com/tensorflow/models/blob/master/research/struct2depth/model.py#L625-L641
+def one_hot(labels: torch.Tensor, num_classes: int, device: torch.device=None, dtype: torch.dtype=None) -> torch.Tensor:
+ r"""Converts an integer label tensor to a one-hot 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.
+
+ Returns:
+ torch.Tensor: the labels in one hot tensor.
+ """
+ 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)
class DiceLoss(nn.Module):
- r"""Criterion that computes Dice Coefficient loss.
+ r"""Criterion that computes Sørensen-Dice Coefficient loss.
"""
def __init__(self,
smooth: Optional[float] = 1.0,
@@ -19,34 +46,6 @@ class DiceLoss(nn.Module):
self.reduction: str = reduction
self.eps: float = 1e-6
- @staticmethod
- def make_one_hot(labels: torch.Tensor, num_classes: int) -> torch.Tensor:
- r"""Converts an integer label tensor a one-hot labels 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.
- Returns:
- torch.Tensor: the labels in one hot tensor.
- """
- 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=labels.device)
- return one_hot.scatter_(1, labels.unsqueeze(1), 1.0)
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
if not torch.is_tensor(input):
@@ -66,8 +65,8 @@ class DiceLoss(nn.Module):
input_soft = F.softmax(input, dim=1)
# create the labels one hot tensor
- target_one_hot = self.make_one_hot(target, num_classes=input.shape[1])
- target_one_hot = target_one_hot.to(input.dtype)
+ target_one_hot = one_hot(target, num_classes=input.shape[1],
+ device=input.device, dtype=input.dtype)
# compute the actual dice score
numerator = torch.sum(input_soft * target_one_hot, dim=(1, 2, 3))