π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add reduction option to MS_SSIMLoss (#1655)
Jonas Maison6c519078e5a8
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.pyindex f41de5cb0..f44e8963b 100644--- a/kornia/losses/ms_ssim.py+++ b/kornia/losses/ms_ssim.py@@ -32,6 +32,10 @@ class MS_SSIMLoss(nn.Module):K: k values.alpha : specifies the alpha valuecompensation: specifies the scaling coefficient.+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.Returns:The computed loss.@@ -39,7 +43,7 @@ class MS_SSIMLoss(nn.Module):Shape:- Input1: :math:`(N, C, H, W)`.- Input2: :math:`(N, C, H, W)`.- - Output: :math:`(N,)` or scalar.+ - Output: :math:`(N, H, W)` or scalar if reduction is set to ``'mean'`` or ``'sum'``.Examples:>>> input1 = torch.rand(1, 3, 5, 5)@@ -55,6 +59,7 @@ class MS_SSIMLoss(nn.Module):K: Tuple[float, float] = (0.01, 0.03),alpha: float = 0.025,compensation: float = 200.0,+ reduction: str = 'mean',) -> None:super().__init__()self.DR: float = data_range@@ -63,6 +68,7 @@ class MS_SSIMLoss(nn.Module):self.pad = int(2 * sigmas[-1])self.alpha: float = alphaself.compensation: float = compensation+ self.reduction: str = reduction# Set filter sizefilter_size = int(4 * sigmas[-1] + 1)@@ -162,4 +168,12 @@ class MS_SSIMLoss(nn.Module):loss = self.alpha * loss_ms_ssim + (1 - self.alpha) * gaussian_l1 / self.DRloss = self.compensation * loss- return loss.mean()+ if self.reduction == "mean":+ loss = torch.mean(loss)+ elif self.reduction == "sum":+ loss = torch.sum(loss)+ elif self.reduction == "none":+ pass+ else:+ raise NotImplementedError(f"Invalid reduction mode: {self.reduction}")+ return lossdiff --git a/test/losses/test_ssim.py b/test/losses/test_ssim.pyindex 2e24cf6d7..498ed8250 100644--- a/test/losses/test_ssim.py+++ b/test/losses/test_ssim.py@@ -85,11 +85,12 @@ class TestMS_SSIMLoss:assert_close(msssim2.item(), 0.0)# TODO: implement for single channel image+ @pytest.mark.parametrize("reduction_type", ["mean", "sum"])@pytest.mark.parametrize("batch_shape", [(2, 1, 2, 3), (1, 3, 10, 16)])- def test_msssim(self, device, dtype, batch_shape):+ def test_msssim(self, device, dtype, batch_shape, reduction_type):img = torch.rand(batch_shape, device=device, dtype=dtype)- msssiml1 = kornia.losses.MS_SSIMLoss().to(device, dtype)+ msssiml1 = kornia.losses.MS_SSIMLoss(reduction=reduction_type).to(device, dtype)loss = msssiml1(img, img)assert_close(loss.item(), 0.0)