Reconstruction#

Functions#

kornia.losses.ssim_loss(img1, img2, window_size, max_val=1.0, eps=1e-12, reduction='mean', padding='same')[source]#

Compute a loss based on the SSIM measurement.

The loss, or the Structural dissimilarity (DSSIM) is described as:

\[\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}\]
Convention:
  • See the Convention block of ssim() for the window, the border and max_val.

  • The per-pixel loss is the structural dissimilarity clamped to \([0, 1]\), clamp((1 - SSIM) / 2, 0, 1); Losses and metrics relates it to the 1 - SSIM loss. The clamp acts only where roundoff pushes the map outside \([-1, 1]\), as for images with a large constant offset.

  • The default reduction='mean' averages every element; 'none' keeps the shape of the SSIM map.

Parameters:
  • img1 (Tensor) – the first input image with shape \((B, C, H, W)\).

  • img2 (Tensor) – the second input image with shape \((B, C, H, W)\).

  • window_size (int) – the size of the gaussian kernel to smooth the images.

  • max_val (float, optional) – the dynamic range of the images. Default: 1.0

  • eps (float, optional) – 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"

  • padding (str, optional) – 'same' | 'valid'. Whether to only use the “valid” convolution area to compute SSIM to match the MATLAB implementation of original SSIM paper. Default: "same"

Return type:

Tensor

Returns:

The loss based on the ssim index.

Examples

>>> input1 = torch.rand(1, 4, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5)
>>> loss = ssim_loss(input1, input2, 5)
kornia.losses.ssim3d_loss(img1, img2, window_size, max_val=1.0, eps=1e-12, reduction='mean', padding='same')[source]#

Compute a loss based on the SSIM measurement.

The loss is the structural dissimilarity (DSSIM) of each voxel, clamped to \([0, 1]\):

\[\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}\]
Convention:
  • See the Convention block of ssim3d() for the window, the border and max_val.

  • The default reduction='mean' averages every element; 'none' keeps the shape of the SSIM map.

  • The per-voxel loss is clamp((1 - SSIM) / 2, 0, 1), as in ssim_loss().

Parameters:
  • img1 (Tensor) – the first input image with shape \((B, C, D, H, W)\).

  • img2 (Tensor) – the second input image with shape \((B, C, D, H, W)\).

  • window_size (int) – the size of the gaussian kernel to smooth the images.

  • max_val (float, optional) – the dynamic range of the images. Default: 1.0

  • eps (float, optional) – 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"

  • padding (str, optional) – 'same' | 'valid'. Whether to only use the “valid” convolution area to compute SSIM to match the MATLAB implementation of original SSIM paper. Default: "same"

Return type:

Tensor

Returns:

The loss based on the ssim index.

Examples

>>> input1 = torch.rand(1, 4, 5, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5, 5)
>>> loss = ssim3d_loss(input1, input2, 5)
kornia.losses.psnr_loss(image, target, max_val)[source]#

Compute the PSNR loss.

The loss is computed as follows:

\[\text{loss} = -\text{psnr(x, y)}\]
Convention:
  • See the Convention block of psnr(): the MSE is pooled over the batch, and identical inputs give -inf.

Parameters:
  • image (Tensor) – the input image with shape \((*)\).

  • target (Tensor) – the labels image with shape \((*)\).

  • max_val (float) – the data range of the images, \(\text{MAX}_I\).

Return type:

Tensor

Returns:

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)
kornia.losses.total_variation(img, reduction='sum')[source]#

Compute Total Variation according to [1].

Convention:
  • The anisotropic L1 variation, \(\sum |\partial_y I| + \sum |\partial_x I|\), over the last two axes only: the output keeps every leading axis, \((B, C)\) for an image batch, and the channels are not summed.

  • The default reduction='sum' adds the differences. 'mean' averages each term over its own count, \((H - 1) W\) vertical and \(H (W - 1)\) horizontal differences, and adds the two means; it is not the sum divided by \(H W\). An axis with no adjacent pixels contributes zero. There is no 'none'. Losses and metrics compares both with torchmetrics.

