π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] Added differentiable Hausdorff Distance (HD) loss (#1254)
Jian Shi06884a08f710
diff --git a/docs/source/losses.rst b/docs/source/losses.rstindex f712f9f44..be4472bb5 100644--- a/docs/source/losses.rst+++ b/docs/source/losses.rst@@ -39,3 +39,5 @@ Module.. autoclass:: TotalVariation.. autoclass:: PSNRLoss.. autoclass:: BinaryFocalLossWithLogits+.. autoclass:: HausdorffERLoss+.. autoclass:: HausdorffERLoss3Ddiff --git a/docs/source/references.bib b/docs/source/references.bibindex 39f6b3eef..d6294c850 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -109,3 +109,14 @@booktitle={CVPR},year={2021}}++@article{karimi2019reducing,+ title={Reducing the hausdorff distance in medical image segmentation with convolutional neural networks},+ author={Karimi, Davood and Salcudean, Septimiu E},+ journal={IEEE Transactions on medical imaging},+ volume={39},+ number={2},+ pages={499--513},+ year={2019},+ publisher={IEEE}+}diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex 7171917c7..b7990a181 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -2,6 +2,7 @@ from .depth_smooth import inverse_depth_smoothness_loss, InverseDepthSmoothnessLfrom .dice import dice_loss, DiceLossfrom .divergence import js_div_loss_2d, kl_div_loss_2dfrom .focal import binary_focal_loss_with_logits, BinaryFocalLossWithLogits, focal_loss, FocalLoss+from .hausdorff import HausdorffERLoss, HausdorffERLoss3Dfrom .psnr import psnr, psnr_loss, PSNRLossfrom .ssim import SSIM, ssim, ssim_loss, SSIMLossfrom .total_variation import total_variation, TotalVariationdiff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.pynew file mode 100644index 000000000..bdcecca22--- /dev/null+++ b/kornia/losses/hausdorff.py@@ -0,0 +1,218 @@+from typing import Callable++import torch+import torch.nn as nn+++class _HausdorffERLossBase(nn.Module):+ """Base class for binary Hausdorff loss based on morphological erosion.++ This is an Hausdorff Distance (HD) Loss that based on morphological erosion,which provided+ a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.+ The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/+ blob/master/hausdorff_loss.py>`__.++ Args:+ alpha: controls the erosion rate in each iteration.+ k: the number of iterations of erosion.+ reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.+ 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,+ 'sum': the output will be summed.++ Returns:+ Estimated Hausdorff Loss.+ """++ conv: Callable+ max_pool: Callable++ def __init__(self, alpha: float = 2.0, k: int = 10, reduction: str = 'mean') -> None:+ super().__init__()+ self.alpha = alpha+ self.k = k+ self.reduction = reduction+ self.register_buffer("kernel", self.get_kernel())++ def get_kernel(self) -> torch.Tensor:+ """Get kernel for image morphology convolution."""+ raise NotImplementedError++ def perform_erosion(+ self, pred: torch.Tensor, target: torch.Tensor+ ) -> torch.Tensor:+ bound = (pred - target) ** 2++ kernel = torch.as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)+ eroded = torch.zeros_like(bound, device=pred.device, dtype=pred.dtype)+ mask = torch.ones_like(bound, device=pred.device, dtype=torch.bool)++ # Same padding, assuming kernel is odd and square (cube) shaped.+ # NOTE: int() has to be added for enabling JIT.+ padding = int((kernel.size(-1) - 1) // 2)+ for k in range(self.k):+ # compute convolution with kernel+ dilation = self.conv(bound, weight=kernel, padding=padding, groups=1)+ # apply soft thresholding at 0.5 and normalize+ erosion = dilation - 0.5+ erosion[erosion < 0] = 0++ # image-wise differences for 2D images+ erosion_max = self.max_pool(erosion)+ erosion_min = - self.max_pool(- erosion)+ # No normalization needed if `max - min = 0`+ _to_norm = (erosion_max - erosion_min) != 0+ to_norm = _to_norm.squeeze()+ if to_norm.any():+ # NOTE: avoid in-place ops like below, which will not pass gradcheck:+ # erosion[to_norm] = (erosion[to_norm] - erosion_min[to_norm]) / (+ # erosion_max[to_norm] - erosion_min[to_norm])+ _erosion_to_fill = (erosion - erosion_min) / (erosion_max - erosion_min)+ erosion = torch.where(mask * _to_norm, _erosion_to_fill, erosion)++ # save erosion and add to loss+ eroded = eroded + erosion * (k + 1) ** self.alpha+ bound = erosion++ return eroded++ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute Hausdorff loss.++ Args:+ pred: predicted tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.+ Each channel is as binary as: 1 -> fg, 0 -> bg.+ target: target tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.++ Returns:+ Estimated Hausdorff Loss.+ """+ if not (pred.shape[2:] == target.shape[2:] and pred.size(0) == target.size(0) and target.size(1) == 1):+ raise ValueError(+ "Prediction and target need to be of same size, and target should not be one-hot."+ f"Got {pred.shape} and {target.shape}."+ )+ if pred.size(1) < target.max().item():+ raise ValueError("Invalid target value.")++ out = torch.stack([+ self.perform_erosion(+ pred[:, i:i + 1],+ torch.where(+ target == i,+ torch.tensor(1, device=target.device, dtype=target.dtype),+ torch.tensor(0, device=target.device, dtype=target.dtype)+ )+ )+ for i in range(pred.size(1))+ ])+ if self.reduction == 'mean':+ return out.mean()+ elif self.reduction == 'sum':+ return out.sum()+ elif self.reduction == 'none':+ return out+ else:+ raise NotImplementedError(f"reduction `{self.reduction}` has not been implemented yet.")+++class HausdorffERLoss(_HausdorffERLossBase):+ """Binary Hausdorff loss based on morphological erosion.++ This is an Hausdorff Distance (HD) Loss that based on morphological erosion,which provided+ a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.+ The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/+ blob/master/hausdorff_loss.py>`__.++ Args:+ alpha: controls the erosion rate in each iteration.+ k: the number of iterations of erosion.+ reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.+ 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,+ 'sum': the output will be summed.++ Examples:+ >>> hdloss = HausdorffERLoss()+ >>> input = torch.randn(5, 3, 20, 20)+ >>> target = (torch.rand(5, 1, 20, 20) * 2).long()+ >>> res = hdloss(input, target)+ """++ conv = torch.conv2d+ max_pool = nn.AdaptiveMaxPool2d(1)++ def get_kernel(self) -> torch.Tensor:+ """Get kernel for image morphology convolution."""+ cross = torch.tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])+ kernel = cross * 0.2+ return kernel[None]++ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute Hausdorff loss.++ Args:+ pred: predicted tensor with a shape of :math:`(B, C, H, W)`.+ Each channel is as binary as: 1 -> fg, 0 -> bg.+ target: target tensor with a shape of :math:`(B, 1, H, W)`.++ Returns:+ Estimated Hausdorff Loss.+ """+ if pred.dim() != 4:+ raise ValueError(f"Only 2D images supported. Got {pred.dim()}.")+ if not (target.max() < pred.size(1) and target.min() >= 0 and target.dtype == torch.long):+ raise ValueError(+ f"Expect long type target value in range (0, {pred.size(1)})."+ f"({target.min()}, {target.max()})"+ )+ return super().forward(pred, target)+++class HausdorffERLoss3D(_HausdorffERLossBase):+ """Binary 3D Hausdorff loss based on morphological erosion.++ This is a 3D Hausdorff Distance (HD) Loss that based on morphological erosion,which provided+ a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.+ The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/+ blob/master/hausdorff_loss.py>`__.++ Args:+ alpha: controls the erosion rate in each iteration.+ k: the number of iterations of erosion.+ reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.+ 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,+ 'sum': the output will be summed.++ Examples:+ >>> hdloss = HausdorffERLoss3D()+ >>> input = torch.randn(5, 3, 20, 20, 20)+ >>> target = (torch.rand(5, 1, 20, 20, 20) * 2).long()+ >>> res = hdloss(input, target)+ """++ conv = torch.conv3d+ max_pool = nn.AdaptiveMaxPool3d(1)++ def get_kernel(self) -> torch.Tensor:+ """Get kernel for image morphology convolution."""+ cross = torch.tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])+ bound = torch.tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])+ # NOTE: The original repo claimed it shaped as (3, 1, 3, 3)+ # which Jian suspect it is wrongly implemented.+ # https://github.com/PatRyg99/HausdorffLoss/blob/9f580acd421af648e74b45d46555ccb7a876c27c/hausdorff_loss.py#L94+ kernel = torch.stack([bound, cross, bound], dim=1) * (1 / 7)+ return kernel[None]++ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute 3D Hausdorff loss.++ Args:+ pred: predicted tensor with a shape of :math:`(B, C, D, H, W)`.+ Each channel is as binary as: 1 -> fg, 0 -> bg.+ target: target tensor with a shape of :math:`(B, 1, D, H, W)`.++ Returns:+ Estimated Hausdorff Loss.+ """+ if pred.dim() != 5:+ raise ValueError(f"Only 3D images supported. Got {pred.dim()}.")+ return super().forward(pred, target)diff --git a/requirements-dev.txt b/requirements-dev.txtindex 1789f03b2..da1f9a889 100644--- a/requirements-dev.txt+++ b/requirements-dev.txt@@ -10,3 +10,4 @@ pre-commit>=2.0yapfisortnumpy+scipydiff --git a/test/losses/test_hd.py b/test/losses/test_hd.pynew file mode 100644index 000000000..212f40748--- /dev/null+++ b/test/losses/test_hd.py@@ -0,0 +1,185 @@+import numpy as np+import pytest+import torch+import torch.nn as nn+from scipy.ndimage import convolve+from torch.autograd import gradcheck++import kornia+import kornia.testing as utils+from kornia.testing import assert_close+++class HausdorffERLossNumpy(nn.Module):+ """Binary Hausdorff loss based on morphological erosion.++ Taken from https://github.com/PatRyg99/HausdorffLoss/blob/master/hausdorff_loss.py+ """++ def __init__(self, alpha=2.0, erosions=10, **kwargs):+ super().__init__()+ self.alpha = alpha+ self.erosions = erosions+ self.prepare_kernels()++ def prepare_kernels(self):+ cross = np.array([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])+ bound = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])++ self.kernel2D = cross * 0.2+ # NOTE: updated from np.array([bound, cross, bound]) * (1 / 7)+ self.kernel3D = np.array([bound, cross, bound]).squeeze()[None] * (1 / 7)++ @torch.no_grad()+ def perform_erosion(+ self, pred: np.ndarray, target: np.ndarray, debug+ ) -> np.ndarray:+ bound = (pred - target) ** 2++ if bound.ndim == 5:+ kernel = self.kernel3D+ elif bound.ndim == 4:+ kernel = self.kernel2D+ else:+ raise ValueError(f"Dimension {bound.ndim} is nor supported.")++ eroted = np.zeros_like(bound)+ erosions = []++ for batch in range(len(bound)):++ # debug+ erosions.append(np.copy(bound[batch][0]))++ for k in range(self.erosions):++ # compute convolution with kernel+ dilation = convolve(bound[batch], kernel, mode="constant", cval=0.0)++ # apply soft thresholding at 0.5 and normalize+ erosion = dilation - 0.5+ erosion[erosion < 0] = 0++ if erosion.ptp() != 0:+ erosion = (erosion - erosion.min()) / erosion.ptp()++ # save erosion and add to loss+ bound[batch] = erosion+ eroted[batch] += erosion * (k + 1) ** self.alpha+ if debug:+ erosions.append(np.copy(erosion[0]))++ # image visualization in debug mode+ if debug:+ return eroted, erosions+ else:+ return eroted++ def forward_one(+ self, pred: torch.Tensor, target: torch.Tensor, debug=False+ ) -> torch.Tensor:+ """+ Uses one binary channel: 1 - fg, 0 - bg+ pred: (b, 1, x, y, z) or (b, 1, x, y)+ target: (b, 1, x, y, z) or (b, 1, x, y)+ """+ assert pred.size(1) == target.size(1) == 1+ # pred = torch.sigmoid(pred)++ if debug:+ eroted, erosions = self.perform_erosion(+ pred.cpu().numpy(), target.cpu().numpy(), debug+ )+ return eroted.mean(), erosions++ else:+ eroted = torch.from_numpy(+ self.perform_erosion(pred.cpu().numpy(), target.cpu().numpy(), debug)+ ).to(dtype=pred.dtype, device=pred.device)++ loss = eroted.mean()++ return loss++ def forward(+ self, pred: torch.Tensor, target: torch.Tensor, debug=False+ ) -> torch.Tensor:+ """+ Uses one binary channel: 1 - fg, 0 - bg+ pred: (b, 1, x, y, z) or (b, 1, x, y)+ target: (b, 1, x, y, z) or (b, 1, x, y)+ """+ assert pred.dim() == 4 or pred.dim() == 5, "Only 2D and 3D supported"+ assert (+ pred.dim() == target.dim() and target.size(1) == 1+ ), "Prediction and target need to be of same dimension"+ return torch.stack([+ self.forward_one(+ pred[:, i:i + 1],+ torch.where(+ target == i,+ torch.tensor(1, device=target.device, dtype=target.dtype),+ torch.tensor(0, device=target.device, dtype=target.dtype))+ ) for i in range(pred.size(1))]).mean()+++class TestHausdorffLoss:++ @pytest.mark.parametrize("reduction", ['mean', 'none', 'sum'])+ @pytest.mark.parametrize("hd,shape", [+ [kornia.losses.HausdorffERLoss, (10, 10)],+ [kornia.losses.HausdorffERLoss3D, (10, 10, 10)],+ ])+ def test_smoke_none(self, hd, shape, reduction, device, dtype):+ num_classes = 3+ logits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)+ labels = (torch.rand(2, 1, *shape, dtype=dtype, device=device) * (num_classes - 1)).long()+ loss = hd(reduction=reduction)++ loss(logits, labels)++ @pytest.mark.parametrize("hd,shape", [+ [kornia.losses.HausdorffERLoss, (10, 10)],+ [kornia.losses.HausdorffERLoss3D, (10, 10, 10)],+ ])+ def test_jit(self, hd, shape, device, dtype):+ num_classes = 3+ logits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)+ labels = (torch.rand(2, 1, *shape, dtype=dtype, device=device) * (num_classes - 1)).long()+ loss = hd(k=2)++ op_script = torch.jit.trace(loss, (logits, labels))+ actual = op_script(logits, labels)+ expected = loss(logits, labels)+ assert_close(actual, expected)++ @pytest.mark.parametrize("hd,shape", [+ [kornia.losses.HausdorffERLoss, (100, 100)],+ [kornia.losses.HausdorffERLoss3D, (100, 100, 100)],+ ])+ def test_numeric(self, hd, shape, device, dtype):+ num_classes = 3+ logits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)+ labels = (torch.rand(2, 1, *shape, dtype=dtype, device=device) * (num_classes - 1)).long()+ loss = hd(k=10)+ loss_np = HausdorffERLossNumpy(erosions=10)++ expected = loss_np(logits, labels)+ actual = loss(logits, labels)+ assert_close(actual, expected)++ @pytest.mark.parametrize("hd,shape", [+ [kornia.losses.HausdorffERLoss, (10, 10)],+ [kornia.losses.HausdorffERLoss3D, (10, 10, 10)],+ ])+ @pytest.mark.skip(reason='It passed, but will take too much time to run.')+ def test_gradcheck(self, hd, shape, device):+ num_classes = 3+ logits = torch.rand(2, num_classes, *shape, device=device)+ labels = (torch.rand(2, 1, *shape, device=device) * (num_classes - 1)).long()+ loss = hd(k=2)++ logits = utils.tensor_to_gradcheck_var(logits) # to var+ assert gradcheck(+ loss, (logits, labels,), raise_exception=True+ )diff --git a/test/test_losses.py b/test/losses/test_losses.pysimilarity index 100%rename from test/test_losses.pyrename to test/losses/test_losses.py