Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Rename variables shadowing build-in input function (#2628)

Alina Bondaretsef0f61812e59
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index b11237e17..df8df2535 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -12,7 +12,7 @@ from kornia.utils.one_hot import one_hot
# https://github.com/Lightning-AI/metrics/blob/v0.11.3/src/torchmetrics/functional/classification/dice.py#L66-L207
-def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: float = 1e-8) -> Tensor:
+def dice_loss(pred: Tensor, target: Tensor, average: str = "micro", eps: float = 1e-8) -> Tensor:
r"""Criterion that computes Sørensen-Dice Coefficient loss.
According to [1], we compute the Sørensen-Dice Coefficient as follows:
@@ -35,7 +35,7 @@ def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: float
[1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
Args:
- input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
+ pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
labels: labels tensor with shape :math:`(N, H, W)` where each value
is :math:`0 ≤ targets[i] ≤ C-1`.
average:
@@ -49,30 +49,30 @@ def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: float
Example:
>>> N = 5 # num_classes
- >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
- >>> output = dice_loss(input, target)
+ >>> output = dice_loss(pred, target)
>>> output.backward()
"""
- KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_IS_TENSOR(pred)
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxNxHxW. Got: {input.shape}")
+ if not len(pred.shape) == 4:
+ raise ValueError(f"Invalid pred shape, we expect BxNxHxW. Got: {pred.shape}")
- if not input.shape[-2:] == target.shape[-2:]:
- raise ValueError(f"input and target shapes must be the same. Got: {input.shape} and {target.shape}")
+ if not pred.shape[-2:] == target.shape[-2:]:
+ raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")
- if not input.device == target.device:
- raise ValueError(f"input and target must be in the same device. Got: {input.device} and {target.device}")
+ if not pred.device == target.device:
+ raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")
possible_average = {"micro", "macro"}
KORNIA_CHECK(average in possible_average, f"The `average` has to be one of {possible_average}. Got: {average}")
# compute softmax over the classes axis
- input_soft: Tensor = input.softmax(dim=1)
+ pred_soft: Tensor = pred.softmax(dim=1)
# create the labels one hot tensor
- target_one_hot: Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
+ target_one_hot: Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# set dimensions for the appropriate averaging
dims: tuple[int, ...] = (2, 3)
@@ -80,8 +80,8 @@ def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: float
dims = (1, *dims)
# compute the actual dice score
- intersection = torch.sum(input_soft * target_one_hot, dims)
- cardinality = torch.sum(input_soft + target_one_hot, dims)
+ intersection = torch.sum(pred_soft * target_one_hot, dims)
+ cardinality = torch.sum(pred_soft + target_one_hot, dims)
dice_score = 2.0 * intersection / (cardinality + eps)
dice_loss = -dice_score + 1.0
@@ -122,16 +122,16 @@ class DiceLoss(nn.Module):
eps: Scalar to enforce numerical stabiliy.
Shape:
- - Input: :math:`(N, C, H, W)` where C = number of classes.
+ - Pred: :math:`(N, C, H, W)` where C = number of classes.
- Target: :math:`(N, H, W)` where each value is
:math:`0 ≤ targets[i] ≤ C-1`.
Example:
>>> N = 5 # num_classes
>>> criterion = DiceLoss()
- >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
- >>> output = criterion(input, target)
+ >>> output = criterion(pred, target)
>>> output.backward()
"""
@@ -140,5 +140,5 @@ class DiceLoss(nn.Module):
self.average = average
self.eps = eps
- def forward(self, input: Tensor, target: Tensor) -> Tensor:
- return dice_loss(input, target, self.average, self.eps)
+ def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ return dice_loss(pred, target, self.average, self.eps)
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index a417728b6..771025c46 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -33,11 +33,11 @@ def _reduce_loss(losses: Tensor, reduction: str) -> Tensor:
return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)
-def js_div_loss_2d(input: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
+def js_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
r"""Calculate the Jensen-Shannon divergence loss between heatmaps.
Args:
- input: the input tensor with shape :math:`(B, N, H, W)`.
+ pred: the input tensor with shape :math:`(B, N, H, W)`.
target: the target tensor with shape :math:`(B, N, H, W)`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
@@ -46,19 +46,19 @@ def js_div_loss_2d(input: Tensor, target: Tensor, reduction: str = 'mean') -> Te
summed.
Examples:
- >>> input = torch.full((1, 1, 2, 4), 0.125)
- >>> loss = js_div_loss_2d(input, input)
+ >>> pred = torch.full((1, 1, 2, 4), 0.125)
+ >>> loss = js_div_loss_2d(pred, pred)
>>> loss.item()
0.0
"""
- return _reduce_loss(_js_div_2d(target, input), reduction)
+ return _reduce_loss(_js_div_2d(target, pred), reduction)
-def kl_div_loss_2d(input: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
+def kl_div_loss_2d(pred: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
r"""Calculate the Kullback-Leibler divergence loss between heatmaps.
Args:
- input: the input tensor with shape :math:`(B, N, H, W)`.
+ pred: the input tensor with shape :math:`(B, N, H, W)`.
target: the target tensor with shape :math:`(B, N, H, W)`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
@@ -67,9 +67,9 @@ def kl_div_loss_2d(input: Tensor, target: Tensor, reduction: str = 'mean') -> Te
summed.
Examples:
- >>> input = torch.full((1, 1, 2, 4), 0.125)
- >>> loss = kl_div_loss_2d(input, input)
+ >>> pred = torch.full((1, 1, 2, 4), 0.125)
+ >>> loss = kl_div_loss_2d(pred, pred)
>>> loss.item()
0.0
"""
- return _reduce_loss(_kl_div_2d(target, input), reduction)
+ return _reduce_loss(_kl_div_2d(target, pred), reduction)
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index e374a77ad..707877caf 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -14,7 +14,7 @@ from kornia.utils.one_hot import one_hot
def focal_loss(
- input: Tensor,
+ pred: Tensor,
target: Tensor,
alpha: Optional[float],
gamma: float = 2.0,
@@ -33,7 +33,7 @@ def focal_loss(
- :math:`p_t` is the model's estimated probability for each class.
Args:
- input: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
+ pred: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
target: labels tensor with shape :math:`(N, *)` where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
alpha: Weighting factor :math:`\alpha \in [0, 1]`.
@@ -50,35 +50,35 @@ def focal_loss(
Example:
>>> C = 5 # num_classes
- >>> input = torch.randn(1, C, 3, 5, requires_grad=True)
+ >>> pred = torch.randn(1, C, 3, 5, requires_grad=True)
>>> target = torch.randint(C, (1, 3, 5))
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
- >>> output = focal_loss(input, target, **kwargs)
+ >>> output = focal_loss(pred, target, **kwargs)
>>> output.backward()
"""
- KORNIA_CHECK_SHAPE(input, ["B", "C", "*"])
- out_size = (input.shape[0],) + input.shape[2:]
+ KORNIA_CHECK_SHAPE(pred, ["B", "C", "*"])
+ out_size = (pred.shape[0],) + pred.shape[2:]
KORNIA_CHECK(
- (input.shape[0] == target.shape[0] and target.shape[1:] == input.shape[2:]),
+ (pred.shape[0] == target.shape[0] and target.shape[1:] == pred.shape[2:]),
f'Expected target size {out_size}, got {target.shape}',
)
KORNIA_CHECK(
- input.device == target.device,
- f"input and target must be in the same device. Got: {input.device} and {target.device}",
+ pred.device == target.device,
+ f"pred and target must be in the same device. Got: {pred.device} and {target.device}",
)
# create the labels one hot tensor
- target_one_hot: Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
+ target_one_hot: Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# compute softmax over the classes axis
- log_input_soft: Tensor = input.log_softmax(1)
+ log_pred_soft: Tensor = pred.log_softmax(1)
# compute the actual focal loss
- loss_tmp: Tensor = -torch.pow(1.0 - log_input_soft.exp(), gamma) * log_input_soft * target_one_hot
+ loss_tmp: Tensor = -torch.pow(1.0 - log_pred_soft.exp(), gamma) * log_pred_soft * target_one_hot
- num_of_classes = input.shape[1]
- boradcast_dims = [-1] + [1] * len(input.shape[2:])
+ num_of_classes = pred.shape[1]
+ boradcast_dims = [-1] + [1] * len(pred.shape[2:])
if alpha is not None:
alpha_fac = tensor([1 - alpha] + [alpha] * (num_of_classes - 1), dtype=loss_tmp.dtype, device=loss_tmp.device)
alpha_fac = alpha_fac.view(boradcast_dims)
@@ -91,8 +91,8 @@ def focal_loss(
f'weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}',
)
KORNIA_CHECK(
- weight.device == input.device,
- f"weight and input must be in the same device. Got: {weight.device} and {input.device}",
+ weight.device == pred.device,
+ f"weight and pred must be in the same device. Got: {weight.device} and {pred.device}",
)
weight = weight.view(boradcast_dims)
@@ -132,17 +132,17 @@ class FocalLoss(nn.Module):
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
Shape:
- - Input: :math:`(N, C, *)` where C = number of classes.
+ - Pred: :math:`(N, C, *)` where C = number of classes.
- Target: :math:`(N, *)` where each value is an integer
representing correct classification :math:`target[i] \in [0, C)`.
Example:
>>> C = 5 # num_classes
- >>> input = torch.randn(1, C, 3, 5, requires_grad=True)
+ >>> pred = torch.randn(1, C, 3, 5, requires_grad=True)
>>> target = torch.randint(C, (1, 3, 5))
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
>>> criterion = FocalLoss(**kwargs)
- >>> output = criterion(input, target)
+ >>> output = criterion(pred, target)
>>> output.backward()
"""
@@ -155,12 +155,12 @@ class FocalLoss(nn.Module):
self.reduction: str = reduction
self.weight: Optional[Tensor] = weight
- def forward(self, input: Tensor, target: Tensor) -> Tensor:
- return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.weight)
+ def forward(self, pred: Tensor, target: Tensor) -> Tensor:
+ return focal_loss(pred, target, self.alpha, self.gamma, self.reduction, self.weight)
def binary_focal_loss_with_logits(
- input: Tensor,
+ pred: Tensor,
target: Tensor,
alpha: Optional[float] = 0.25,
gamma: float = 2.0,
@@ -180,8 +180,8 @@ def binary_focal_loss_with_logits(
- :math:`p_t` is the model's estimated probability for each class.
Args:
- input: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
- target: labels tensor with the same shape as input :math:`(N, C, *)`
+ pred: logits tensor with shape :math:`(N, C, *)` where C = number of classes.
+ target: labels tensor with the same shape as pred :math:`(N, C, *)`
where each value is between 0 and 1.
alpha: Weighting factor :math:`\alpha \in [0, 1]`.
gamma: Focusing parameter :math:`\gamma >= 0`.
@@ -199,22 +199,22 @@ def binary_focal_loss_with_logits(
Examples:
>>> C = 3 # num_classes
- >>> input = torch.randn(1, C, 5, requires_grad=True)
+ >>> pred = torch.randn(1, C, 5, requires_grad=True)
>>> target = torch.randint(2, (1, C, 5))
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
- >>> output = binary_focal_loss_with_logits(input, target, **kwargs)
+ >>> output = binary_focal_loss_with_logits(pred, target, **kwargs)
>>> output.backward()
"""
- KORNIA_CHECK_SHAPE(input, ["B", "C", "*"])
- KORNIA_CHECK(input.shape == target.shape, f'Expected target size {input.shape}, got {target.shape}')
+ KORNIA_CHECK_SHAPE(pred, ["B", "C", "*"])
+ KORNIA_CHECK(pred.shape == target.shape, f'Expected target size {pred.shape}, got {target.shape}')
KORNIA_CHECK(
- input.device == target.device,
- f"input and target must be in the same device. Got: {input.device} and {target.device}",
+ pred.device == target.device,
+ f"pred and target must be in the same device. Got: {pred.device} and {target.device}",
)
- log_probs_pos: Tensor = nn.functional.logsigmoid(input)
- log_probs_neg: Tensor = nn.functional.logsigmoid(-input)
+ log_probs_pos: Tensor = nn.functional.logsigmoid(pred)
+ log_probs_neg: Tensor = nn.functional.logsigmoid(-pred)
pos_term: Tensor = -log_probs_neg.exp().pow(gamma) * target * log_probs_pos
neg_term: Tensor = -log_probs_pos.exp().pow(gamma) * (1.0 - target) * log_probs_neg
@@ -222,8 +222,8 @@ def binary_focal_loss_with_logits(
pos_term = alpha * pos_term
neg_term = (1.0 - alpha) * neg_term
- num_of_classes = input.shape[1]
- boradcast_dims = [-1] + [1] * len(input.shape[2:])
+ num_of_classes = pred.shape[1]
+ boradcast_dims = [-1] + [1] * len(pred.shape[2:])
if pos_weight is not None:
KORNIA_CHECK_IS_TENSOR(pos_weight, "pos_weight must be Tensor or None.")
KORNIA_CHECK(
@@ -231,8 +231,8 @@ def binary_focal_loss_with_logits(
f'pos_weight shape must be (num_of_classes,): ({num_of_classes},), got {pos_weight.shape}',
)
KORNIA_CHECK(
- pos_weight.device == input.device,
- f"pos_weight and input must be in the same device. Got: {pos_weight.device} and {input.device}",
+ pos_weight.device == pred.device,
+ f"pos_weight and pred must be in the same device. Got: {pos_weight.device} and {pred.device}",
)
pos_weight = pos_weight.view(boradcast_dims)
@@ -246,8 +246,8 @@ def binary_focal_loss_with_logits(
f'weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}',
)
KORNIA_CHECK(
- weight.device == input.device,
- f"weight and input must be in the same device. Got: {weight.device} and {input.device}",
+ weight.device == pred.device,
+ f"weight and pred must be in the same device. Got: {weight.device} and {pred.device}",
)
weight = weight.view(boradcast_dims)
@@ -289,17 +289,17 @@ class BinaryFocalLossWithLogits(nn.Module):
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
Shape:
- - Input: :math:`(N, C, *)` where C = number of classes.
- - Target: the same shape as Input :math:`(N, C, *)`
+ - Pred: :math:`(N, C, *)` where C = number of classes.
+ - Target: the same shape as Pred :math:`(N, C, *)`
where each value is between 0 and 1.
Examples:
>>> C = 3 # num_classes
- >>> input = torch.randn(1, C, 5, requires_grad=True)
+ >>> pred = torch.randn(1, C, 5, requires_grad=True)
>>> target = torch.randint(2, (1, C, 5))
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> criterion = BinaryFocalLossWithLogits(**kwargs)
- >>> output = criterion(input, target)
+ >>> output = criterion(pred, target)
>>> output.backward()
"""
@@ -318,7 +318,7 @@ class BinaryFocalLossWithLogits(nn.Module):
self.pos_weight: Optional[Tensor] = pos_weight
self.weight: Optional[Tensor] = weight
- def forward(self, input: Tensor, target: Tensor) -> Tensor:
+ def forward(self, pred: Tensor, target: Tensor) -> Tensor:
return binary_focal_loss_with_logits(
- input, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight
+ pred, target, self.alpha, self.gamma, self.reduction, self.pos_weight, self.weight
)
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index 37688a304..6ab148a81 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -6,7 +6,7 @@ from torch import nn
from kornia import metrics
-def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
+def psnr_loss(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
r"""Function that computes the PSNR loss.
The loss is computed as follows:
@@ -18,9 +18,9 @@ def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torc
See :meth:`~kornia.losses.psnr` for details abut PSNR.
Args:
- input: the input image with shape :math:`(*)`.
+ image: the input image with shape :math:`(*)`.
labels : the labels image with shape :math:`(*)`.
- max_val: The maximum value in the input tensor.
+ max_val: The maximum value in the image tensor.
Return:
the computed loss as a scalar.
@@ -30,7 +30,7 @@ def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torc
>>> psnr_loss(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)
tensor(-20.0000)
"""
- return -1.0 * metrics.psnr(input, target, max_val)
+ return -1.0 * metrics.psnr(image, target, max_val)
class PSNRLoss(nn.Module):
@@ -45,11 +45,11 @@ class PSNRLoss(nn.Module):
See :meth:`~kornia.losses.psnr` for details abut PSNR.
Args:
- max_val: The maximum value in the input tensor.
+ max_val: The maximum value in the image tensor.
Shape:
- - Input: arbitrary dimensional tensor :math:`(*)`.
- - Target: arbitrary dimensional tensor :math:`(*)` same shape as input.
+ - Image: arbitrary dimensional tensor :math:`(*)`.
+ - Target: arbitrary dimensional tensor :math:`(*)` same shape as image.
- Output: a scalar.
Examples:
@@ -63,5 +63,5 @@ class PSNRLoss(nn.Module):
super().__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)
+ def forward(self, image: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ return psnr_loss(image, target, self.max_val)
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 6d43ab2d7..cfbbf56a8 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -11,7 +11,7 @@ from kornia.utils.one_hot import one_hot
def tversky_loss(
- input: torch.Tensor, target: torch.Tensor, alpha: float, beta: float, eps: float = 1e-8
+ pred: torch.Tensor, target: torch.Tensor, alpha: float, beta: float, eps: float = 1e-8
) -> torch.Tensor:
r"""Criterion that computes Tversky Coefficient loss.
@@ -34,7 +34,7 @@ def tversky_loss(
- :math:`\alpha + \beta = 1` => F beta coeff
Args:
- input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
+ pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
target: labels tensor with shape :math:`(N, H, W)` where each value
is :math:`0 ≤ targets[i] ≤ C-1`.
alpha: the first coefficient in the denominator.
@@ -46,34 +46,34 @@ def tversky_loss(
Example:
>>> N = 5 # num_classes
- >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
- >>> output = tversky_loss(input, target, alpha=0.5, beta=0.5)
+ >>> output = tversky_loss(pred, target, alpha=0.5, beta=0.5)
>>> output.backward()
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if not isinstance(pred, torch.Tensor):
+ raise TypeError(f"pred type is not a torch.Tensor. Got {type(pred)}")
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxNxHxW. Got: {input.shape}")
+ if not len(pred.shape) == 4:
+ raise ValueError(f"Invalid pred shape, we expect BxNxHxW. Got: {pred.shape}")
- if not input.shape[-2:] == target.shape[-2:]:
- raise ValueError(f"input and target shapes must be the same. Got: {input.shape} and {input.shape}")
+ if not pred.shape[-2:] == target.shape[-2:]:
+ raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")
- if not input.device == target.device:
- raise ValueError(f"input and target must be in the same device. Got: {input.device} and {target.device}")
+ if not pred.device == target.device:
+ raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")
# compute softmax over the classes axis
- input_soft: torch.Tensor = F.softmax(input, dim=1)
+ pred_soft: torch.Tensor = F.softmax(pred, dim=1)
# create the labels one hot tensor
- target_one_hot: torch.Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
# compute the actual dice score
dims = (1, 2, 3)
- intersection = torch.sum(input_soft * target_one_hot, dims)
- fps = torch.sum(input_soft * (-target_one_hot + 1.0), dims)
- fns = torch.sum((-input_soft + 1.0) * target_one_hot, dims)
+ intersection = torch.sum(pred_soft * target_one_hot, dims)
+ fps = torch.sum(pred_soft * (-target_one_hot + 1.0), dims)
+ fns = torch.sum((-pred_soft + 1.0) * target_one_hot, dims)
numerator = intersection
denominator = intersection + alpha * fps + beta * fns
@@ -109,16 +109,16 @@ class TverskyLoss(nn.Module):
eps: scalar for numerical stability.
Shape:
- - Input: :math:`(N, C, H, W)` where C = number of classes.
+ - Pred: :math:`(N, C, H, W)` where C = number of classes.
- Target: :math:`(N, H, W)` where each value is
:math:`0 ≤ targets[i] ≤ C-1`.
Examples:
>>> N = 5 # num_classes
>>> criterion = TverskyLoss(alpha=0.5, beta=0.5)
- >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
+ >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
- >>> output = criterion(input, target)
+ >>> output = criterion(pred, target)
>>> output.backward()
"""
@@ -128,5 +128,5 @@ class TverskyLoss(nn.Module):
self.beta: float = beta
self.eps: float = eps
- def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
- return tversky_loss(input, target, self.alpha, self.beta, self.eps)
+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ return tversky_loss(pred, target, self.alpha, self.beta, self.eps)
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index 4d7799bf7..05e1293f0 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -3,11 +3,11 @@ from typing import List, Tuple
from kornia.core import Tensor
-def accuracy(input: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List[Tensor]:
+def accuracy(pred: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List[Tensor]:
"""Computes the accuracy over the k top predictions for the specified values of k.
Args:
- input: the input tensor with the logits to evaluate.
+ pred: the input tensor with the logits to evaluate.
target: the tensor containing the ground truth.
topk: the expected topk ranking.
@@ -17,9 +17,9 @@ def accuracy(input: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> Lis
>>> accuracy(logits, target)
[tensor(100.)]
"""
- maxk = min(max(topk), input.size()[1])
+ maxk = min(max(topk), pred.size()[1])
batch_size = target.size(0)
- _, pred = input.topk(maxk, 1, True, True)
+ _, pred = pred.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
return [correct[: min(k, maxk)].reshape(-1).float().sum(0) * 100.0 / batch_size for k in topk]
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index a96c68802..697a8aef0 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -5,12 +5,12 @@ import torch
def confusion_matrix(
- input: torch.Tensor, target: torch.Tensor, num_classes: int, normalized: bool = False
+ pred: torch.Tensor, target: torch.Tensor, num_classes: int, normalized: bool = False
) -> torch.Tensor:
r"""Compute confusion matrix to evaluate the accuracy of a classification.
Args:
- input: tensor with estimated targets returned by a
+ pred: tensor with estimated targets returned by a
classifier. The shape can be :math:`(B, *)` and must contain integer
values between 0 and K-1.
target: tensor with ground truth (correct) target
@@ -32,24 +32,24 @@ def confusion_matrix(
[0., 1., 0.],
[0., 0., 0.]]])
"""
- if not torch.is_tensor(input) and input.dtype is not torch.int64:
- raise TypeError(f"Input input type is not a torch.Tensor with torch.int64 dtype. Got {type(input)}")
+ if not torch.is_tensor(pred) and pred.dtype is not torch.int64:
+ raise TypeError(f"Input pred type is not a torch.Tensor with torch.int64 dtype. Got {type(pred)}")
if not torch.is_tensor(target) and target.dtype is not torch.int64:
raise TypeError(f"Input target type is not a torch.Tensor with torch.int64 dtype. Got {type(target)}")
- if not input.shape == target.shape:
- raise ValueError(f"Inputs input and target must have the same shape. Got: {input.shape} and {target.shape}")
- if not input.device == target.device:
- raise ValueError(f"Inputs must be in the same device. Got: {input.device} - {target.device}")
+ if not pred.shape == target.shape:
+ raise ValueError(f"Inputs pred and target must have the same shape. Got: {pred.shape} and {target.shape}")
+ if not pred.device == target.device:
+ raise ValueError(f"Inputs must be in the same device. Got: {pred.device} - {target.device}")
if not isinstance(num_classes, int) or num_classes < 2:
raise ValueError(f"The number of classes must be an integer bigger than two. Got: {num_classes}")
- batch_size: int = input.shape[0]
+ batch_size: int = pred.shape[0]
# hack for bitcounting 2 arrays together
# NOTE: torch.bincount does not implement batched version
- pre_bincount: torch.Tensor = input + target * num_classes
+ pre_bincount: torch.Tensor = pred + target * num_classes
pre_bincount_vec: torch.Tensor = pre_bincount.view(batch_size, -1)
confusion_list = []
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index 26173c8ba..a668f09d5 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -3,13 +3,13 @@ import torch
from .confusion_matrix import confusion_matrix
-def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: float = 1e-6) -> torch.Tensor:
+def mean_iou(pred: torch.Tensor, target: torch.Tensor, num_classes: int, eps: float = 1e-6) -> torch.Tensor:
r"""Calculate mean Intersection-Over-Union (mIOU).
The function internally computes the confusion matrix.
Args:
- input : tensor with estimated targets returned by a
+ pred : tensor with estimated targets returned by a
classifier. The shape can be :math:`(B, *)` and must contain integer
values between 0 and K-1.
target: tensor with ground truth (correct) target
@@ -28,21 +28,21 @@ def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: f
>>> mean_iou(logits, target, num_classes=3)
tensor([[1., 1., 1.]])
"""
- if not torch.is_tensor(input) and input.dtype is not torch.int64:
- raise TypeError(f"Input input type is not a torch.Tensor with torch.int64 dtype. Got {type(input)}")
+ if not torch.is_tensor(pred) and pred.dtype is not torch.int64:
+ raise TypeError(f"Input pred type is not a torch.Tensor with torch.int64 dtype. Got {type(pred)}")
if not torch.is_tensor(target) and target.dtype is not torch.int64:
raise TypeError(f"Input target type is not a torch.Tensor with torch.int64 dtype. Got {type(target)}")
- if not input.shape == target.shape:
- raise ValueError(f"Inputs input and target must have the same shape. Got: {input.shape} and {target.shape}")
- if not input.device == target.device:
- raise ValueError(f"Inputs must be in the same device. Got: {input.device} - {target.device}")
+ if not pred.shape == target.shape:
+ raise ValueError(f"Inputs pred and target must have the same shape. Got: {pred.shape} and {target.shape}")
+ if not pred.device == target.device:
+ raise ValueError(f"Inputs must be in the same device. Got: {pred.device} - {target.device}")
if not isinstance(num_classes, int) or num_classes < 2:
raise ValueError(f"The number of classes must be an integer bigger than two. Got: {num_classes}")
# we first compute the confusion matrix
- conf_mat: torch.Tensor = confusion_matrix(input, target, num_classes)
+ conf_mat: torch.Tensor = confusion_matrix(pred, target, num_classes)
# compute the actual intersection over union
sum_over_row = torch.sum(conf_mat, dim=1)
diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.py
index 549cacbf3..ba40e0748 100644
--- a/kornia/metrics/psnr.py
+++ b/kornia/metrics/psnr.py
@@ -2,7 +2,7 @@ import torch
from torch.nn.functional import mse_loss as mse
-def psnr(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
+def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
r"""Create a function that calculates the PSNR between 2 images.
PSNR is Peek Signal to Noise Ratio, which is similar to mean squared error.
@@ -22,7 +22,7 @@ def psnr(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
(e.g for floating point images :math:`\text{MAX}_I=1`).
Args:
- input: the input image with arbitrary shape :math:`(*)`.
+ image: the input image with arbitrary shape :math:`(*)`.
labels: the labels image with arbitrary shape :math:`(*)`.
max_val: The maximum value in the input tensor.
@@ -37,13 +37,13 @@ def psnr(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
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(input)}.")
+ if not isinstance(image, torch.Tensor):
+ raise TypeError(f"Expected torch.Tensor but got {type(image)}.")
if not isinstance(target, torch.Tensor):
raise TypeError(f"Expected torch.Tensor but got {type(target)}.")
- if input.shape != target.shape:
- raise TypeError(f"Expected tensors of equal shapes, but got {input.shape} and {target.shape}")
+ if image.shape != target.shape:
+ raise TypeError(f"Expected tensors of equal shapes, but got {image.shape} and {target.shape}")
- return 10.0 * torch.log10(max_val**2 / mse(input, target, reduction='mean'))
+ return 10.0 * torch.log10(max_val**2 / mse(image, target, reduction='mean'))
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index f444bda87..f61a466d9 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -262,7 +262,7 @@ def _get_precision_by_name(
def _default_tolerances(*inputs: Any) -> Tuple[float, float]:
- rtols, atols = zip(*[_DTYPE_PRECISIONS.get(torch.as_tensor(input).dtype, (0.0, 0.0)) for input in inputs])
+ rtols, atols = zip(*[_DTYPE_PRECISIONS.get(torch.as_tensor(input_).dtype, (0.0, 0.0)) for input_ in inputs])
return max(rtols), max(atols)
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index 9005fa39c..56629ea74 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -189,19 +189,19 @@ class TestTverskyLoss:
with pytest.raises(TypeError) as errinfo:
criterion('not a tensor', torch.rand(1))
- assert 'Input type is not a torch.Tensor. Got' in str(errinfo)
+ assert 'pred type is not a torch.Tensor. Got' in str(errinfo)
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1), torch.rand(1))
- assert 'Invalid input shape, we expect BxNxHxW. Got:' in str(errinfo)
+ assert 'Invalid pred shape, we expect BxNxHxW. Got:' in str(errinfo)
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
- assert 'input and target shapes must be the same. Got:' in str(errinfo)
+ assert 'pred and target shapes must be the same. Got:' in str(errinfo)
with pytest.raises(ValueError) as errinfo:
criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
- assert 'input and target must be in the same device. Got:' in str(errinfo)
+ assert 'pred and target must be in the same device. Got:' in str(errinfo)
def test_all_zeros(self, device, dtype):
num_classes = 3
@@ -281,15 +281,15 @@ class TestDiceLoss:
def test_exception(self):
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1), torch.rand(1, 1, 1))
- assert 'Invalid input shape, we expect BxNxHxW. Got:' in str(errinf)
+ assert 'Invalid pred shape, we expect BxNxHxW. Got:' in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 2))
- assert 'input and target shapes must be the same. Got: ' in str(errinf)
+ assert 'pred and target shapes must be the same. Got: ' in str(errinf)
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device='meta'))
- assert 'input and target must be in the same device. Got:' in str(errinf)
+ assert 'pred and target must be in the same device. Got:' in str(errinf)
def test_averaging_micro(self, device, dtype):
num_classes = 2
@@ -446,7 +446,7 @@ class TestDepthSmoothnessLoss:
class TestDivergenceLoss:
@pytest.mark.parametrize(
- "input,target,expected",
+ "pred,target,expected",
[
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
@@ -454,13 +454,13 @@ class TestDivergenceLoss:
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
],
)
- 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))
+ def test_js_div_loss_2d(self, device, dtype, pred, target, expected):
+ actual = kornia.losses.js_div_loss_2d(pred.to(device, dtype), target.to(device, dtype))
expected = torch.tensor(expected).to(device, dtype)
assert_close(actual, expected)
@pytest.mark.parametrize(
- "input,target,expected",
+ "pred,target,expected",
[
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
@@ -468,13 +468,13 @@ class TestDivergenceLoss:
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
],
)
- 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))
+ def test_kl_div_loss_2d(self, device, dtype, pred, target, expected):
+ actual = kornia.losses.kl_div_loss_2d(pred.to(device, dtype), target.to(device, dtype))
expected = torch.tensor(expected).to(device, dtype)
assert_close(actual, expected)
@pytest.mark.parametrize(
- "input,target,expected",
+ "pred,target,expected",
[
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1), 0.0)),
(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7), 0.0)),
@@ -482,12 +482,12 @@ class TestDivergenceLoss:
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7), math.inf)),
],
)
- 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")
+ def test_kl_div_loss_2d_without_reduction(self, device, dtype, pred, target, expected):
+ actual = kornia.losses.kl_div_loss_2d(pred.to(device, dtype), target.to(device, dtype), reduction="none")
assert_close(actual, expected.to(device, dtype))
@pytest.mark.parametrize(
- "input,target,expected",
+ "pred,target,expected",
[
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
@@ -495,15 +495,15 @@ class TestDivergenceLoss:
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
],
)
- def test_noncontiguous_kl(self, device, dtype, input, target, expected):
- input = input.to(device, dtype).view(input.shape[::-1]).transpose(-2, -1)
+ def test_noncontiguous_kl(self, device, dtype, pred, target, expected):
+ pred = pred.to(device, dtype).view(pred.shape[::-1]).transpose(-2, -1)
target = target.to(device, dtype).view(target.shape[::-1]).transpose(-2, -1)
- actual = kornia.losses.kl_div_loss_2d(input, target)
+ actual = kornia.losses.kl_div_loss_2d(pred, target)
expected = torch.tensor(expected).to(device, dtype)
assert_close(actual, expected)
@pytest.mark.parametrize(
- "input,target,expected",
+ "pred,target,expected",
[
(torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
(torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
@@ -511,43 +511,43 @@ class TestDivergenceLoss:
(torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.303251),
],
)
- def test_noncontiguous_js(self, device, dtype, input, target, expected):
- input = input.to(device, dtype).view(input.shape[::-1]).transpose(-2, -1)
+ def test_noncontiguous_js(self, device, dtype, pred, target, expected):
+ pred = pred.to(device, dtype).view(pred.shape[::-1]).transpose(-2, -1)
target = target.to(device, dtype).view(target.shape[::-1]).transpose(-2, -1)
- actual = kornia.losses.js_div_loss_2d(input, target)
+ actual = kornia.losses.js_div_loss_2d(pred, target)
expected = torch.tensor(expected).to(device, dtype)
assert_close(actual, expected)
def test_gradcheck_kl(self, device, dtype):
- input = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
+ pred = 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 = tensor_to_gradcheck_var(input) # to var
+ pred = tensor_to_gradcheck_var(pred) # to var
target = tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.kl_div_loss_2d, (input, target), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.losses.kl_div_loss_2d, (pred, target), raise_exception=True, fast_mode=True)
def test_gradcheck_js(self, device, dtype):
- input = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
+ pred = 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 = tensor_to_gradcheck_var(input) # to var
+ pred = tensor_to_gradcheck_var(pred) # to var
target = tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.js_div_loss_2d, (input, target), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.losses.js_div_loss_2d, (pred, target), raise_exception=True, fast_mode=True)
def test_dynamo_kl(self, device, dtype, torch_optimizer):
- input = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
+ pred = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
target = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
- args = (input, target)
+ args = (pred, target)
op = kornia.losses.kl_div_loss_2d
op_optimized = torch_optimizer(op)
assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
def test_dynamo_js(self, device, dtype, torch_optimizer):
- input = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
+ pred = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
target = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
- args = (input, target)
+ args = (pred, target)
op = kornia.losses.js_div_loss_2d
op_optimized = torch_optimizer(op)
assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
@@ -556,31 +556,31 @@ class TestDivergenceLoss:
class TestTotalVariation:
# Total variation of constant vectors is 0
@pytest.mark.parametrize(
- "input, expected",
+ "pred, expected",
[
(torch.ones(3, 4, 5), torch.tensor([0.0, 0.0, 0.0])),
(2 * torch.ones(2, 3, 4, 5), torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])),
],
)
- def test_tv_on_constant(self, device, dtype, input, expected):
- actual = kornia.losses.total_variation(input.to(device, dtype))
+ def test_tv_on_constant(self, device, dtype, pred, expected):
+ actual = kornia.losses.total_variation(pred.to(device, dtype))
assert_close(actual, expected.to(device, dtype))
# Total variation of constant vectors is 0
@pytest.mark.parametrize(
- "input, expected",
+ "pred, expected",
[
(torch.ones(3, 4, 5), torch.tensor([0.0, 0.0, 0.0])),
(2 * torch.ones(2, 3, 4, 5), torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])),
],
)
- def test_tv_on_constant_int(self, device, input, expected):
- actual = kornia.losses.total_variation(input.to(device, dtype=torch.int32), reduction='mean')
+ def test_tv_on_constant_int(self, device, pred, expected):
+ actual = kornia.losses.total_variation(pred.to(device, dtype=torch.int32), reduction='mean')
assert_close(actual, expected.to(device))
# Total variation for 3D tensors
@pytest.mark.parametrize(
- "input, expected",
+ "pred, expected",
[
(
torch.tensor(
@@ -613,13 +613,13 @@ class TestTotalVariation:
),
],
)
- def test_tv_on_3d(self, device, dtype, input, expected):
- actual = kornia.losses.total_variation(input.to(device, dtype))
+ def test_tv_on_3d(self, device, dtype, pred, expected):
+ actual = kornia.losses.total_variation(pred.to(device, dtype))
assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
# Total variation for 4D tensors
@pytest.mark.parametrize(
- "input, expected",
+ "pred, expected",
[
(
torch.tensor(
@@ -650,33 +650,33 @@ class TestTotalVariation:
),
],
)
- def test_tv_on_4d(self, device, dtype, input, expected):
- actual = kornia.losses.total_variation(input.to(device, dtype))
+ def test_tv_on_4d(self, device, dtype, pred, expected):
+ actual = kornia.losses.total_variation(pred.to(device, dtype))
assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
- @pytest.mark.parametrize("input", [torch.rand(3, 5, 5), torch.rand(4, 3, 5, 5), torch.rand(4, 2, 3, 5, 5)])
- def test_tv_shapes(self, device, dtype, input):
- input = input.to(device, dtype)
+ @pytest.mark.parametrize("pred", [torch.rand(3, 5, 5), torch.rand(4, 3, 5, 5), torch.rand(4, 2, 3, 5, 5)])
+ def test_tv_shapes(self, device, dtype, pred):
+ pred = pred.to(device, dtype)
actual_lesser_dims = []
- for slice in torch.unbind(input, dim=0):
+ for slice in torch.unbind(pred, dim=0):
slice_tv = kornia.losses.total_variation(slice)
actual_lesser_dims.append(slice_tv)
actual_lesser_dims = torch.stack(actual_lesser_dims, dim=0)
- actual_higher_dims = kornia.losses.total_variation(input)
+ actual_higher_dims = kornia.losses.total_variation(pred)
assert_close(actual_lesser_dims, actual_higher_dims.to(device, dtype), rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("reduction, expected", [("sum", torch.tensor(20)), ("mean", torch.tensor(1))])
def test_tv_reduction(self, device, dtype, reduction, expected):
- input, _ = torch_meshgrid([torch.arange(5), torch.arange(5)], "ij")
- input = input.to(device, dtype)
- actual = kornia.losses.total_variation(input, reduction=reduction)
+ pred, _ = torch_meshgrid([torch.arange(5), torch.arange(5)], "ij")
+ pred = pred.to(device, dtype)
+ actual = kornia.losses.total_variation(pred, reduction=reduction)
assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)
# 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, device, dtype, input):
+ @pytest.mark.parametrize("pred", [1, [1, 2]])
+ def test_tv_on_invalid_types(self, device, dtype, pred):
with pytest.raises(TypeError):
- kornia.losses.total_variation(input)
+ kornia.losses.total_variation(pred)
def test_dynamo(self, device, dtype, torch_optimizer):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -702,11 +702,11 @@ class TestTotalVariation:
class TestPSNRLoss:
def test_smoke(self, device, dtype):
- input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ pred = 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)
+ loss = criterion(pred, target)
assert loss is not None
@@ -725,16 +725,16 @@ class TestPSNRLoss:
criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))
def test_loss(self, device, dtype):
- input = torch.ones(1, device=device, dtype=dtype)
+ pred = 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.0)
+ actual = kornia.losses.psnr_loss(pred, 1.2 * pred, 2.0)
assert_close(actual, expected)
def test_dynamo(self, device, dtype, torch_optimizer):
- input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ pred = 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.0)
+ args = (pred, target, 1.0)
op = kornia.losses.psnr_loss
op_optimized = torch_optimizer(op)
@@ -742,22 +742,22 @@ class TestPSNRLoss:
assert_close(op(*args), op_optimized(*args))
def test_module(self, device, dtype):
- input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ pred = 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.0)
+ args = (pred, target, 1.0)
op = kornia.losses.psnr_loss
op_module = kornia.losses.PSNRLoss(1.0)
- assert_close(op(*args), op_module(input, target))
+ assert_close(op(*args), op_module(pred, target))
def test_gradcheck(self, device, dtype):
- input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
- input = tensor_to_gradcheck_var(input) # to var
+ pred = tensor_to_gradcheck_var(pred) # to var
target = tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.psnr_loss, (input, target, 1.0), raise_exception=True, fast_mode=True)
+ assert gradcheck(kornia.losses.psnr_loss, (pred, target, 1.0), raise_exception=True, fast_mode=True)
class TestLovaszHingeLoss: