Reconstruction#
Compare an image with a reference using ssim_loss(), MS_SSIMLoss or psnr_loss(); volumes with
ssim3d_loss(). A robust loss compares any two tensors: charbonnier_loss() grows linearly for large
residuals, cauchy_loss() only logarithmically, and geman_mcclure_loss() and welsch_loss() saturate.
total_variation() penalises one image without a reference. inverse_depth_smoothness_loss() needs an
inverse-depth map and an image to weight its gradients, but no reference depth map.
Functions#
- kornia.losses.ssim_loss(img1, img2, window_size, max_val=1.0, eps=1e-12, reduction='mean', padding='same')[source]#
Compute the DSSIM loss between two images from their SSIM map.
loss = ssim_loss(img1, img2, window_size)maps the SSIM of two(B, C, H, W)images to a dissimilarity in \([0, 1]\).\[\text{loss}(x, y) = \operatorname{clamp}\left(\frac{1 - \text{SSIM}(x, y)}{2}, 0, 1\right)\]- Convention:
See the Convention block of
ssim()for the window, the border andmax_val.Losses and metrics relates this loss to the
1 - SSIMloss. The clamp acts only where roundoff pushes the map outside \([-1, 1]\), as for images with a large constant offset.
- Parameters:
img1 (
Tensor) – first image with shape(B, C, H, W).img2 (
Tensor) – second image with the same shape.window_size (
int) – size of the Gaussian window in pixels, a positive odd integer.max_val (
float, optional) – data range \(L\) of the images, a Python float or int. Default:1.0eps (
float, optional) – term added to the denominator of the SSIM. Default:1e-12reduction (
str, optional) –'mean'(default) averages the loss,'sum'adds it,'none'keeps the SSIM map’s shape. Default:"mean"padding (
str, optional) –'same'or'valid', as inssim(). Default:"same"
- Return type:
- Returns:
the loss, a scalar or, for
reduction='none', with the shape of the SSIM map.
See also
SSIMLoss: the module form.ssim(): the SSIM map itself, not the dissimilarity.ssim3d_loss(): the same loss for volumes.MS_SSIMLoss: several scales, plus an L1 term.
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 the DSSIM loss between two volumes from their SSIM map.
loss = ssim3d_loss(img1, img2, window_size)maps the SSIM of two(B, C, D, H, W)volumes to a dissimilarity in \([0, 1]\), asssim_loss()does for images.\[\text{loss}(x, y) = \operatorname{clamp}\left(\frac{1 - \text{SSIM}(x, y)}{2}, 0, 1\right)\]- Convention:
See the Convention block of
ssim3d()for the window, the border andmax_val, and that ofssim_loss()for the loss.
- Parameters:
img1 (
Tensor) – first volume with shape(B, C, D, H, W).img2 (
Tensor) – second volume with the same shape.window_size (
int) – size of the Gaussian window in voxels, a positive odd integer.max_val (
float, optional) – data range \(L\) of the volumes, a Python float or int. Default:1.0eps (
float, optional) – term added to the denominator of the SSIM. Default:1e-12reduction (
str, optional) –'mean'(default) averages the loss,'sum'adds it,'none'keeps the SSIM map’s shape. Default:"mean"padding (
str, optional) –'same'or'valid', as inssim3d(). Default:"same"
- Return type:
- Returns:
the loss, a scalar or, for
reduction='none', with the shape of the SSIM map.
See also
SSIM3DLoss: the module form.ssim3d(): the SSIM map itself, not the dissimilarity.ssim_loss(): the same loss for images.
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 negative PSNR of two images.
loss = psnr_loss(image, target, max_val)is-psnr(image, target, max_val), so minimising it raises the PSNR.- Convention:
See the Convention block of
psnr(): the MSE is pooled over the batch, and identical inputs give-inf.
- Parameters:
- Return type:
- Returns:
the loss, a scalar for a scalar range or with the shape of a tensor range.
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 the total variation of an image.
tv = total_variation(img)adds, for each(H, W)slice ofimg, the absolute differences between vertically and between horizontally adjacent pixels, and returns one value per leading index.\[\text{TV}(I) = \sum |\partial_y I| + \sum |\partial_x I|\]- Convention:
The channels are not summed: a
(B, C, H, W)batch gives(B, C).reduction='sum'is not normalised by the image size.'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.Narrow integer inputs are promoted before the differences, to avoid overflow.
- Parameters:
- Return type:
- Returns:
the total variation with shape
(*,).
Note
See a working example here.
See also
TotalVariation: the module form, which always sums.inverse_depth_smoothness_loss(): smoothness of a depth map, weighted by image edges.
Examples
>>> total_variation(torch.ones(4, 4)) tensor(0.) >>> total_variation(torch.ones(2, 5, 3, 4, 4)).shape torch.Size([2, 5, 3])
- Reference:
- kornia.losses.inverse_depth_smoothness_loss(idepth, image)[source]#
Compute the edge-aware smoothness loss of an inverse depth map.
loss = inverse_depth_smoothness_loss(idepth, image)penalises the horizontal and vertical gradients of an(N, 1, H, W)inverse depth. Each is weighted by the exponential of minus the gradient of the(N, 3, H, W)image, so a depth edge costs little where the image has an edge.\[\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:
idepthis penalised andimageonly 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
imageis expected in a unit range: in[0, 255], a step of a few levels already drives its weight to about 0.idepthis 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:
- Return type:
- Returns:
the loss, a scalar.
See also
InverseDepthSmoothnessLoss: the module form.total_variation(): the smoothness of one image, with no weights.
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]#
Compute the Charbonnier (L1-L2) loss between a prediction and a target.
loss = charbonnier_loss(img1, img2)penalises each residual \(x - y\) ofimg1(\(x\)) andimg2(\(y\)) quadratically near 0 and linearly beyond, without bound.\[\text{loss}(x, y) = \sqrt{(x - y)^{2} + 1} - 1\]- Reference:
[1] https://arxiv.org/pdf/1701.03077.pdf [2] Charbonnier: https://ieeexplore.ieee.org/document/413553 [3] L1-L2: https://hal.inria.fr/inria-00074015/document [4] https://arxiv.org/pdf/1712.05927.pdf
- Convention:
The robust losses are the general loss of Barron [1] on the residual
img1 - img2at scale \(c = 1\): \(\alpha = 1\) here, \(\alpha = 0\) incauchy_loss(), \(\alpha = -2\) ingeman_mcclure_loss()and \(\alpha = -\infty\) inwelsch_loss(). Other works use a slightly different Charbonnier form [4].There is no scale argument: the penalty stops being quadratic at residuals of about 1 in the units of the data. For a scale \(c\), pass
img1 / candimg2 / c. Losses and metrics maps the losses onto Barron’s code.The losses are symmetric in
img1andimg2, which must have the same shape, without broadcasting, and the same device.This loss,
cauchy_loss(),geman_mcclure_loss()andwelsch_loss()evaluate float16 and bfloat16 inputs in float32, gradients included, and return the input dtype.
- Parameters:
- Return type:
- Returns:
the loss with the shape of the inputs for
reduction='none', a scalar otherwise.
See also
CharbonnierLoss: the module form.cauchy_loss(): grows only logarithmically for large residuals.
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]#
Compute the Welsch (Leclerc) loss between a prediction and a target.
loss = welsch_loss(img1, img2)penalises each residual \(x - y\) ofimg1(\(x\)) andimg2(\(y\)) quadratically near 0 and saturates at 1, and its gradient vanishes for large residuals.\[\text{loss}(x, y) = 1 - \exp\left(-\frac{1}{2} (x - y)^{2}\right)\]- Reference:
[1] https://arxiv.org/pdf/1701.03077.pdf [2] Welsch: https://www.tandfonline.com/doi/abs/10.1080/03610917808812083 [3] Leclerc: 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:
- Return type:
- Returns:
the loss with the shape of the inputs for
reduction='none'orNone, a scalar otherwise.
See also
WelschLoss: the module form.geman_mcclure_loss(): saturates at 2, more slowly.
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]#
Compute the Cauchy (Lorentzian) loss between a prediction and a target.
loss = cauchy_loss(img1, img2)penalises each residual \(x - y\) ofimg1(\(x\)) andimg2(\(y\)) quadratically near 0 and only logarithmically beyond, without bound.\[\text{loss}(x, y) = \log\left(\frac{1}{2} (x - y)^{2} + 1\right)\]- Reference:
[1] https://arxiv.org/pdf/1701.03077.pdf [2] Cauchy: 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:
- Return type:
- Returns:
the loss with the shape of the inputs for
reduction='none', a scalar otherwise.
See also
CauchyLoss: the module form.charbonnier_loss(): grows linearly for large residuals.geman_mcclure_loss(): saturates at 2 for large residuals.
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]#
Compute the Geman-McClure loss between a prediction and a target.
loss = geman_mcclure_loss(img1, img2)penalises each residual \(x - y\) ofimg1(\(x\)) andimg2(\(y\)) quadratically near 0 and saturates at 2, and its gradient vanishes for large residuals.\[\text{loss}(x, y) = \frac{2 (x - y)^{2}}{(x - y)^{2} + 4}\]- Reference:
[1] https://arxiv.org/pdf/1701.03077.pdf [2] Geman-McClure: Geman and McClure, 1985, Bayesian image analysis: an application to single photon emission tomography.
- Convention:
See the Convention block of
charbonnier_loss(); this is Barron’s loss with \(\alpha = -2\).
- Parameters:
- Return type:
- Returns:
the loss with the shape of the inputs for
reduction='none', a scalar otherwise.
See also
GemanMcclureLoss: the module form.cauchy_loss(): grows logarithmically, without bound.welsch_loss(): saturates at 1, faster.
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]#
Compute the DSSIM loss between two images from their SSIM map (module form).
criterion = SSIMLoss(window_size, ...)stores its arguments, andloss = criterion(img1, img2)isssim_loss()on two(B, C, H, W)images.- Convention:
See the Convention block of
ssim_loss().
- Parameters:
window_size (
int) – size of the Gaussian window in pixels, a positive odd integer.max_val (
float, optional) – data range \(L\) of the images, a Python float or int. Default:1.0eps (
float, optional) – term added to the denominator of the SSIM. Default:1e-12reduction (
str, optional) –'mean'(default),'sum'or'none', as inssim_loss(). Default:"mean"padding (
str, optional) –'same'or'valid', as inssim(). Default:"same"
- Shape:
img1:
(B, C, H, W).img2:
(B, C, H, W).Output: a scalar or, for
reduction='none', the shape of the SSIM map.
See also
ssim_loss(): the one-call form.SSIM: the SSIM map itself, not the dissimilarity.SSIM3DLoss: the same loss for volumes.MS_SSIMLoss: several scales, plus an L1 term.
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]#
Compute the DSSIM loss between two volumes from their SSIM map (module form).
criterion = SSIM3DLoss(window_size, ...)stores its arguments, andloss = criterion(img1, img2)isssim3d_loss()on two(B, C, D, H, W)volumes.- Convention:
See the Convention block of
ssim3d_loss().
- Parameters:
window_size (
int) – size of the Gaussian window in voxels, a positive odd integer.max_val (
float, optional) – data range \(L\) of the volumes, a Python float or int. Default:1.0eps (
float, optional) – term added to the denominator of the SSIM. Default:1e-12reduction (
str, optional) –'mean'(default),'sum'or'none', as inssim3d_loss(). Default:"mean"padding (
str, optional) –'same'or'valid', as inssim3d(). Default:"same"
- Shape:
img1:
(B, C, D, H, W).img2:
(B, C, D, H, W).Output: a scalar or, for
reduction='none', the shape of the SSIM map.
See also
ssim3d_loss(): the one-call form.SSIM3D: the SSIM map itself, not the dissimilarity.SSIMLoss: the same loss for images.
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]#
Compute the multi-scale SSIM plus L1 loss between two images.
criterion = MS_SSIMLoss(sigmas, ...)builds one Gaussian mask per sigma.loss = criterion(img1, img2)mixes, at every pixel of two(B, C, H, W)images, one minus their multi-scale SSIM with a Gaussian-filtered L1 difference, as in [1].\[\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
alpha, \(c\) iscompensationand \(L\) isdata_range.\(x\) and \(y\) are the reconstructed and true reference images.
\(\mathcal{L_{MSSIM}}\) is one minus the mean over the channels of the MS-SSIM.
\(G_{\sigma_M}\) is the Gaussian of the last entry \(\sigma_M\) of
sigmas, the coarsest scale.\(\mathcal{L_1}\) is the L1 difference, averaged over the channels after the filter.
- 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- Convention:
The MS-SSIM of a channel is its luminance at the coarsest scale times its contrast-structure at every scale, 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.
“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
sigmasis the coarsest scale, so the order matters: it sets the window,2 * int(2 * sigmas[-1]) + 1taps 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, wheressim()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 defaultalphaand can score higher at a largealpha.data_rangeis themax_valofssim(): it sets \(C_1\) and \(C_2\) and divides the L1 term; pixel values are not rescaled.data_range=255.0on 8-bit images gives the loss of the same images divided by 255 at the defaultdata_range=1.0.The defaults follow [3]:
alpha=0.025, as in [2], andcompensation=200, which neither [1] nor [2] applies; [1] sets \(\alpha = 0.84\). The defaultreduction='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.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.
- Parameters:
sigmas (
Sequence[float], optional) – Gaussian sigma of each scale; the last entry is the coarsest. Default:(0.5, 1.0, 2.0, 4.0, 8.0)data_range (
float, optional) – range \(L\) of the images. Default:1.0K (
tuple[float,float], optional) – 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) – weight of the MS-SSIM term; the L1 term gets \(1 - \alpha\). Default:0.025compensation (
float, optional) – factor \(c\) that scales the whole loss. Default:200.0reduction (
str, optional) –'mean'(default) averages the loss,'sum'adds it,'none'keeps one value per pixel. Default:"mean"
- Shape:
Input1:
(B, C, H, W).Input2:
(B, C, H, W).Output:
(B, H, W)or scalar if reduction is set to'mean'or'sum'.
See also
SSIMLoss: one scale and no L1 term, as(1 - SSIM) / 2;ssim_loss()is its one-call form.
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 of an image (module form).
tv = TotalVariation()takes no arguments, andout = tv(img)istotal_variation()withreduction='sum'.- Convention:
See the Convention block of
total_variation().- Shape:
Input:
(*, H, W).Output:
(*,).
See also
total_variation(): the one-call form, withreduction='mean'too.
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
- class kornia.losses.PSNRLoss(max_val)[source]#
Compute the PSNR loss, the negative PSNR of two images (module form).
criterion = PSNRLoss(max_val)storesmax_val, andloss = criterion(image, target)ispsnr_loss().- Convention:
See the Convention block of
psnr_loss().
- Parameters:
max_val (
float|int|Tensor) – data range \(\text{MAX}_I\) of the images, as a float, integer or tensor.
- Shape:
Image:
(*).Target:
(*), the shape of the image.Output: a scalar for a scalar range, or the shape of a tensor range.
See also
psnr_loss(): the one-call form.psnr(): the PSNR itself, with the opposite sign.
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]#
Compute the edge-aware smoothness loss of an inverse depth map (module form).
smooth = InverseDepthSmoothnessLoss()takes no arguments, andloss = smooth(idepth, image)isinverse_depth_smoothness_loss().- Convention:
See the Convention block of
inverse_depth_smoothness_loss().- Shape:
Inverse Depth:
(N, 1, H, W)Image:
(N, 3, H, W)Output: scalar
See also
inverse_depth_smoothness_loss(): the one-call form.
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]#
Compute the Charbonnier (L1-L2) loss between a prediction and a target (module form).
criterion = CharbonnierLoss(reduction)storesreduction, andloss = criterion(img1, img2)ischarbonnier_loss().- Convention:
See the Convention block of
charbonnier_loss().
- Parameters:
reduction (
str, optional) –'none'(default),'mean'or'sum', as incharbonnier_loss(). Default:"none"
- Shape:
img1: prediction
(*).img2: target with the same shape as
img1.Output: the shape of the inputs for
reduction='none', a scalar otherwise.
See also
charbonnier_loss(): the one-call form.CauchyLoss: grows only logarithmically for large residuals.
Example
>>> criterion = CharbonnierLoss(reduction="mean") >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True) >>> img2 = torch.randn(2, 3, 32, 32) >>> output = criterion(img1, img2) >>> output.backward()
- class kornia.losses.WelschLoss(reduction='none')[source]#
Compute the Welsch (Leclerc) loss between a prediction and a target (module form).
criterion = WelschLoss(reduction)storesreduction, andloss = criterion(img1, img2)iswelsch_loss().- Convention:
See the Convention block of
welsch_loss().
- Parameters:
reduction (
Optional[str], optional) –'none'(default),None,'mean'or'sum', as inwelsch_loss(). Default:"none"
- Shape:
img1: prediction
(*).img2: target with the same shape as
img1.Output: the shape of the inputs for
reduction='none'orNone, a scalar otherwise.
See also
welsch_loss(): the one-call form.GemanMcclureLoss: saturates at 2, more slowly.
Example
>>> criterion = WelschLoss(reduction="mean") >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True) >>> img2 = torch.randn(2, 3, 32, 32) >>> output = criterion(img1, img2) >>> output.backward()
- class kornia.losses.CauchyLoss(reduction='none')[source]#
Compute the Cauchy (Lorentzian) loss between a prediction and a target (module form).
criterion = CauchyLoss(reduction)storesreduction, andloss = criterion(img1, img2)iscauchy_loss().- Convention:
See the Convention block of
cauchy_loss().
- Parameters:
reduction (
str, optional) –'none'(default),'mean'or'sum', as incauchy_loss(). Default:"none"
- Shape:
img1: prediction
(*).img2: target with the same shape as
img1.Output: the shape of the inputs for
reduction='none', a scalar otherwise.
See also
cauchy_loss(): the one-call form.CharbonnierLoss: grows linearly for large residuals.GemanMcclureLoss: saturates at 2 for large residuals.
Example
>>> criterion = CauchyLoss(reduction="mean") >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True) >>> img2 = torch.randn(2, 3, 32, 32) >>> output = criterion(img1, img2) >>> output.backward()
- class kornia.losses.GemanMcclureLoss(reduction='none')[source]#
Compute the Geman-McClure loss between a prediction and a target (module form).
criterion = GemanMcclureLoss(reduction)storesreduction, andloss = criterion(img1, img2)isgeman_mcclure_loss().- Convention:
See the Convention block of
geman_mcclure_loss().
- Parameters:
reduction (
str, optional) –'none'(default),'mean'or'sum', as ingeman_mcclure_loss(). Default:"none"
- Shape:
img1: prediction
(*).img2: target with the same shape as
img1.Output: the shape of the inputs for
reduction='none', a scalar otherwise.
See also
geman_mcclure_loss(): the one-call form.CauchyLoss: grows logarithmically, without bound.WelschLoss: saturates at 1, faster.
Example
>>> criterion = GemanMcclureLoss(reduction="mean") >>> img1 = torch.randn(2, 3, 32, 32, requires_grad=True) >>> img2 = torch.randn(2, 3, 32, 32) >>> output = criterion(img1, img2) >>> output.backward()