Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Fix] Refactor psnr and ssim losses (#847)

Edgar Riba65364d97ebbd
diff --git a/docs/source/losses.rst b/docs/source/losses.rst
index 54a8c1139..f712f9f44 100644
--- a/docs/source/losses.rst
+++ b/docs/source/losses.rst
@@ -7,6 +7,8 @@ Reconstruction
--------------
.. autofunction:: ssim
+.. autofunction:: ssim_loss
+.. autofunction:: psnr
.. autofunction:: psnr_loss
.. autofunction:: total_variation
.. autofunction:: inverse_depth_smoothness_loss
@@ -14,6 +16,7 @@ Reconstruction
Semantic Segmentation
---------------------
+.. autofunction:: binary_focal_loss_with_logits
.. autofunction:: focal_loss
.. autofunction:: dice_loss
.. autofunction:: tversky_loss
@@ -31,6 +34,8 @@ Module
.. autoclass:: TverskyLoss
.. autoclass:: FocalLoss
.. autoclass:: SSIM
+.. autoclass:: SSIMLoss
.. autoclass:: InverseDepthSmoothnessLoss
.. autoclass:: TotalVariation
.. autoclass:: PSNRLoss
+.. autoclass:: BinaryFocalLossWithLogits
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 07633b7d3..d8c50d28b 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -1,4 +1,4 @@
-from .ssim import SSIM, ssim
+from .ssim import SSIM, ssim, SSIMLoss, ssim_loss
from .dice import DiceLoss, dice_loss
from .tversky import TverskyLoss, tversky_loss
from .focal import FocalLoss, focal_loss, BinaryFocalLossWithLogits, binary_focal_loss_with_logits
@@ -7,4 +7,4 @@ from .depth_smooth import (
)
from .divergence import kl_div_loss_2d, js_div_loss_2d
from .total_variation import TotalVariation, total_variation
-from .psnr import PSNRLoss, psnr_loss
+from .psnr import PSNRLoss, psnr_loss, psnr
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 483c31033..b03d999fb 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -38,18 +38,20 @@ def js_div_loss_2d(
):
r"""Calculates the Jensen-Shannon divergence loss between heatmaps.
- Arguments:
- input (torch.Tensor): the input tensor.
- target (torch.Tensor): the target tensor.
+ Args:
+ input (torch.Tensor): the input tensor with shape :math:`(B, N, H, W)`.
+ target (torch.Tensor): the target tensor with shape :math:`(B, N, H, W)`.
reduction (string, optional): 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. Default: ``'mean'``.
-
- Shape:
- - Input: :math:`(B, N, H, W)`
- - Target: :math:`(B, N, H, W)`, same shape as the input
+ 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. Default: `mean`.
+
+ Examples:
+ >>> input = torch.full((1, 1, 2, 4), 0.125)
+ >>> loss = js_div_loss_2d(input, input)
+ >>> loss.item()
+ 0.0
"""
return _reduce_loss(_js_div_2d(target, input), reduction)
@@ -61,17 +63,19 @@ def kl_div_loss_2d(
):
r"""Calculates the Kullback-Leibler divergence loss between heatmaps.
- Arguments:
- input (torch.Tensor): the input tensor.
- target (torch.Tensor): the target tensor.
+ Args:
+ input (torch.Tensor): the input tensor with shape :math:`(B, N, H, W)`.
+ target (torch.Tensor): the target tensor with shape :math:`(B, N, H, W)`.
reduction (string, optional): 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. Default: ``'mean'``.
-
- Shape:
- - Input: :math:`(B, N, H, W)`
- - Target: :math:`(B, N, H, W)`, same shape as the input
+ 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. Default: `mean`.
+
+ Examples:
+ >>> input = torch.full((1, 1, 2, 4), 0.125)
+ >>> loss = js_div_loss_2d(input, input)
+ >>> loss.item()
+ 0.0
"""
return _reduce_loss(_kl_div_2d(target, input), reduction)
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 01835e732..cfbac4455 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -147,7 +147,7 @@ class FocalLoss(nn.Module):
def binary_focal_loss_with_logits(
- inp: torch.Tensor,
+ input: torch.Tensor,
target: torch.Tensor,
alpha: float = .25,
gamma: float = 2.0,
@@ -155,44 +155,46 @@ def binary_focal_loss_with_logits(
eps: float = 1e-8) -> torch.Tensor:
r"""Function that computes Binary Focal loss.
- args:
- inp (torch.Tensor) : input data tensor
- target (torch.Tensor): the target tensor
- alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`. Default: 0.25.
- gamma (float): Focusing parameter :math:`\gamma >= 0`. Default: 2.0.
- reduction (str, optional): Specifies the reduction to apply to the. Default: 'none'.
+ .. math::
+
+ \text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)
+
+ where:
+ - :math:`p_t` is the model's estimated probability for each class.
+
+ Args:
+ input (torch.Tensor): input data tensor with shape :math:`(N, 1, *)`.
+ target (torch.Tensor): the target tensor with shape :math:`(N, 1, *)`.
+ alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`. Default: 0.25.
+ gamma (float): Focusing parameter :math:`\gamma >= 0`. Default: 2.0.
+ reduction (str, optional): Specifies the reduction to apply to the. Default: 'none'.
eps (float): for numerically stability when dividing. Default: 1e-8.
- returns:
- torch.tensor: loss
+ Returns:
+ torch.tensor: the computed loss.
Examples:
- >>> num_classes = 1
- >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
- >>> logits = torch.tensor([[[[6.325]]],[[[5.26]]],[[[87.49]]]])
- >>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
- >>> binary_focal_loss_with_logits(logits, labels, **kwargs)
- tensor(4.6052)
+ >>> num_classes = 1
+ >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
+ >>> logits = torch.tensor([[[[6.325]]],[[[5.26]]],[[[87.49]]]])
+ >>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
+ >>> binary_focal_loss_with_logits(logits, labels, **kwargs)
+ tensor(4.6052)
"""
- if not isinstance(inp, torch.Tensor):
+ if not isinstance(input, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(inp)))
+ .format(type(input)))
- if not len(inp.shape) >= 2:
+ if not len(input.shape) >= 2:
raise ValueError("Invalid input shape, we expect BxCx*. Got: {}"
- .format(inp.shape))
+ .format(input.shape))
- if inp.size(0) != target.size(0):
+ if input.size(0) != target.size(0):
raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
- .format(inp.size(0), target.size(0)))
-
- if not inp.device == target.device:
- raise ValueError(
- "input and target must be in the same device. Got: {} and {}".format(
- inp.device, target.device))
+ .format(input.size(0), target.size(0)))
- probs = torch.sigmoid(inp)
+ probs = torch.sigmoid(input)
target = target.unsqueeze(dim=1)
loss_tmp = -alpha * torch.pow((1. - probs), gamma) * target * torch.log(probs + eps) \
- (1 - alpha) * torch.pow(probs, gamma) * (1. - target) * torch.log(1. - probs + eps)
@@ -222,8 +224,7 @@ class BinaryFocalLossWithLogits(nn.Module):
where:
- :math:`p_t` is the model's estimated probability for each class.
-
- Arguments:
+ Args:
alpha (float): Weighting factor for the rare class :math:`\alpha \in [0, 1]`.
gamma (float): Focusing parameter :math:`\gamma >= 0`.
reduction (str, optional): Specifies the reduction to apply to the
@@ -232,8 +233,8 @@ class BinaryFocalLossWithLogits(nn.Module):
in the output, ‘sum’: the output will be summed. Default: ‘none’.
Shape:
- - Input: :math:`(N, 1, *)`
- - Target: :math:`(N, 1, *)`
+ - Input: :math:`(N, 1, *)`.
+ - Target: :math:`(N, 1, *)`.
Examples:
>>> N = 1 # num_classes
@@ -253,8 +254,6 @@ class BinaryFocalLossWithLogits(nn.Module):
self.reduction: str = reduction
self.eps: float = 1e-8
- def forward(
- self,
- input: torch.Tensor,
- target: torch.Tensor) -> torch.Tensor:
- return binary_focal_loss_with_logits(input, target, self.alpha, self.gamma, self.reduction, self.eps)
+ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ return binary_focal_loss_with_logits(
+ input, target, self.alpha, self.gamma, self.reduction, self.eps)
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index ce91d374c..e66287619 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -1,10 +1,13 @@
import torch
import torch.nn as nn
-from torch.nn.functional import mse_loss
+from torch.nn.functional import mse_loss as mse
-class PSNRLoss(nn.Module):
- r"""Creates a criterion that calculates the PSNR between 2 images. Given an m x n image, the PSNR is:
+def psnr(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
+ r"""Creates a function that calculates the PSNR between 2 images.
+
+ PSNR is Peek Signal to Noise Ratio, which is similar to mean squared error.
+ Given an m x n image, the PSNR is:
.. math::
@@ -19,41 +22,88 @@ class PSNRLoss(nn.Module):
and :math:`\text{MAX}_I` is the maximum possible input value
(e.g for floating point images :math:`\text{MAX}_I=1`).
+ Args:
+ input (torch.Tensor): the input image with arbitrary shape :math:`(*)`.
+ labels (torch.Tensor): the labels image with arbitrary shape :math:`(*)`.
+ max_val (float): The maximum value in the input tensor.
- Arguments:
- max_val (float): Maximum value of input
-
- Shape:
- - input: :math:`(*)`
- - approximation: :math:`(*)` same shape as input
- - output: :math:`()` a scalar
+ Return:
+ torch.Tensor: the computed loss as a scalar.
Examples:
- >>> psnr_loss(torch.ones(1), 1.2*torch.ones(1), 2) # 10 * log(4/((1.2-1)**2)) / log(10)
+ >>> ones = torch.ones(1)
+ >>> psnr(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)
tensor(20.0000)
Reference:
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition
"""
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Expected torch.Tensor but got {type(target)}.")
- def __init__(self, max_val: float) -> None:
- super(PSNRLoss, self).__init__()
- self.max_val: float = max_val
+ if not isinstance(target, torch.Tensor):
+ raise TypeError(f"Expected torch.Tensor but got {type(input)}.")
- def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: # type: ignore
- return psnr_loss(input, target, self.max_val)
+ if input.shape != target.shape:
+ raise TypeError(f"Expected tensors of equal shapes, but got {input.shape} and {target.shape}")
+
+ return 10. * torch.log10(max_val ** 2 / mse(input, target, reduction='mean'))
def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
- r"""Function that computes PSNR
+ r"""Function that computes the PSNR loss.
+
+ The loss is computed as follows:
+
+ .. math::
+
+ \text{loss} = -\text{psnr(x, y)}
+
+ See :meth:`~kornia.losses.psnr` for details abut PSNR.
- See :class:`~kornia.losses.PSNRLoss` for details.
+ Args:
+ input (torch.Tensor): the input image with shape :math:`(*)`.
+ labels (torch.Tensor): the labels image with shape :math:`(*)`.
+ max_val (float): The maximum value in the input tensor.
+
+ Return:
+ torch.Tensor: the computed loss as a scalar.
+
+ Examples:
+ >>> ones = torch.ones(1)
+ >>> psnr_loss(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)
+ tensor(-20.0000)
"""
- if not torch.is_tensor(input) or not torch.is_tensor(target):
- raise TypeError(f"Expected 2 torch tensors but got {type(input)} and {type(target)}")
- if input.shape != target.shape:
- raise TypeError(f"Expected tensors of equal shapes, but got {input.shape} and {target.shape}")
- mse_val = mse_loss(input, target, reduction='mean')
- max_val_tensor: torch.Tensor = torch.tensor(max_val).to(input.device).to(input.dtype)
- return 10 * torch.log10(max_val_tensor * max_val_tensor / mse_val)
+ return -1. * psnr(input, target, max_val)
+
+
+class PSNRLoss(nn.Module):
+ r"""Creates a criterion that calculates the PSNR loss.
+
+ The loss is computed as follows:
+
+ .. math::
+
+ \text{loss} = -\text{psnr(x, y)}
+
+ See :meth:`~kornia.losses.psnr` for details abut PSNR.
+
+ Shape:
+ - Input: arbitrary dimensional tensor :math:`(*)`.
+ - Target: arbitrary dimensional tensor :math:`(*)` same shape as input.
+ - Output: a scalar.
+
+ Examples:
+ >>> ones = torch.ones(1)
+ >>> criterion = PSNRLoss(2.)
+ >>> criterion(ones, 1.2 * ones) # 10 * log(4/((1.2-1)**2)) / log(10)
+ tensor(-20.0000)
+ """
+
+ def __init__(self, max_val: float) -> None:
+ super(PSNRLoss, self).__init__()
+ self.max_val: float = max_val
+
+ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ return psnr_loss(input, target, self.max_val)
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index d9c6c6358..cf5ced78c 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -7,14 +7,11 @@ import torch.nn.functional as F
from kornia.filters import get_gaussian_kernel2d, filter2D
-def _compute_zero_padding(kernel_size: int) -> int:
- """Computes zero padding."""
- return (kernel_size - 1) // 2
+def ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int,
+ max_val: float = 1.0, eps: float = 1e-12) -> torch.Tensor:
+ r"""Function that computes the Structural Similarity (SSIM) index map between two images.
-
-class SSIM(nn.Module):
- r"""Creates a criterion that measures the Structural Similarity (SSIM)
- index between each element in the input `x` and target `y`.
+ Measures the (SSIM) index between each element in the input `x` and target `y`.
The index can be described as:
@@ -29,135 +26,203 @@ class SSIM(nn.Module):
- :math:`L` is the dynamic range of the pixel-values (typically this is
:math:`2^{\#\text{bits per pixel}}-1`).
- the loss, or the Structural dissimilarity (DSSIM) can be finally described
- as:
+ Args:
+ img1 (torch.Tensor): the first input image with shape :math:`(B, C, H, W)`.
+ img2 (torch.Tensor): the second input image with shape :math:`(B, C, H, W)`.
+ window_size (int): the size of the gaussian kernel to smooth the images.
+ max_val (float): the dynamic range of the images. Default: 1.
+ eps (float): Small value for numerically stability when dividing. Default: 1e-12.
+
+ Returns:
+ torch.Tensor: The ssim index map with shape :math:`(B, C, H, W)`.
+
+ Examples:
+ >>> input1 = torch.rand(1, 4, 5, 5)
+ >>> input2 = torch.rand(1, 4, 5, 5)
+ >>> ssim_map = ssim(input1, input2, 5) # 1x4x5x5
+ """
+ if not isinstance(img1, torch.Tensor):
+ raise TypeError("Input img1 type is not a torch.Tensor. Got {}"
+ .format(type(img1)))
+
+ if not isinstance(img2, torch.Tensor):
+ raise TypeError("Input img2 type is not a torch.Tensor. Got {}"
+ .format(type(img2)))
+
+ if not isinstance(max_val, float):
+ raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")
+
+ if not len(img1.shape) == 4:
+ raise ValueError("Invalid img1 shape, we expect BxCxHxW. Got: {}"
+ .format(img1.shape))
+
+ if not len(img2.shape) == 4:
+ raise ValueError("Invalid img2 shape, we expect BxCxHxW. Got: {}"
+ .format(img2.shape))
+
+ if not img1.shape == img2.shape:
+ raise ValueError("img1 and img2 shapes must be the same. Got: {} and {}"
+ .format(img1.shape, img2.shape))
+
+ # prepare kernel
+ kernel: torch.Tensor = (
+ get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5)).unsqueeze(0)
+ )
+
+ # compute coefficients
+ C1: float = (0.01 * max_val) ** 2
+ C2: float = (0.03 * max_val) ** 2
+
+ # compute local mean per channel
+ mu1: torch.Tensor = filter2D(img1, kernel)
+ mu2: torch.Tensor = filter2D(img2, kernel)
+
+ mu1_sq = mu1.pow(2)
+ mu2_sq = mu2.pow(2)
+ mu1_mu2 = mu1 * mu2
+
+ # compute local sigma per channel
+ sigma1_sq = filter2D(img1 * img1, kernel) - mu1_sq
+ sigma2_sq = filter2D(img2 * img2, kernel) - mu2_sq
+ sigma12 = filter2D(img1 * img2, kernel) - mu1_mu2
+
+ # compute the similarity index map
+ num: torch.Tensor = (2. * mu1_mu2 + C1) * (2. * sigma12 + C2)
+ den: torch.Tensor = (
+ (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
+ )
+
+ return num / (den + eps)
+
+
+def ssim_loss(img1: torch.Tensor, img2: torch.Tensor, window_size: int,
+ max_val: float = 1.0, eps: float = 1e-12, reduction: str = 'mean') -> torch.Tensor:
+ r"""Function that computes a loss based on the SSIM measurement.
+
+ The loss, or the Structural dissimilarity (DSSIM) is described as:
.. math::
\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}
- Arguments:
- window_size (int): the size of the kernel.
+ See :meth:`~kornia.losses.ssim` for details about SSIM.
+
+ Args:
+ img1 (torch.Tensor): the first input image with shape :math:`(B, C, H, W)`.
+ img2 (torch.Tensor): the second input image with shape :math:`(B, C, H, W)`.
+ window_size (int): the size of the gaussian kernel to smooth the images.
max_val (float): the dynamic range of the images. Default: 1.
+ eps (float): Small value for numerically stability when dividing. Default: 1e-12.
reduction (str, optional): 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. Default: 'none'.
+ in the output, 'sum': the output will be summed. Default: 'mean'.
Returns:
- Tensor: the ssim index.
-
- Shape:
- - Input: :math:`(B, C, H, W)`
- - Target :math:`(B, C, H, W)`
- - Output: scale, if reduction is 'none', then :math:`(B, C, H, W)`
-
- Examples::
+ torch.Tensor: The loss based on the ssim index.
+ Examples:
>>> input1 = torch.rand(1, 4, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5)
- >>> ssim = SSIM(5, reduction='none')
- >>> loss = ssim(input1, input2) # 1x4x5x5
+ >>> loss = ssim_loss(input1, input2, 5)
"""
+ # compute the ssim map
+ ssim_map: torch.Tensor = ssim(img1, img2, window_size, max_val, eps)
- def __init__(
- self,
- window_size: int,
- reduction: str = "none",
- max_val: float = 1.0) -> None:
- super(SSIM, self).__init__()
- self.window_size: int = window_size
- self.max_val: float = max_val
- self.reduction: str = reduction
-
- self.window: torch.Tensor = get_gaussian_kernel2d(
- (window_size, window_size), (1.5, 1.5))
- self.window = self.window.requires_grad_(False) # need to disable gradients
+ # compute and reduce the loss
+ loss = torch.clamp(1. - ssim_map, min=0, max=1) / 2.
- self.padding: int = _compute_zero_padding(window_size)
+ if reduction == "mean":
+ loss = torch.mean(loss)
+ elif reduction == "sum":
+ loss = torch.sum(loss)
+ elif reduction == "none":
+ pass
+ return loss
- self.C1: float = (0.01 * self.max_val) ** 2
- self.C2: float = (0.03 * self.max_val) ** 2
- def forward( # type: ignore
- self,
- img1: torch.Tensor,
- img2: torch.Tensor) -> torch.Tensor:
+class SSIM(nn.Module):
+ r"""Creates a module that computes the Structural Similarity (SSIM) index between two images.
- if not torch.is_tensor(img1):
- raise TypeError("Input img1 type is not a torch.Tensor. Got {}"
- .format(type(img1)))
+ Measures the (SSIM) index between each element in the input `x` and target `y`.
- if not torch.is_tensor(img2):
- raise TypeError("Input img2 type is not a torch.Tensor. Got {}"
- .format(type(img2)))
+ The index can be described as:
- if not len(img1.shape) == 4:
- raise ValueError("Invalid img1 shape, we expect BxCxHxW. Got: {}"
- .format(img1.shape))
+ .. math::
- if not len(img2.shape) == 4:
- raise ValueError("Invalid img2 shape, we expect BxCxHxW. Got: {}"
- .format(img2.shape))
+ \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}
+ {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}
- if not img1.shape == img2.shape:
- raise ValueError("img1 and img2 shapes must be the same. Got: {} and {}"
- .format(img1.shape, img2.shape))
+ where:
+ - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to
+ stabilize the division with weak denominator.
+ - :math:`L` is the dynamic range of the pixel-values (typically this is
+ :math:`2^{\#\text{bits per pixel}}-1`).
- if not img1.device == img2.device:
- raise ValueError("img1 and img2 must be in the same device. Got: {} and {}"
- .format(img1.device, img2.device))
+ Args:
+ window_size (int): the size of the gaussian kernel to smooth the images.
+ max_val (float): the dynamic range of the images. Default: 1.
+ eps (float): Small value for numerically stability when dividing. Default: 1e-12.
- if not img1.dtype == img2.dtype:
- raise ValueError("img1 and img2 must be in the same dtype. Got: {} and {}"
- .format(img1.dtype, img2.dtype))
+ Shape:
+ - Input: :math:`(B, C, H, W)`.
+ - Target :math:`(B, C, H, W)`.
+ - Output: :math:`(B, C, H, W)`.
- # prepare kernel
- b, c, h, w = img1.shape
- tmp_kernel: torch.Tensor = self.window.to(img1.device).to(img1.dtype)
- tmp_kernel = torch.unsqueeze(tmp_kernel, dim=0)
+ Examples:
+ >>> input1 = torch.rand(1, 4, 5, 5)
+ >>> input2 = torch.rand(1, 4, 5, 5)
+ >>> ssim = SSIM(5)
+ >>> ssim_map = ssim(input1, input2) # 1x4x5x5
+ """
- # compute local mean per channel
- mu1: torch.Tensor = filter2D(img1, tmp_kernel)
- mu2: torch.Tensor = filter2D(img2, tmp_kernel)
+ def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12) -> None:
+ super(SSIM, self).__init__()
+ self.window_size: int = window_size
+ self.max_val: float = max_val
+ self.eps = eps
- mu1_sq = mu1.pow(2)
- mu2_sq = mu2.pow(2)
- mu1_mu2 = mu1 * mu2
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
+ return ssim(img1, img2, self.window_size, self.max_val, self.eps)
- # compute local sigma per channel
- sigma1_sq = filter2D(img1 * img1, tmp_kernel) - mu1_sq
- sigma2_sq = filter2D(img2 * img2, tmp_kernel) - mu2_sq
- sigma12 = filter2D(img1 * img2, tmp_kernel) - mu1_mu2
- ssim_map = ((2. * mu1_mu2 + self.C1) * (2. * sigma12 + self.C2)) / \
- ((mu1_sq + mu2_sq + self.C1) * (sigma1_sq + sigma2_sq + self.C2))
+class SSIMLoss(nn.Module):
+ r"""Creates a criterion that computes a loss based on the SSIM measurement.
- loss = torch.clamp(-ssim_map + 1., min=0, max=1) / 2.
+ The loss, or the Structural dissimilarity (DSSIM) is described as:
- if self.reduction == "mean":
- loss = torch.mean(loss)
- elif self.reduction == "sum":
- loss = torch.sum(loss)
- elif self.reduction == "none":
- pass
- return loss
+ .. math::
+ \text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}
-######################
-# functional interface
-######################
+ See :meth:`~kornia.losses.ssim_loss` for details about SSIM.
+ Args:
+ window_size (int): the size of the gaussian kernel to smooth the images.
+ max_val (float): the dynamic range of the images. Default: 1.
+ eps (float): Small value for numerically stability when dividing. Default: 1e-12.
+ reduction (str, optional): 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. Default: 'mean'.
-def ssim(
- img1: torch.Tensor,
- img2: torch.Tensor,
- window_size: int,
- reduction: str = "none",
- max_val: float = 1.0) -> torch.Tensor:
- r"""Function that measures the Structural Similarity (SSIM) index between
- each element in the input `x` and target `y`.
+ Returns:
+ torch.Tensor: The loss based on the ssim index.
- See :class:`~kornia.losses.SSIM` for details.
+ Examples:
+ >>> input1 = torch.rand(1, 4, 5, 5)
+ >>> input2 = torch.rand(1, 4, 5, 5)
+ >>> criterion = SSIMLoss(5)
+ >>> loss = criterion(input1, input2)
"""
- return SSIM(window_size, reduction, max_val)(img1, img2)
+
+ def __init__(self, window_size: int, max_val: float = 1.0,
+ eps: float = 1e-12, reduction: str = 'mean') -> None:
+ super(SSIMLoss, self).__init__()
+ self.window_size: int = window_size
+ self.max_val: float = max_val
+ self.eps: float = eps
+ self.reduction: str = reduction
+
+ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:
+ return ssim_loss(img1, img2, self.window_size, self.max_val, self.eps, self.reduction)
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 4abacfab5..4d0fd7e6e 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -2,16 +2,48 @@ import torch
import torch.nn as nn
+def total_variation(img: torch.Tensor) -> torch.Tensor:
+ r"""Function that computes Total Variation according to [1].
+
+ Args:
+ img (torch.Tensor): the input image with shape :math:`(N, C, H, W)` or :math:`(C, H, W)`.
+
+ Return:
+ torch.Tensor: a scalar with the computer loss.
+
+ Examples:
+ >>> total_variation(torch.ones(3, 4, 4))
+ tensor(0.)
+
+ Reference:
+ [1] https://en.wikipedia.org/wiki/Total_variation
+ """
+ if not isinstance(img, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(img)}")
+
+ if len(img.shape) < 3 or len(img.shape) > 4:
+ raise ValueError(
+ f"Expected input tensor to be of ndim 3 or 4, but got {len(img.shape)}."
+ )
+
+ pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]
+ pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]
+
+ reduce_axes = (-3, -2, -1)
+ res1 = pixel_dif1.abs().sum(dim=reduce_axes)
+ res2 = pixel_dif2.abs().sum(dim=reduce_axes)
+
+ return res1 + res2
+
+
class TotalVariation(nn.Module):
r"""Computes the Total Variation according to [1].
Shape:
- - Input: :math:`(N, C, H, W)` or :math:`(C, H, W)` where C = number of classes.
- - Output: :math:`(N,)` or :math:`()`
+ - Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`.
+ - Output: :math:`(N,)` or scalar.
Examples:
- >>> total_variation(torch.ones(3, 4, 4))
- tensor(0.)
>>> tv = TotalVariation()
>>> output = tv(torch.ones((2, 3, 4, 4), requires_grad=True))
>>> output.data
@@ -25,24 +57,5 @@ class TotalVariation(nn.Module):
def __init__(self) -> None:
super(TotalVariation, self).__init__()
- def forward( # type: ignore
- self, img) -> torch.Tensor:
+ def forward(self, img) -> torch.Tensor:
return total_variation(img)
-
-
-def total_variation(img: torch.Tensor) -> torch.Tensor:
- r"""Function that computes Total Variation.
-
- See :class:`~kornia.losses.TotalVariation` for details.
- """
- if not torch.is_tensor(img):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(img)}")
- img_shape = img.shape
- if len(img_shape) == 3 or len(img_shape) == 4:
- pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]
- pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]
- reduce_axes = (-3, -2, -1)
- else:
- raise ValueError("Expected input tensor to be of ndim 3 or 4, but got " + str(len(img_shape)))
-
- return pixel_dif1.abs().sum(dim=reduce_axes) + pixel_dif2.abs().sum(dim=reduce_axes)
diff --git a/test/test_losses.py b/test/test_losses.py
index fac180898..548c1fb76 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -338,14 +338,13 @@ class TestDepthSmoothnessLoss:
class TestSSIMLoss:
-
def test_ssim_equal_none(self, device, dtype):
# input data
img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
img2 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
- ssim1 = kornia.ssim(img1, img1, window_size=5, reduction="none")
- ssim2 = kornia.ssim(img2, img2, window_size=5, reduction="none")
+ ssim1 = kornia.losses.ssim_loss(img1, img1, window_size=5, reduction="none")
+ ssim2 = kornia.losses.ssim_loss(img2, img2, window_size=5, reduction="none")
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
assert_allclose(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)
@@ -358,12 +357,34 @@ class TestSSIMLoss:
# input data
img = torch.rand(batch_shape, device=device, dtype=dtype)
- ssim = kornia.losses.SSIM(window_size, reduction_type)
- loss = ssim(img, img)
+ loss = kornia.losses.ssim_loss(
+ img, img, window_size, reduction=reduction_type)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
assert_allclose(loss.item(), 0.0, rtol=tol_val, atol=tol_val)
+ def test_jit(self, device, dtype):
+ img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+
+ args = (img1, img2, 5, 1.0, 1e-6, 'mean')
+
+ op = kornia.losses.ssim_loss
+ op_script = torch.jit.script(op)
+
+ assert_allclose(op(*args), op_script(*args))
+
+ def test_module(self, device, dtype):
+ img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+
+ args = (img1, img2, 5, 1.0, 1e-12, 'mean')
+
+ op = kornia.losses.ssim_loss
+ op_module = kornia.losses.SSIMLoss(*args[2:])
+
+ assert_allclose(op(*args), op_module(*args[:2]))
+
def test_gradcheck(self, device, dtype):
# input data
window_size = 3
@@ -373,7 +394,7 @@ class TestSSIMLoss:
# evaluate function gradient
img1 = utils.tensor_to_gradcheck_var(img1) # to var
img2 = utils.tensor_to_gradcheck_var(img2, requires_grad=False) # to var
- assert gradcheck(kornia.ssim, (img1, img2, window_size), raise_exception=True)
+ assert gradcheck(kornia.losses.ssim_loss, (img1, img2, window_size), raise_exception=True)
class TestDivergenceLoss:
@@ -383,9 +404,10 @@ class TestDivergenceLoss:
(torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
])
- def test_js_div_loss_2d(self, device, input, target, expected):
- actual = kornia.losses.js_div_loss_2d(input.to(device), target.to(device)).item()
- assert_allclose(actual, expected)
+ def test_js_div_loss_2d(self, device, dtype, input, target, expected):
+ actual = kornia.losses.js_div_loss_2d(
+ input.to(device, dtype), target.to(device, dtype))
+ assert_allclose(actual.item(), expected)
@pytest.mark.parametrize('input,target,expected', [
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
@@ -393,9 +415,10 @@ class TestDivergenceLoss:
(torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
])
- def test_kl_div_loss_2d(self, device, input, target, expected):
- actual = kornia.losses.kl_div_loss_2d(input.to(device), target.to(device)).item()
- assert_allclose(actual, expected)
+ def test_kl_div_loss_2d(self, device, dtype, input, target, expected):
+ actual = kornia.losses.kl_div_loss_2d(
+ input.to(device, dtype), target.to(device, dtype))
+ assert_allclose(actual.item(), expected)
@pytest.mark.parametrize('input,target,expected', [
(torch.full((1, 1, 2, 4), 0.125),
@@ -411,9 +434,10 @@ class TestDivergenceLoss:
torch.full((1, 7, 2, 4), 0.125),
torch.full((1, 7), math.inf)),
])
- def test_kl_div_loss_2d_without_reduction(self, device, input, target, expected):
- actual = kornia.losses.kl_div_loss_2d(input.to(device), target.to(device), reduction='none')
- assert_allclose(actual, expected.to(device))
+ def test_kl_div_loss_2d_without_reduction(self, device, dtype, input, target, expected):
+ actual = kornia.losses.kl_div_loss_2d(
+ input.to(device, dtype), target.to(device, dtype), reduction='none')
+ assert_allclose(actual, expected.to(device, dtype))
@pytest.mark.parametrize('input,target,expected', [
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
@@ -421,9 +445,9 @@ class TestDivergenceLoss:
(torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
])
- def test_noncontiguous_kl(self, device, input, target, expected):
- input = input.to(device).view(input.shape[::-1]).T
- target = target.to(device).view(target.shape[::-1]).T
+ def test_noncontiguous_kl(self, device, dtype, input, target, expected):
+ input = input.to(device, dtype).view(input.shape[::-1]).T
+ target = target.to(device, dtype).view(target.shape[::-1]).T
actual = kornia.losses.kl_div_loss_2d(input, target).item()
assert_allclose(actual, expected)
@@ -433,15 +457,15 @@ class TestDivergenceLoss:
(torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
])
- def test_noncontiguous_js(self, device, input, target, expected):
- input = input.to(device).view(input.shape[::-1]).T
- target = target.to(device).view(target.shape[::-1]).T
+ def test_noncontiguous_js(self, device, dtype, input, target, expected):
+ input = input.to(device, dtype).view(input.shape[::-1]).T
+ target = target.to(device, dtype).view(target.shape[::-1]).T
actual = kornia.losses.js_div_loss_2d(input, target).item()
assert_allclose(actual, expected)
- def test_gradcheck_kl(self, device):
- input = torch.rand(1, 1, 10, 16).to(device)
- target = torch.rand(1, 1, 10, 16).to(device)
+ def test_gradcheck_kl(self, device, dtype):
+ input = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
+ target = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
# evaluate function gradient
input = utils.tensor_to_gradcheck_var(input) # to var
@@ -449,9 +473,9 @@ class TestDivergenceLoss:
assert gradcheck(kornia.losses.kl_div_loss_2d, (input, target),
raise_exception=True)
- def test_gradcheck_js(self, device):
- input = torch.rand(1, 1, 10, 16).to(device)
- target = torch.rand(1, 1, 10, 16).to(device)
+ def test_gradcheck_js(self, device, dtype):
+ input = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
+ target = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
# evaluate function gradient
input = utils.tensor_to_gradcheck_var(input) # to var
@@ -478,16 +502,16 @@ class TestDivergenceLoss:
class TestTotalVariation:
# Total variation of constant vectors is 0
- @pytest.mark.parametrize('input,expected', [
+ @pytest.mark.parametrize('input, expected', [
(torch.ones(3, 4, 5), torch.zeros(())),
(2 * torch.ones(2, 3, 4, 5), torch.zeros(2)),
])
- def test_tv_on_constant(self, device, input, expected):
- actual = kornia.losses.total_variation(input.to(device))
- assert_allclose(actual, expected.to(device))
+ def test_tv_on_constant(self, device, dtype, input, expected):
+ actual = kornia.losses.total_variation(input.to(device, dtype))
+ assert_allclose(actual, expected.to(device, dtype))
# Total variation for 3D tensors
- @pytest.mark.parametrize('input,expected', [
+ @pytest.mark.parametrize('input, expected', [
(torch.tensor([[[0.11747694, 0.5717714, 0.89223915, 0.2929412, 0.63556224],
[0.5371079, 0.13416398, 0.7782737, 0.21392655, 0.1757018],
[0.62360305, 0.8563448, 0.25304103, 0.68539226, 0.6956515],
@@ -505,11 +529,12 @@ class TestTotalVariation:
(torch.tensor([[[0.09094203, 0.32630223, 0.8066123],
[0.10921168, 0.09534764, 0.48588026]]]), torch.tensor(1.6900232)),
])
- def test_tv_on_3d(self, device, input, expected):
- assert_allclose(kornia.losses.total_variation(input.to(device)), expected.to(device))
+ def test_tv_on_3d(self, device, dtype, input, expected):
+ actual = kornia.losses.total_variation(input.to(device, dtype))
+ assert_allclose(actual, expected.to(device, dtype))
# Total variation for 4D tensors
- @pytest.mark.parametrize('input,expected', [
+ @pytest.mark.parametrize('input, expected', [
(torch.tensor([[[[0.8756, 0.0920],
[0.8034, 0.3107]],
[[0.3069, 0.2981],
@@ -529,77 +554,112 @@ class TestTotalVariation:
[[[0.5078, 0.5703, 0.9110],
[0.4765, 0.8401, 0.2754]]]]), torch.tensor([1.9565653, 2.5786452, 2.2681699])),
])
- def test_tv_on_4d(self, device, input, expected):
- assert_allclose(kornia.losses.total_variation(input.to(device)), expected.to(device))
+ def test_tv_on_4d(self, device, dtype, input, expected):
+ actual = kornia.losses.total_variation(input.to(device, dtype))
+ assert_allclose(actual, expected.to(device, dtype), rtol=1e-4, atol=1e-4)
# Expect ValueError to be raised when tensors of ndim != 3 or 4 are passed
@pytest.mark.parametrize('input', [
torch.rand(2, 3, 4, 5, 3),
torch.rand(3, 1),
])
- def test_tv_on_invalid_dims(self, device, input):
+ def test_tv_on_invalid_dims(self, device, dtype, input):
with pytest.raises(ValueError) as ex_info:
- kornia.losses.total_variation(input.to(device))
+ kornia.losses.total_variation(input.to(device, dtype))
# Expect TypeError to be raised when non-torch tensors are passed
@pytest.mark.parametrize('input', [
1,
[1, 2],
])
- def test_tv_on_invalid_types(self, input):
+ def test_tv_on_invalid_types(self, device, dtype, input):
with pytest.raises(TypeError) as ex_info:
kornia.losses.total_variation(input)
+ def test_jit(self, device, dtype):
+ image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
-class TestPSNRLoss:
- def test_smoke(self, device):
- input = torch.rand(2, 3, 3, 2).to(device)
- target = torch.rand(2, 3, 3, 2).to(device)
+ op = kornia.losses.total_variation
+ op_script = torch.jit.script(op)
- criterion = kornia.losses.PSNRLoss(1.0)
- loss = criterion(input, target)
+ assert_allclose(op(image), op_script(image))
+
+ def test_module(self, device, dtype):
+ image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+
+ op = kornia.losses.total_variation
+ op_module = kornia.losses.TotalVariation()
- assert loss.shape == tuple()
+ assert_allclose(op(image), op_module(image))
- def test_same_input(self, device):
- input = torch.rand(2, 3, 3, 2).to(device)
- target = input.clone()
+ def test_gradcheck(self, device, dtype):
+ image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ image = utils.tensor_to_gradcheck_var(image) # to var
+ assert gradcheck(kornia.losses.total_variation, (image,),
+ raise_exception=True)
+
+
+class TestPSNRLoss:
+ def test_smoke(self, device, dtype):
+ input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
criterion = kornia.losses.PSNRLoss(1.0)
loss = criterion(input, target)
- assert_allclose(loss, torch.tensor(float('inf')).to(device))
+ assert loss is not None
- def test_type(self):
+ def test_type(self, device, dtype):
# Expecting an exception
# since we pass integers instead of torch tensors
- criterion = kornia.losses.PSNRLoss(1.0)
+ criterion = kornia.losses.PSNRLoss(1.0).to(device, dtype)
with pytest.raises(Exception) as e:
criterion(1, 2)
- def test_shape(self):
+ def test_shape(self, device, dtype):
# Expecting an exception
# since we pass tensors of different shapes
- criterion = kornia.losses.PSNRLoss(1.0)
+ criterion = kornia.losses.PSNRLoss(1.0).to(device, dtype)
with pytest.raises(Exception) as e:
criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))
- def test_simple(self, device):
- assert_allclose(
- kornia.losses.psnr_loss(
- torch.ones(1).to(device),
- 1.2 * torch.ones(1).to(device),
- 2),
- torch.tensor(20.0).to(device))
+ def test_metric(self, device, dtype):
+ input = torch.ones(1, device=device, dtype=dtype)
+ expected = torch.tensor(20.0, device=device, dtype=dtype)
+ actual = kornia.losses.psnr(input, 1.2 * input, 2.)
+ assert_allclose(actual, expected)
+
+ def test_loss(self, device, dtype):
+ input = torch.ones(1, device=device, dtype=dtype)
+ expected = torch.tensor(-20.0, device=device, dtype=dtype)
+ actual = kornia.losses.psnr_loss(input, 1.2 * input, 2.)
+ assert_allclose(actual, expected)
- @pytest.mark.skip(reason="TODO: implement me")
- def test_jit(self):
- pass
+ def test_jit(self, device, dtype):
+ input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
- def test_gradcheck(self, device):
- input = torch.rand(2, 3, 3, 2).to(device)
- target = torch.rand(2, 3, 3, 2).to(device)
+ args = (input, target, 1.)
+
+ op = kornia.losses.psnr_loss
+ op_script = torch.jit.script(op)
+
+ assert_allclose(op(*args), op_script(*args))
+ def test_module(self, device, dtype):
+ input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+
+ args = (input, target, 1.)
+
+ op = kornia.losses.psnr_loss
+ op_module = kornia.losses.PSNRLoss(1.)
+
+ assert_allclose(op(*args), op_module(input, target))
+
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
target = utils.tensor_to_gradcheck_var(target) # to var
assert gradcheck(