🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(losses): add detailed missing public docstrings (#3733)
Jeevang1-epic2d4a5346135b
diff --git a/kornia/losses/_utils.py b/kornia/losses/_utils.pyindex e35715a4d..c26a8bbbc 100644--- a/kornia/losses/_utils.py+++ b/kornia/losses/_utils.py@@ -25,6 +25,24 @@ import torchdef mask_ignore_pixels(target: torch.Tensor, ignore_index: Optional[int]) -> tuple[torch.Tensor, Optional[torch.Tensor]]:+ """Replace ignored target labels with a valid class and return their mask.++ Loss functions often need class indices to stay inside the valid class+ range before one-hot encoding or gathering. This helper keeps valid labels+ unchanged, maps ignored positions to class ``0`` temporarily, and returns a+ mask so callers can remove those positions from the final loss.++ Args:+ target: Target label tensor with arbitrary shape.+ ignore_index: Label value that should be ignored. If ``None``, no+ masking is applied.++ Returns:+ Tuple ``(target, target_mask)``. ``target`` is either the original+ tensor or a copy where ignored labels were replaced by zero.+ ``target_mask`` is ``None`` when no ignored pixels are present;+ otherwise it is a boolean tensor with ``True`` at valid positions.+ """if ignore_index is None:return target, Nonediff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.pyindex 7c55491c3..88df954d9 100644--- a/kornia/losses/cauchy.py+++ b/kornia/losses/cauchy.py@@ -129,4 +129,15 @@ class CauchyLoss(nn.Module):self.reduction = reductiondef forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ """Compute the Cauchy robust regression loss.++ Args:+ img1: Predicted tensor with arbitrary shape.+ img2: Target tensor with the same shape as ``img1``.++ Returns:+ Loss tensor reduced according to ``self.reduction``. The Cauchy+ penalty grows more slowly than squared error for large residuals,+ making it less sensitive to outliers.+ """return cauchy_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.pyindex ad3d8b897..ff9090b66 100644--- a/kornia/losses/charbonnier.py+++ b/kornia/losses/charbonnier.py@@ -142,4 +142,15 @@ class CharbonnierLoss(nn.Module):self.reduction = reductiondef forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ """Compute the Charbonnier robust regression loss.++ Args:+ img1: Predicted tensor with arbitrary shape.+ img2: Target tensor with the same shape as ``img1``.++ Returns:+ Loss tensor reduced according to ``self.reduction``. The+ Charbonnier penalty is a smooth approximation of absolute error and+ remains differentiable near zero residual.+ """return charbonnier_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.pyindex eef209754..671b5e62d 100644--- a/kornia/losses/depth_smooth.py+++ b/kornia/losses/depth_smooth.py@@ -119,4 +119,16 @@ class InverseDepthSmoothnessLoss(nn.Module):"""def forward(self, idepth: torch.Tensor, image: torch.Tensor) -> torch.Tensor:+ """Compute image-aware smoothness regularization for inverse depth.++ Args:+ idepth: Inverse-depth tensor with shape :math:`(B, 1, H, W)`.+ image: RGB image tensor with shape :math:`(B, 3, H, W)` used to+ reduce the smoothness penalty across visible image edges.++ Returns:+ Scalar tensor containing the edge-aware smoothness loss. Smoothness+ is encouraged in flat image regions and relaxed near strong image+ gradients.+ """return inverse_depth_smoothness_loss(idepth, image)diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex e0c2b3e15..87f40eca2 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -194,13 +194,17 @@ class DiceLoss(nn.Module):self.ignore_index = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:- """Compute Dice loss from logits and integer labels.+ """Compute Sørensen-Dice loss for segmentation logits and labels.Args:- pred: The input prediction logits with shape :math:`(N, C, H, W)`.- target: The ground truth labels with shape :math:`(N, H, W)`.+ pred: Logit tensor with shape :math:`(B, C, H, W)`, where+ :math:`B` is batch size, :math:`C` is number of classes,+ :math:`H` is height, and :math:`W` is width.+ target: Integer target labels with shape :math:`(B, H, W)`.Returns:- The computed Sørensen-Dice loss value.+ Scalar tensor containing ``1 - Dice`` after applying the configured+ averaging strategy, class weights, numerical epsilon, and optional+ ignored label handling."""return dice_loss(pred, target, self.average, self.eps, self.weight, self.ignore_index)diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 55ba6b773..7302046c2 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -192,6 +192,19 @@ class FocalLoss(nn.Module):self.ignore_index: Optional[int] = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute multi-class focal loss from class logits.++ Args:+ pred: Logit tensor with shape :math:`(B, C, *)`, where :math:`B`+ is batch size, :math:`C` is number of classes, and ``*`` is+ any number of spatial dimensions.+ target: Integer class-label tensor with shape :math:`(B, *)`.++ Returns:+ Focal-loss tensor reduced according to ``self.reduction``. The+ focusing factor ``self.gamma`` down-weights easy examples, while+ ``self.alpha`` and ``self.weight`` provide optional class weighting.+ """return focal_loss(pred, target, self.alpha, self.gamma, self.reduction, self.weight, self.ignore_index)@@ -368,6 +381,17 @@ class BinaryFocalLossWithLogits(nn.Module):self.ignore_index: Optional[int] = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute binary focal loss from logits.++ Args:+ pred: Logit tensor for binary predictions with arbitrary shape.+ target: Binary target tensor with the same shape as ``pred``.++ Returns:+ Binary focal-loss tensor reduced according to ``self.reduction``.+ Positive examples may be reweighted by ``self.pos_weight`` and+ examples matching ``self.ignore_index`` are ignored when configured.+ """return binary_focal_loss_with_logits(pred, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight, self.ignore_index)diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.pyindex 367335acb..7d5c14914 100644--- a/kornia/losses/geman_mcclure.py+++ b/kornia/losses/geman_mcclure.py@@ -131,4 +131,15 @@ class GemanMcclureLoss(nn.Module):self.reduction = reductiondef forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ """Compute the Geman-McClure robust regression loss.++ Args:+ img1: Predicted tensor with arbitrary shape.+ img2: Target tensor with the same shape as ``img1``.++ Returns:+ Loss tensor reduced according to ``self.reduction``. The robust+ penalty limits the contribution of large residuals compared with a+ plain squared-error loss.+ """return geman_mcclure_loss(img1=img1, img2=img2, reduction=self.reduction)diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.pyindex 8955fb0fc..6b88c80e4 100644--- a/kornia/losses/lovasz_hinge.py+++ b/kornia/losses/lovasz_hinge.py@@ -154,4 +154,14 @@ class LovaszHingeLoss(nn.Module):super().__init__()def forward(self, pred: Tensor, target: Tensor) -> Tensor:+ """Compute binary Lovasz hinge loss for segmentation logits.++ Args:+ pred: Binary logit tensor with shape :math:`(B, 1, H, W)`.+ target: Binary label tensor with shape :math:`(B, H, W)`.++ Returns:+ Scalar tensor containing the Lovasz hinge surrogate for the+ intersection-over-union objective.+ """return lovasz_hinge_loss(pred=pred, target=target)diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.pyindex 29427813f..c7e8d9de0 100644--- a/kornia/losses/lovasz_softmax.py+++ b/kornia/losses/lovasz_softmax.py@@ -183,4 +183,16 @@ class LovaszSoftmaxLoss(nn.Module):self.weight = weightdef forward(self, pred: Tensor, target: Tensor) -> Tensor:+ """Compute multi-class Lovasz-Softmax loss.++ Args:+ pred: Class logit tensor with shape :math:`(B, C, H, W)`, where+ :math:`C` is the number of classes.+ target: Integer class-label tensor with shape :math:`(B, H, W)`.++ Returns:+ Scalar tensor containing the Lovasz-Softmax surrogate for the+ mean intersection-over-union objective, using ``self.weight`` when+ class weights are configured.+ """return lovasz_softmax_loss(pred=pred, target=target, weight=self.weight)diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.pyindex 0be788d59..e2fdc958a 100644--- a/kornia/losses/mutual_information.py+++ b/kornia/losses/mutual_information.py@@ -83,6 +83,13 @@ def truncated_gaussian_kernel(x: torch.Tensor, window_radius: float = 1.0) -> toclass MIKernel(Enum):+ """Available kernels for mutual-information density estimation.++ The enum values are callable kernels used to softly assign signal samples+ to histogram bins. They are used by the entropy-based mutual-information+ losses to build differentiable joint histograms.+ """+xu = member(xu_kernel)rectangular = member(rectangular_kernel)truncated_gaussian = member(truncated_gaussian_kernel)@@ -194,6 +201,23 @@ class EntropyBasedLossBase(torch.nn.Module):# TODO: optimize method below, maybe with ihdex coordinates conversiondef trace_in_ref_mask(self, other_signal, other_mask):+ """Align another masked signal with the reference mask positions.++ The reference signal can be stored with a mask, while the compared+ signal may use a different mask over the same flattened coordinate+ space. This helper restores the compared signal to the original flat+ shape when needed, then selects the elements that correspond to the+ stored reference mask.++ Args:+ other_signal: Flattened signal values after applying ``other_mask``.+ other_mask: Boolean mask describing which flattened positions are+ present in ``other_signal``.++ Returns:+ Signal values traced onto the reference mask used by this loss+ instance.+ """if other_mask.all():return other_signal[..., self.mask]@@ -274,6 +298,14 @@ class EntropyBasedLossBase(torch.nn.Module):class MILossFromRef(EntropyBasedLossBase):+ """Mutual-information loss against a stored reference signal.++ The reference signal is normalized and stored during initialization by the+ base class. Calling the module with another signal estimates both marginal+ entropies and the joint entropy, then returns negative mutual information+ so it can be minimized as a loss.+ """+def forward(self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None) -> torch.Tensor:"""Compute differentiable mutual information for self.signal and other_signal.@@ -296,6 +328,13 @@ class MILossFromRef(EntropyBasedLossBase):class NMILossFromRef(EntropyBasedLossBase):+ """Normalized mutual-information loss against a stored reference signal.++ This variant divides the sum of marginal entropies by joint entropy before+ negating the value. It is commonly useful when the amount of overlap or+ intensity distribution scale differs between compared signals.+ """+def forward(self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None) -> torch.Tensor:"""Compute differentiable normalized mutual information for self.signal and other_signal.@@ -355,6 +394,16 @@ class MILossFromRef2D(MILossFromRef):@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:+ """Flatten the spatial dimensions of a 2D signal batch.++ Args:+ tensor: Signal tensor with shape :math:`(*, H, W)`, where ``*`` is+ any leading batch shape.++ Returns:+ Tensor with shape :math:`(*, H * W)` suitable for histogram-based+ mutual-information computation.+ """return tensor.reshape(tensor.shape[:-2] + (-1,))def forward(@@ -417,6 +466,16 @@ class MILossFromRef3D(MILossFromRef):@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:+ """Flatten the spatial dimensions of a 3D signal batch.++ Args:+ tensor: Signal tensor with shape :math:`(*, D, H, W)`, where+ :math:`D` is depth, :math:`H` is height, and :math:`W` is+ width.++ Returns:+ Tensor with shape :math:`(*, D * H * W)` for entropy estimation.+ """return tensor.reshape(tensor.shape[:-3] + (-1,))def forward(@@ -479,6 +538,15 @@ class NMILossFromRef2D(NMILossFromRef):@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:+ """Flatten the spatial dimensions of a 2D signal batch.++ Args:+ tensor: Signal tensor with shape :math:`(*, H, W)`.++ Returns:+ Tensor with shape :math:`(*, H * W)` used by the normalized+ mutual-information base implementation.+ """return tensor.reshape(tensor.shape[:-2] + (-1,))def forward(@@ -541,6 +609,15 @@ class NMILossFromRef3D(NMILossFromRef):@staticmethoddef arrange_shape(tensor: torch.Tensor) -> torch.Tensor:+ """Flatten the spatial dimensions of a 3D signal batch.++ Args:+ tensor: Signal tensor with shape :math:`(*, D, H, W)`.++ Returns:+ Tensor with shape :math:`(*, D * H * W)` used by the normalized+ mutual-information base implementation.+ """return tensor.reshape(tensor.shape[:-3] + (-1,))def forward(diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.pyindex 9a312e1ae..91c4b7cfd 100644--- a/kornia/losses/psnr.py+++ b/kornia/losses/psnr.py@@ -83,4 +83,15 @@ class PSNRLoss(nn.Module):self.max_val: float = max_valdef forward(self, image: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute the negative PSNR loss between two tensors.++ Args:+ image: Predicted image or signal tensor with arbitrary shape.+ target: Reference tensor with the same shape as ``image``.++ Returns:+ Scalar tensor containing the PSNR-based loss computed with+ ``self.max_val``. Lower values correspond to higher peak signal to+ noise ratio.+ """return psnr_loss(image, target, self.max_val)diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.pyindex faae20734..7cc56aff5 100644--- a/kornia/losses/ssim.py+++ b/kornia/losses/ssim.py@@ -126,4 +126,17 @@ class SSIMLoss(nn.Module):self.padding: str = paddingdef forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ """Compute SSIM loss between two 2D image tensors.++ Args:+ img1: First image batch with shape :math:`(B, C, H, W)`, where+ :math:`B` is batch size, :math:`C` is channel count,+ :math:`H` is height, and :math:`W` is width.+ img2: Second image batch with the same shape as ``img1``.++ Returns:+ SSIM loss tensor reduced according to ``self.reduction``. The loss+ is derived from structural similarity, so lower values indicate+ more similar local luminance, contrast, and structure.+ """return ssim_loss(img1, img2, self.window_size, self.max_val, self.eps, self.reduction, self.padding)diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.pyindex e0bc74292..90db71e26 100644--- a/kornia/losses/ssim3d.py+++ b/kornia/losses/ssim3d.py@@ -126,4 +126,18 @@ class SSIM3DLoss(nn.Module):self.padding: str = paddingdef forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ """Compute SSIM loss between two 3D image or volume tensors.++ Args:+ img1: First volume batch with shape :math:`(B, C, D, H, W)`, where+ :math:`B` is batch size, :math:`C` is channel count,+ :math:`D` is depth, :math:`H` is height, and :math:`W` is+ width.+ img2: Second volume batch with the same shape as ``img1``.++ Returns:+ SSIM3D loss tensor reduced according to ``self.reduction``. Lower+ values indicate stronger local structural agreement between the two+ volumes.+ """return ssim3d_loss(img1, img2, self.window_size, self.max_val, self.eps, self.reduction, self.padding)diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex 45b3f0e9a..babec8768 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -101,4 +101,16 @@ class TotalVariation(nn.Module):"""def forward(self, img: torch.Tensor) -> torch.Tensor:+ """Compute total variation for an image or image batch.++ Args:+ img: Tensor with shape :math:`(*, H, W)`, where ``*`` represents+ optional leading dimensions such as batch and channels,+ :math:`H` is height, and :math:`W` is width.++ Returns:+ Tensor containing the sum of absolute horizontal and vertical+ finite differences for each leading element. Lower values indicate+ spatially smoother images.+ """return total_variation(img)diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.pyindex 7d5cd1450..0e8a7f863 100644--- a/kornia/losses/tversky.py+++ b/kornia/losses/tversky.py@@ -167,4 +167,19 @@ class TverskyLoss(nn.Module):self.ignore_index: Optional[int] = ignore_indexdef forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ """Compute the Tversky segmentation loss for class logits and labels.++ Args:+ pred: Logit tensor with shape :math:`(B, C, H, W)`, where+ :math:`B` is batch size, :math:`C` is number of classes,+ :math:`H` is height, and :math:`W` is width.+ target: Integer class-label tensor with shape :math:`(B, H, W)`.+ Labels matching ``self.ignore_index`` are excluded from the+ loss when an ignore index is configured.++ Returns:+ Scalar tensor containing the Tversky loss. ``self.alpha`` controls+ the false-positive penalty and ``self.beta`` controls the+ false-negative penalty.+ """return tversky_loss(pred, target, self.alpha, self.beta, self.eps, self.ignore_index)diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.pyindex 57c847fd7..d727d0946 100644--- a/kornia/losses/welsch.py+++ b/kornia/losses/welsch.py@@ -130,4 +130,15 @@ class WelschLoss(nn.Module):self.reduction = reductiondef forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ """Compute the Welsch robust regression loss.++ Args:+ img1: Predicted tensor with arbitrary shape.+ img2: Target tensor with the same shape as ``img1``.++ Returns:+ Loss tensor reduced according to ``self.reduction``. The Welsch+ penalty saturates for large residuals, reducing the influence of+ strong outliers.+ """return welsch_loss(img1=img1, img2=img2, reduction=self.reduction)