Parameters:
  • img (Tensor) – the input image with shape \((*, H, W)\).

  • reduction (str, optional) – Specifies the reduction to apply to the output: 'mean' | 'sum'. 'mean': each of the vertical and horizontal terms is averaged over its own number of differences, 'sum': the differences are summed. Default: "sum"

Return type:

Tensor

Returns:

a torch.Tensor with shape \((*,)\).

Examples

>>> total_variation(torch.ones(4, 4))
tensor(0.)
>>> total_variation(torch.ones(2, 5, 3, 4, 4)).shape
torch.Size([2, 5, 3])

Note

See a working example here. Total Variation is formulated with summation, however this is not resolution invariant; reduction='mean' averages instead. Narrow integer inputs are promoted before computing differences to avoid overflow.

Reference:

[1] https://en.wikipedia.org/wiki/Total_variation

kornia.losses.inverse_depth_smoothness_loss(idepth, image)[source]#

Criterion that computes image-aware inverse depth smoothness loss.

\[\text{loss} = \operatorname{mean}_{nij} \left| \partial_x d_{nij} \right| e^{-\frac{1}{C} \sum_c \left| \partial_x I_{ncij} \right|} + \operatorname{mean}_{nij} \left| \partial_y d_{nij} \right| e^{-\frac{1}{C} \sum_c \left| \partial_y I_{ncij} \right|}\]

with forward differences \(\partial_x\) and \(\partial_y\), each mean taken over its own differences.

Convention:
  • idepth is penalised and image only sets the weights: a constant inverse depth gives 0 for any image, and a constant image gives the plain mean of \(|\partial_x d|\) plus that of \(|\partial_y d|\).

  • The weights use the raw image values, so image is expected in a unit range: in [0, 255], a step of a few levels already drives its weight to about 0.

  • idepth is not normalised, so the loss is linear in its scale; Losses and metrics shows how to port a normalised smoothness term.

  • Only the rank, \((H, W)\), device and dtype are validated: the channel counts are not, a batch of one broadcasts against the other argument, and swapped arguments return a value.

Parameters:
  • idepth (Tensor) – tensor with the inverse depth with shape \((N, 1, H, W)\).

  • image (Tensor) – tensor with the input image with shape \((N, 3, H, W)\).

Return type:

Tensor

Returns:

a scalar with the computed loss.

Examples

>>> idepth = torch.rand(1, 1, 4, 5)
>>> image = torch.rand(1, 3, 4, 5)
>>> loss = inverse_depth_smoothness_loss(idepth, image)
kornia.losses.charbonnier_loss(img1, img2, reduction='none')[source]#

Criterion that computes the Charbonnier [2] (aka. L1-L2 [3]) loss.

According to [1], we compute the Charbonnier loss as follows:

\[\text{loss}(x, y) = \sqrt{(x - y)^{2} + 1} - 1\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] https://ieeexplore.ieee.org/document/413553 [3] https://hal.inria.fr/inria-00074015/document [4] https://arxiv.org/pdf/1712.05927.pdf

Note

This implementation follows the formulation by Barron [1]. Other works utilize a slightly different implementation (see [4]).

Convention:
  • The robust losses are the general loss of Barron [1] on the residual img1 - img2 at scale \(c = 1\): \(\alpha = 1\) here, \(\alpha = 0\) in cauchy_loss(), \(\alpha = -2\) in geman_mcclure_loss() and \(\alpha = -\infty\) in welsch_loss().

  • There is no scale argument: \(c = 1\) is in the units of the data, so the shape of the penalty depends on them; for a scale \(c\), pass img1 / c and img2 / c. Losses and metrics maps the losses onto Barron’s code.

  • The losses are symmetric in img1 and img2, which must have the same shape, without broadcasting, and the same device. The default reduction='none' returns the loss of every element, in the shape of the inputs.

  • This loss, cauchy_loss(), geman_mcclure_loss() and welsch_loss() evaluate float16 and bfloat16 inputs in float32, gradients included, and return the input dtype.

Parameters:
  • img1 (Tensor) – the predicted torch.Tensor with shape \((*)\).

  • img2 (Tensor) – the target torch.Tensor with the same shape as img1.

  • reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Return type:

Tensor

Returns:

the computed loss, with the shape of the inputs for reduction='none' and a scalar otherwise.

Example

>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = charbonnier_loss(img1, img2, reduction="sum")
>>> output.backward()
kornia.losses.welsch_loss(img1, img2, reduction='none')[source]#

Criterion that computes the Welsch [2] (aka. Leclerc [3]) loss.

According to [1], we compute the Welsch loss as follows:

\[\text{WL}(x, y) = 1 - exp(-\frac{1}{2} (x - y)^{2})\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] https://www.tandfonline.com/doi/abs/10.1080/03610917808812083 [3] https://link.springer.com/article/10.1007/BF00054839

Convention:

See the Convention block of charbonnier_loss(); this is Barron’s loss with \(\alpha = -\infty\).

Parameters:
  • img1 (Tensor) – the predicted torch.Tensor with shape \((*)\).

  • img2 (Tensor) – the target torch.Tensor with the same shape as img1.

  • reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Return type:

Tensor

Returns:

the computed loss, with the shape of the inputs for reduction='none' and a scalar otherwise.

Example

>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = welsch_loss(img1, img2, reduction="mean")
>>> output.backward()
kornia.losses.cauchy_loss(img1, img2, reduction='none')[source]#

Criterion that computes the Cauchy [2] (aka. Lorentzian) loss.

According to [1], we compute the Cauchy loss as follows:

\[\text{loss}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf

Convention:

See the Convention block of charbonnier_loss(); this is Barron’s loss with \(\alpha = 0\).

Parameters:
  • img1 (Tensor) – the predicted torch.Tensor with shape \((*)\).

  • img2 (Tensor) – the target torch.Tensor with the same shape as img1.

  • reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Return type:

Tensor

Returns:

the computed loss, with the shape of the inputs for reduction='none' and a scalar otherwise.

Example

>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = cauchy_loss(img1, img2, reduction="mean")
>>> output.backward()
kornia.losses.geman_mcclure_loss(img1, img2, reduction='none')[source]#

Criterion that computes the Geman-McClure loss [2].

According to [1], we compute the Geman-McClure loss as follows:

\[\text{loss}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985

Convention:

See the Convention block of charbonnier_loss(); this is Barron’s loss with \(\alpha = -2\).

Parameters:
  • img1 (Tensor) – the predicted torch.Tensor with shape \((*)\).

  • img2 (Tensor) – the target torch.Tensor with the same shape as img1.

  • reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Return type:

Tensor

Returns:

the computed loss, with the shape of the inputs for reduction='none' and a scalar otherwise.

Example

>>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 32)
>>> output = geman_mcclure_loss(img1, img2, reduction="mean")
>>> output.backward()

Modules#

class kornia.losses.SSIMLoss(window_size, max_val=1.0, eps=1e-12, reduction='mean', padding='same')[source]#

Create a criterion that computes a loss based on the SSIM measurement.

The loss, or the Structural dissimilarity (DSSIM) is described as:

\[\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}\]
Convention:

See the Convention block of ssim_loss().

Parameters:
  • window_size (int) – the size of the gaussian kernel to smooth the images.

  • max_val (float, optional) – the dynamic range of the images. Default: 1.0

  • eps (float, optional) – 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"

  • padding (str, optional) – 'same' | 'valid'. Whether to only use the “valid” convolution area to compute SSIM to match the MATLAB implementation of original SSIM paper. Default: "same"

Returns:

The loss based on the ssim index.

Examples

>>> input1 = torch.rand(1, 4, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5)
>>> criterion = SSIMLoss(5)
>>> loss = criterion(input1, input2)
class kornia.losses.SSIM3DLoss(window_size, max_val=1.0, eps=1e-12, reduction='mean', padding='same')[source]#

Create a criterion that computes a loss based on the SSIM measurement.

The loss is the structural dissimilarity (DSSIM) of each voxel, clamped to \([0, 1]\):

\[\text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}\]
Convention:
Parameters:
  • window_size (int) – the size of the gaussian kernel to smooth the images.

  • max_val (float, optional) – the dynamic range of the images. Default: 1.0

  • eps (float, optional) – 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"

  • padding (str, optional) – 'same' | 'valid'. Whether to only use the “valid” convolution area to compute SSIM to match the MATLAB implementation of original SSIM paper. Default: "same"

Returns:

The loss based on the ssim index.

Examples

>>> input1 = torch.rand(1, 4, 5, 5, 5)
>>> input2 = torch.rand(1, 4, 5, 5, 5)
>>> criterion = SSIM3DLoss(5)
>>> loss = criterion(input1, input2)
class kornia.losses.MS_SSIMLoss(sigmas=(0.5, 1.0, 2.0, 4.0, 8.0), data_range=1.0, K=(0.01, 0.03), alpha=0.025, compensation=200.0, reduction='mean')[source]#

Creates a criterion that computes MSSIM + L1 loss.

We compute the MS_SSIM + L1 loss of [1] as follows:

\[\text{loss}(x, y) = c \cdot \left(\alpha \cdot \mathcal{L_{MSSIM}}(x,y) + (1 - \alpha) \cdot G_{\sigma_M} * \mathcal{L_1}(x,y) / L\right)\]
Where:
  • \(\alpha\) is the weight parameter alpha, \(c\) is compensation and \(L\) is data_range.

  • \(x\) and \(y\) are the reconstructed and true reference images.

  • \(\mathcal{L_{MSSIM}}\) is the MS-SSIM loss.

  • \(G_{\sigma_M}\) is the Gaussian of the last entry \(\sigma_M\) of sigmas, the coarsest scale.

  • \(\mathcal{L_1}\) is the L1 loss.

Each channel is filtered at every scale. The MS-SSIM of a channel is its luminance at the coarsest scale times its contrast-structure at every scale, and \(\mathcal{L_{MSSIM}}\) is one minus the mean of the per-channel MS-SSIM: the formula of the reference implementation [2] of [1]. [2] evaluates it once per patch, at its centre; this loss evaluates it at every pixel. The L1 term is filtered at the coarsest scale and averaged over the channels.

Convention:
  • “Multi-scale” means one Gaussian per entry of sigmas, all at full resolution, as in [1], not the dyadic pyramid of Wang et al.; Losses and metrics compares it with pytorch-msssim and torchmetrics.

  • The last entry of sigmas is the coarsest scale, so the order matters: it sets the window, 2 * int(2 * sigmas[-1]) + 1 taps wide, the luminance term and the Gaussian of the L1 term.

  • The images are zero-padded by int(2 * sigmas[-1]) pixels, 16 at the default, where ssim() reflects, so the loss is biased in a band that wide along every border: the zeros attenuate the L1 term there but can raise the MS-SSIM term, so the band scores lower on the whole than reflect padding would at the default alpha and can score higher at a large alpha.

  • data_range is the max_val of ssim(): it sets \(C_1\) and \(C_2\) and divides the L1 term; pixel values are not rescaled.

  • The defaults follow [3]: alpha=0.025, as in [2], and compensation=200, which neither [1] nor [2] applies; [1] sets \(\alpha = 0.84\). The default reduction='mean' averages the \((B, H, W)\) map, whose channels are already averaged.

  • The two images must have the same \((C, H, W)\) shape. Their batch sizes must match, or one of them must be 1, and that image is then compared with every image of the other batch.

Reference:

[1]: https://research.nvidia.com/sites/default/files/pubs/2017-03_Loss-Functions-for/NN_ImgProc.pdf#page11 [2]: NVlabs/PL4NN (MSSSIML1) [3]: psyrocloud/MS-SSIM_L1_LOSS

Parameters:
  • sigmas (Sequence[float], optional) – the Gaussian sigma of each scale; the last entry is taken as the coarsest. Default: (0.5, 1.0, 2.0, 4.0, 8.0)

  • data_range (float, optional) – the range of the images. Default: 1.0

  • K (tuple[float, float], optional) – the constants \((k_1, k_2)\) of \(C_1 = (k_1 L)^2\) and \(C_2 = (k_2 L)^2\). Default: (0.01, 0.03)

  • alpha (float, optional) – the weight of the MS-SSIM term; the L1 term gets \(1 - \alpha\). Default: 0.025

  • compensation (float, optional) – specifies the scaling coefficient. Default: 200.0

  • 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"

Returns:

The computed loss.

Shape:
  • Input1: \((N, C, H, W)\).

  • Input2: \((N, C, H, W)\).

  • Output: \((N, H, W)\) or scalar if reduction is set to 'mean' or 'sum'.

Note

Integer and bool images count as the dtype of the Gaussian masks: float32, unless the module was moved to another floating dtype. The images are filtered in the promoted dtype of the two images and the masks, with float16 and bfloat16 raised to float32 and autocast disabled on CPU, CUDA and MPS. The loss is returned in the promoted dtype of the two images, so two integer images give a loss in the mask dtype. Pixel values are not rescaled: pass data_range=255.0 for 8-bit images, which gives the loss of the images divided by 255 at the default data_range=1.0.

Examples

>>> input1 = torch.rand(1, 3, 5, 5)
>>> input2 = torch.rand(1, 3, 5, 5)
>>> criterion = kornia.losses.MS_SSIMLoss()
>>> loss = criterion(input1, input2)
class kornia.losses.TotalVariation(*args, **kwargs)[source]#

Compute the Total Variation according to [1].

Convention:

See the Convention block of total_variation(). The module has no reduction and always sums.

Shape:
  • Input: \((*, H, W)\).

  • Output: \((*,)\).

Examples

>>> tv = TotalVariation()
>>> output = tv(torch.ones((2, 3, 4, 4), requires_grad=True))
>>> output.data
tensor([[0., 0., 0.],
        [0., 0., 0.]])
>>> output.sum().backward()  # grad can be implicitly created only for scalar outputs
Reference:

[1] https://en.wikipedia.org/wiki/Total_variation

class kornia.losses.PSNRLoss(max_val)[source]#

Create a criterion that calculates the PSNR loss.

The loss is computed as follows:

\[\text{loss} = -\text{psnr(x, y)}\]
Convention:

See the Convention block of psnr(): the MSE is pooled over the batch, and identical inputs give -inf.

Parameters:

max_val (float) – the data range of the images, \(\text{MAX}_I\).

Shape:
  • Image: arbitrary dimensional tensor \((*)\).

  • Target: arbitrary dimensional tensor \((*)\) same shape as image.

  • 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)
class kornia.losses.InverseDepthSmoothnessLoss(*args, **kwargs)[source]#

Criterion that computes image-aware inverse depth smoothness loss.

\[\text{loss} = \operatorname{mean}_{nij} \left| \partial_x d_{nij} \right| e^{-\frac{1}{C} \sum_c \left| \partial_x I_{ncij} \right|} + \operatorname{mean}_{nij} \left| \partial_y d_{nij} \right| e^{-\frac{1}{C} \sum_c \left| \partial_y I_{ncij} \right|}\]

with forward differences \(\partial_x\) and \(\partial_y\), each mean taken over its own differences.

Convention:

See the Convention block of inverse_depth_smoothness_loss().

Shape:
  • Inverse Depth: \((N, 1, H, W)\)

  • Image: \((N, 3, H, W)\)

  • Output: scalar

Examples

>>> idepth = torch.rand(1, 1, 4, 5)
>>> image = torch.rand(1, 3, 4, 5)
>>> smooth = InverseDepthSmoothnessLoss()
>>> loss = smooth(idepth, image)
class kornia.losses.CharbonnierLoss(reduction='none')[source]#

Criterion that computes the Charbonnier [2] (aka. L1-L2 [3]) loss.

According to [1], we compute the Charbonnier loss as follows:

\[\text{loss}(x, y) = \sqrt{(x - y)^{2} + 1} - 1\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] https://ieeexplore.ieee.org/document/413553 [3] https://hal.inria.fr/inria-00074015/document [4] https://arxiv.org/pdf/1712.05927.pdf

Note

This implementation follows the formulation by Barron [1]. Other works utilize a slightly different implementation (see [4]).

Convention:

See the Convention block of charbonnier_loss().

Parameters:

reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Shape:
  • img1: the predicted torch.Tensor with shape \((*)\).

  • img2: the target torch.Tensor with the same shape as img1.

Example

>>> criterion = CharbonnierLoss(reduction="mean")
>>> img1 = torch.randn(2, 3, 32, 2107, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 2107)
>>> output = criterion(img1, img2)
>>> output.backward()
class kornia.losses.WelschLoss(reduction='none')[source]#

Criterion that computes the Welsch [2] (aka. Leclerc [3]) loss.

According to [1], we compute the Welsch loss as follows:

\[\text{WL}(x, y) = 1 - exp(-\frac{1}{2} (x - y)^{2})\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] https://www.tandfonline.com/doi/abs/10.1080/03610917808812083 [3] https://link.springer.com/article/10.1007/BF00054839

Convention:

See the Convention block of welsch_loss().

Parameters:

reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Shape:
  • img1: the predicted torch.Tensor with shape \((*)\).

  • img2: the target torch.Tensor with the same shape as img1.

Example

>>> criterion = WelschLoss(reduction="mean")
>>> img1 = torch.randn(2, 3, 32, 1904, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 1904)
>>> output = criterion(img1, img2)
>>> output.backward()
class kornia.losses.CauchyLoss(reduction='none')[source]#

Criterion that computes the Cauchy [2] (aka. Lorentzian) loss.

According to [1], we compute the Cauchy loss as follows:

\[\text{loss}(x, y) = log(\frac{1}{2} (x - y)^{2} + 1)\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] https://files.is.tue.mpg.de/black/papers/cviu.63.1.1996.pdf

Convention:

See the Convention block of cauchy_loss().

Parameters:

reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Shape:
  • img1: the predicted torch.Tensor with shape \((*)\).

  • img2: the target torch.Tensor with the same shape as img1.

Example

>>> criterion = CauchyLoss(reduction="mean")
>>> img1 = torch.randn(2, 3, 32, 2107, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 2107)
>>> output = criterion(img1, img2)
>>> output.backward()
class kornia.losses.GemanMcclureLoss(reduction='none')[source]#

Criterion that computes the Geman-McClure loss [2].

According to [1], we compute the Geman-McClure loss as follows:

\[\text{loss}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}\]
Where:
  • \(x\) is the prediction.

  • \(y\) is the target to be regressed to.

Reference:

[1] https://arxiv.org/pdf/1701.03077.pdf [2] Bayesian image analysis: An application to single photon emission tomography, Geman and McClure, 1985

Convention:

See the Convention block of geman_mcclure_loss().

Parameters:

reduction (str, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. 'none': no reduction will be applied (default), '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"

Shape:
  • img1: the predicted torch.Tensor with shape \((*)\).

  • img2: the target torch.Tensor with the same shape as img1.

Example

>>> criterion = GemanMcclureLoss(reduction="mean")
>>> img1 = torch.randn(2, 3, 32, 2107, requires_grad=True)
>>> img2 = torch.randn(2, 3, 32, 2107)
>>> output = criterion(img1, img2)
>>> output.backward()