π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
create metrics submodule (#1325)
Edgar Riba5809aa062f76
diff --git a/docs/source/index.rst b/docs/source/index.rstindex 0ac61e084..d45cab622 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -81,6 +81,7 @@ Join the communityfiltersgeometrylosses+ metricsmorphologyutilsxdiff --git a/docs/source/losses.rst b/docs/source/losses.rstindex be4472bb5..070ddcd3c 100644--- a/docs/source/losses.rst+++ b/docs/source/losses.rst@@ -6,9 +6,7 @@ kornia.lossesReconstruction---------------.. autofunction:: ssim.. autofunction:: ssim_loss-.. autofunction:: psnr.. autofunction:: psnr_loss.. autofunction:: total_variation.. autofunction:: inverse_depth_smoothness_loss@@ -33,7 +31,6 @@ Module.. autoclass:: DiceLoss.. autoclass:: TverskyLoss.. autoclass:: FocalLoss-.. autoclass:: SSIM.. autoclass:: SSIMLoss.. autoclass:: InverseDepthSmoothnessLoss.. autoclass:: TotalVariationdiff --git a/docs/source/metrics.rst b/docs/source/metrics.rstnew file mode 100644index 000000000..590599665--- /dev/null+++ b/docs/source/metrics.rst@@ -0,0 +1,29 @@+kornia.metrics+==============++.. currentmodule:: kornia.metrics++Module containing metrics for training networks++Classification+==============++.. autofunction:: accuracy++Segmentation+============++.. autofunction:: confusion_matrix+.. autofunction:: mean_iou++Image Quality+==============++.. autofunction:: psnr+.. autofunction:: ssim+.. autoclass:: SSIM++Monitoring+==========++.. autoclass:: AverageMeterdiff --git a/docs/source/utils.rst b/docs/source/utils.rstindex b9410af05..b8dd1a5bf 100644--- a/docs/source/utils.rst+++ b/docs/source/utils.rst@@ -22,14 +22,8 @@ Pointcloud.. autofunction:: save_pointcloud_ply.. autofunction:: load_pointcloud_ply-Metrics----------.. autofunction:: confusion_matrix-.. autofunction:: mean_iou-.. autofunction:: one_hot-Memory-------+.. autofunction:: one_hot.. autofunction:: batched_forwarddiff --git a/kornia/__init__.py b/kornia/__init__.pyindex 71311f337..45881b35a 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -10,7 +10,21 @@ try:except ImportError:pass-from kornia import augmentation, color, contrib, enhance, feature, filters, geometry, jit, losses, morphology, utils, x+from kornia import (+ augmentation,+ color,+ contrib,+ enhance,+ feature,+ filters,+ geometry,+ jit,+ losses,+ metrics,+ morphology,+ utils,+ x,+)from kornia.color import (bgr_to_grayscale,bgr_to_rgb,diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.pyindex b67fe5b3c..14c7be7ab 100644--- a/kornia/geometry/epipolar/__init__.py+++ b/kornia/geometry/epipolar/__init__.py@@ -1,6 +1,6 @@+from ._metrics import *from .essential import *from .fundamental import *-from .metrics import *from .numeric import *from .projection import *from .scene import *diff --git a/kornia/geometry/epipolar/metrics.py b/kornia/geometry/epipolar/_metrics.pysimilarity index 100%rename from kornia/geometry/epipolar/metrics.pyrename to kornia/geometry/epipolar/_metrics.pydiff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex b7990a181..c7b2335a2 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -3,7 +3,7 @@ from .dice import dice_loss, DiceLossfrom .divergence import js_div_loss_2d, kl_div_loss_2dfrom .focal import binary_focal_loss_with_logits, BinaryFocalLossWithLogits, focal_loss, FocalLossfrom .hausdorff import HausdorffERLoss, HausdorffERLoss3D-from .psnr import psnr, psnr_loss, PSNRLoss-from .ssim import SSIM, ssim, ssim_loss, SSIMLoss+from .psnr import psnr_loss, PSNRLoss+from .ssim import ssim_loss, SSIMLossfrom .total_variation import total_variation, TotalVariationfrom .tversky import tversky_loss, TverskyLossdiff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.pyindex bf48eae98..b56f8a7b8 100644--- a/kornia/losses/psnr.py+++ b/kornia/losses/psnr.py@@ -2,52 +2,7 @@ import torchimport torch.nn as nnfrom torch.nn.functional import mse_loss as mse--def psnr(input: 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.- Given an m x n image, the PSNR is:-- .. math::-- \text{PSNR} = 10 \log_{10} \bigg(\frac{\text{MAX}_I^2}{MSE(I,T)}\bigg)-- where-- .. math::-- \text{MSE}(I,T) = \frac{1}{mn}\sum_{i=0}^{m-1}\sum_{j=0}^{n-1} [I(i,j) - T(i,j)]^2-- and :math:`\text{MAX}_I` is the maximum possible input value- (e.g for floating point images :math:`\text{MAX}_I=1`).-- Args:- input: the input image with arbitrary shape :math:`(*)`.- labels: the labels image with arbitrary shape :math:`(*)`.- max_val: The maximum value in the input tensor.-- Return:- the computed loss as a scalar.-- Examples:- >>> ones = torch.ones(1)- >>> psnr(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)- tensor(20.0000)-- Reference:- https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition- """- if not isinstance(input, torch.Tensor):- raise TypeError(f"Expected torch.Tensor but got {type(target)}.")-- if not isinstance(target, torch.Tensor):- raise TypeError(f"Expected torch.Tensor but got {type(input)}.")-- if input.shape != target.shape:- raise TypeError(f"Expected tensors of equal shapes, but got {input.shape} and {target.shape}")-- return 10.0 * torch.log10(max_val ** 2 / mse(input, target, reduction='mean'))+import kornia.metrics as metricsdef psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:@@ -75,7 +30,7 @@ def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torctensor(-20.0000)"""- return -1.0 * psnr(input, target, max_val)+ return -1.0 * metrics.psnr(input, target, max_val)class PSNRLoss(nn.Module):diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.pyindex 77b3747d7..33026ba34 100644--- a/kornia/losses/ssim.py+++ b/kornia/losses/ssim.py@@ -1,87 +1,7 @@import torchimport torch.nn as nn-from kornia.filters import filter2d, get_gaussian_kernel2d---def ssim(- img1: torch.Tensor, img2: torch.Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12-) -> torch.Tensor:- r"""Function that computes the Structural Similarity (SSIM) index map between two images.-- Measures the (SSIM) index between each element in the input `x` and target `y`.-- The index can be described as:-- .. math::-- \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}- {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}-- where:- - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to- stabilize the division with weak denominator.- - :math:`L` is the dynamic range of the pixel-values (typically this is- :math:`2^{\#\text{bits per pixel}}-1`).-- Args:- img1: the first input image with shape :math:`(B, C, H, W)`.- img2: the second input image with shape :math:`(B, C, H, W)`.- window_size: the size of the gaussian kernel to smooth the images.- max_val: the dynamic range of the images.- eps: Small value for numerically stability when dividing.-- Returns:- The ssim index map with shape :math:`(B, C, H, W)`.-- Examples:- >>> input1 = torch.rand(1, 4, 5, 5)- >>> input2 = torch.rand(1, 4, 5, 5)- >>> ssim_map = ssim(input1, input2, 5) # 1x4x5x5- """- if not isinstance(img1, torch.Tensor):- raise TypeError(f"Input img1 type is not a torch.Tensor. Got {type(img1)}")-- if not isinstance(img2, torch.Tensor):- raise TypeError(f"Input img2 type is not a torch.Tensor. Got {type(img2)}")-- if not isinstance(max_val, float):- raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")-- if not len(img1.shape) == 4:- raise ValueError(f"Invalid img1 shape, we expect BxCxHxW. Got: {img1.shape}")-- if not len(img2.shape) == 4:- raise ValueError(f"Invalid img2 shape, we expect BxCxHxW. Got: {img2.shape}")-- if not img1.shape == img2.shape:- raise ValueError(f"img1 and img2 shapes must be the same. Got: {img1.shape} and {img2.shape}")-- # prepare kernel- kernel: torch.Tensor = get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5)).unsqueeze(0)-- # compute coefficients- C1: float = (0.01 * max_val) ** 2- C2: float = (0.03 * max_val) ** 2-- # compute local mean per channel- mu1: torch.Tensor = filter2d(img1, kernel)- mu2: torch.Tensor = filter2d(img2, kernel)-- mu1_sq = mu1 ** 2- mu2_sq = mu2 ** 2- mu1_mu2 = mu1 * mu2-- # compute local sigma per channel- sigma1_sq = filter2d(img1 ** 2, kernel) - mu1_sq- sigma2_sq = filter2d(img2 ** 2, kernel) - mu2_sq- sigma12 = filter2d(img1 * img2, kernel) - mu1_mu2-- # compute the similarity index map- num: torch.Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)- den: torch.Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)-- return num / (den + eps)+import kornia.metrics as metricsdef ssim_loss(@@ -122,7 +42,7 @@ def ssim_loss(>>> loss = ssim_loss(input1, input2, 5)"""# compute the ssim map- ssim_map: torch.Tensor = ssim(img1, img2, window_size, max_val, eps)+ ssim_map: torch.Tensor = metrics.ssim(img1, img2, window_size, max_val, eps)# compute and reduce the lossloss = torch.clamp((1.0 - ssim_map) / 2, min=0, max=1)@@ -136,51 +56,6 @@ def ssim_loss(return loss-class SSIM(nn.Module):- r"""Create a module that computes the Structural Similarity (SSIM) index between two images.-- Measures the (SSIM) index between each element in the input `x` and target `y`.-- The index can be described as:-- .. math::-- \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}- {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}-- where:- - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to- stabilize the division with weak denominator.- - :math:`L` is the dynamic range of the pixel-values (typically this is- :math:`2^{\#\text{bits per pixel}}-1`).-- Args:- window_size: the size of the gaussian kernel to smooth the images.- max_val: the dynamic range of the images.- eps: Small value for numerically stability when dividing.-- Shape:- - Input: :math:`(B, C, H, W)`.- - Target :math:`(B, C, H, W)`.- - Output: :math:`(B, C, H, W)`.-- Examples:- >>> input1 = torch.rand(1, 4, 5, 5)- >>> input2 = torch.rand(1, 4, 5, 5)- >>> ssim = SSIM(5)- >>> ssim_map = ssim(input1, input2) # 1x4x5x5- """-- def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12) -> None:- super().__init__()- self.window_size: int = window_size- self.max_val: float = max_val- self.eps = eps-- def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:- return ssim(img1, img2, self.window_size, self.max_val, self.eps)--class SSIMLoss(nn.Module):r"""Create a criterion that computes a loss based on the SSIM measurement.diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.pynew file mode 100644index 000000000..ba7c0775d--- /dev/null+++ b/kornia/metrics/__init__.py@@ -0,0 +1,6 @@+from .accuracy import accuracy+from .average_meter import AverageMeter+from .confusion_matrix import confusion_matrix+from .mean_iou import mean_iou+from .psnr import psnr+from .ssim import ssim, SSIMdiff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.pynew file mode 100644index 000000000..a0ab9a66b--- /dev/null+++ b/kornia/metrics/accuracy.py@@ -0,0 +1,19 @@+from typing import List++import torch+++def accuracy(input: torch.Tensor, target: torch.Tensor, topk=(1,)) -> List[torch.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.+ target: the tensor containing the ground truth.+ topk: the expected topk ranking.+ """+ maxk = min(max(topk), input.size()[1])+ batch_size = target.size(0)+ _, pred = input.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. / batch_size for k in topk]diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.pynew file mode 100644index 000000000..54fb98858--- /dev/null+++ b/kornia/metrics/average_meter.py@@ -0,0 +1,29 @@+from typing import Union++import torch+++class AverageMeter:+ """Computes and stores the average and current value.++ Example:+ >>> stats = AverageMeter()+ >>> acc1 = torch.tensor(0.99) # coming from K.metrics.accuracy+ >>> stats.update(acc1, n=1) # where n is batch size usually+ >>> stats.avg+ tensor(0.9900)+ """+ def __init__(self) -> None:+ self.reset()++ def reset(self):+ self.val = 0+ self.avg = 0+ self.sum = 0+ self.count = 0++ def update(self, val: Union[int, float, bool, torch.Tensor], n: int = 1) -> None:+ self.val = val+ self.sum += val * n+ self.count += n+ self.avg = self.sum / self.countdiff --git a/kornia/utils/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.pysimilarity index 100%rename from kornia/utils/metrics/confusion_matrix.pyrename to kornia/metrics/confusion_matrix.pydiff --git a/kornia/utils/metrics/mean_iou.py b/kornia/metrics/mean_iou.pysimilarity index 96%rename from kornia/utils/metrics/mean_iou.pyrename to kornia/metrics/mean_iou.pyindex 2705f4784..adb9d57f4 100644--- a/kornia/utils/metrics/mean_iou.py+++ b/kornia/metrics/mean_iou.py@@ -1,8 +1,6 @@-from typing import Optional-import torch-from kornia.utils.metrics.confusion_matrix import confusion_matrix+from .confusion_matrix import confusion_matrixdef mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: float = 1e-6) -> torch.Tensor:diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.pynew file mode 100644index 000000000..86f319dc4--- /dev/null+++ b/kornia/metrics/psnr.py@@ -0,0 +1,49 @@+import torch+from torch.nn.functional import mse_loss as mse+++def psnr(input: 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.+ Given an m x n image, the PSNR is:++ .. math::++ \text{PSNR} = 10 \log_{10} \bigg(\frac{\text{MAX}_I^2}{MSE(I,T)}\bigg)++ where++ .. math::++ \text{MSE}(I,T) = \frac{1}{mn}\sum_{i=0}^{m-1}\sum_{j=0}^{n-1} [I(i,j) - T(i,j)]^2++ and :math:`\text{MAX}_I` is the maximum possible input value+ (e.g for floating point images :math:`\text{MAX}_I=1`).++ Args:+ input: the input image with arbitrary shape :math:`(*)`.+ labels: the labels image with arbitrary shape :math:`(*)`.+ max_val: The maximum value in the input tensor.++ Return:+ the computed loss as a scalar.++ Examples:+ >>> ones = torch.ones(1)+ >>> psnr(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)+ tensor(20.0000)++ Reference:+ https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition+ """+ if not isinstance(input, torch.Tensor):+ raise TypeError(f"Expected torch.Tensor but got {type(target)}.")++ if not isinstance(target, torch.Tensor):+ raise TypeError(f"Expected torch.Tensor but got {type(input)}.")++ if input.shape != target.shape:+ raise TypeError(f"Expected tensors of equal shapes, but got {input.shape} and {target.shape}")++ return 10.0 * torch.log10(max_val ** 2 / mse(input, target, reduction='mean'))diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pynew file mode 100644index 000000000..e2be903a0--- /dev/null+++ b/kornia/metrics/ssim.py@@ -0,0 +1,129 @@+import torch+import torch.nn as nn++from kornia.filters import filter2d, get_gaussian_kernel2d+++def ssim(+ img1: torch.Tensor, img2: torch.Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12+) -> torch.Tensor:+ r"""Function that computes the Structural Similarity (SSIM) index map between two images.++ Measures the (SSIM) index between each element in the input `x` and target `y`.++ The index can be described as:++ .. math::++ \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}+ {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}++ where:+ - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to+ stabilize the division with weak denominator.+ - :math:`L` is the dynamic range of the pixel-values (typically this is+ :math:`2^{\#\text{bits per pixel}}-1`).++ Args:+ img1: the first input image with shape :math:`(B, C, H, W)`.+ img2: the second input image with shape :math:`(B, C, H, W)`.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.++ Returns:+ The ssim index map with shape :math:`(B, C, H, W)`.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 5)+ >>> input2 = torch.rand(1, 4, 5, 5)+ >>> ssim_map = ssim(input1, input2, 5) # 1x4x5x5+ """+ if not isinstance(img1, torch.Tensor):+ raise TypeError(f"Input img1 type is not a torch.Tensor. Got {type(img1)}")++ if not isinstance(img2, torch.Tensor):+ raise TypeError(f"Input img2 type is not a torch.Tensor. Got {type(img2)}")++ if not isinstance(max_val, float):+ raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")++ if not len(img1.shape) == 4:+ raise ValueError(f"Invalid img1 shape, we expect BxCxHxW. Got: {img1.shape}")++ if not len(img2.shape) == 4:+ raise ValueError(f"Invalid img2 shape, we expect BxCxHxW. Got: {img2.shape}")++ if not img1.shape == img2.shape:+ raise ValueError(f"img1 and img2 shapes must be the same. Got: {img1.shape} and {img2.shape}")++ # prepare kernel+ kernel: torch.Tensor = get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5)).unsqueeze(0)++ # compute coefficients+ C1: float = (0.01 * max_val) ** 2+ C2: float = (0.03 * max_val) ** 2++ # compute local mean per channel+ mu1: torch.Tensor = filter2d(img1, kernel)+ mu2: torch.Tensor = filter2d(img2, kernel)++ mu1_sq = mu1 ** 2+ mu2_sq = mu2 ** 2+ mu1_mu2 = mu1 * mu2++ # compute local sigma per channel+ sigma1_sq = filter2d(img1 ** 2, kernel) - mu1_sq+ sigma2_sq = filter2d(img2 ** 2, kernel) - mu2_sq+ sigma12 = filter2d(img1 * img2, kernel) - mu1_mu2++ # compute the similarity index map+ num: torch.Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)+ den: torch.Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)++ return num / (den + eps)+++class SSIM(nn.Module):+ r"""Create a module that computes the Structural Similarity (SSIM) index between two images.++ Measures the (SSIM) index between each element in the input `x` and target `y`.++ The index can be described as:++ .. math::++ \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}+ {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}++ where:+ - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to+ stabilize the division with weak denominator.+ - :math:`L` is the dynamic range of the pixel-values (typically this is+ :math:`2^{\#\text{bits per pixel}}-1`).++ Args:+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.++ Shape:+ - Input: :math:`(B, C, H, W)`.+ - Target :math:`(B, C, H, W)`.+ - Output: :math:`(B, C, H, W)`.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 5)+ >>> input2 = torch.rand(1, 4, 5, 5)+ >>> ssim = SSIM(5)+ >>> ssim_map = ssim(input1, input2) # 1x4x5x5+ """++ def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12) -> None:+ super().__init__()+ self.window_size: int = window_size+ self.max_val: float = max_val+ self.eps = eps++ def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor:+ return ssim(img1, img2, self.window_size, self.max_val, self.eps)diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex 9db7ea4e8..e51626986 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -1,5 +1,3 @@-from kornia.utils.metrics import *-from .draw import draw_rectanglefrom .grid import create_meshgrid, create_meshgrid3dfrom .helpers import _extract_device_dtypediff --git a/kornia/utils/metrics/__init__.py b/kornia/utils/metrics/__init__.pydeleted file mode 100644index a29a9d4e1..000000000--- a/kornia/utils/metrics/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from .confusion_matrix import confusion_matrix-from .mean_iou import mean_iou--__all__ = ["confusion_matrix", "mean_iou"]diff --git a/kornia/x/metrics.py b/kornia/x/metrics.pydeleted file mode 100644index 12802f0e5..000000000--- a/kornia/x/metrics.py+++ /dev/null@@ -1,29 +0,0 @@-# borrowed from timm: https://github.com/rwightman/pytorch-image-models/timm/utils/metrics.py---class AverageMeter:- """Computes and stores the average and current value."""- def __init__(self):- self.reset()-- def reset(self):- self.val = 0- self.avg = 0- self.sum = 0- self.count = 0-- def update(self, val, n=1):- self.val = val- self.sum += val * n- self.count += n- self.avg = self.sum / self.count---def accuracy(output, target, topk=(1,)):- """Computes the accuracy over the k top predictions for the specified values of k."""- maxk = min(max(topk), output.size()[1])- batch_size = target.size(0)- _, pred = output.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. / batch_size for k in topk]diff --git a/kornia/x/trainer.py b/kornia/x/trainer.pyindex 2ce6b6ee9..0696815c4 100644--- a/kornia/x/trainer.py+++ b/kornia/x/trainer.py@@ -12,7 +12,8 @@ try:except ImportError:Accelerator = None-from .metrics import AverageMeter+from kornia.metrics import AverageMeter+from .utils import Configuration, TrainerStatecallbacks_whitelist = [diff --git a/kornia/x/trainer_classification.py b/kornia/x/trainer_classification.pyindex 53a9b7c48..5279e1a10 100644--- a/kornia/x/trainer_classification.py+++ b/kornia/x/trainer_classification.py@@ -1,6 +1,7 @@import torch-from .metrics import accuracy, AverageMeter+from kornia.metrics import accuracy, AverageMeter+from .trainer import Trainerdiff --git a/test/losses/test_losses.py b/test/losses/test_losses.pyindex c9f91267e..536581a22 100644--- a/test/losses/test_losses.py+++ b/test/losses/test_losses.py@@ -610,12 +610,6 @@ class TestPSNRLoss:with pytest.raises(Exception):criterion(torch.rand(2, 3, 3, 2), torch.rand(2, 3, 3))- def test_metric(self, device, dtype):- input = torch.ones(1, device=device, dtype=dtype)- expected = torch.tensor(20.0, device=device, dtype=dtype)- actual = kornia.losses.psnr(input, 1.2 * input, 2.0)- assert_close(actual, expected)-def test_loss(self, device, dtype):input = torch.ones(1, device=device, dtype=dtype)expected = torch.tensor(-20.0, device=device, dtype=dtype)diff --git a/test/test_metrics.py b/test/test_metrics.pynew file mode 100644index 000000000..b12d2df3e--- /dev/null+++ b/test/test_metrics.py@@ -0,0 +1,183 @@+import torch++import kornia+from kornia.testing import assert_close+++class TestMeanIoU:+ def test_two_classes_perfect(self, device, dtype):+ batch_size = 1+ num_classes = 2+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long)+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long)++ mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)+ mean_iou_real = torch.tensor([[1.0, 1.0]], device=device, dtype=torch.float32)+ assert mean_iou.shape == (batch_size, num_classes)+ assert_close(mean_iou, mean_iou_real)++ def test_two_classes_perfect_batch2(self, device, dtype):+ batch_size = 2+ num_classes = 2+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long).repeat(batch_size, 1)+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long).repeat(batch_size, 1)++ mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)+ mean_iou_real = torch.tensor([[1.0, 1.0], [1.0, 1.0]], device=device, dtype=torch.float32)+ assert mean_iou.shape == (batch_size, num_classes)+ assert_close(mean_iou, mean_iou_real)++ def test_two_classes(self, device, dtype):+ batch_size = 1+ num_classes = 2+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long)+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]], device=device, dtype=torch.long)++ mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)+ mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)+ mean_iou_real = torch.tensor([[0.75, 0.80]], device=device, dtype=torch.float32)+ assert mean_iou.shape == (batch_size, num_classes)+ assert_close(mean_iou, mean_iou_real)++ def test_four_classes_2d_perfect(self, device, dtype):+ batch_size = 1+ num_classes = 4+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)++ mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)+ mean_iou_real = torch.tensor([[1.0, 1.0, 1.0, 1.0]], device=device, dtype=torch.float32)+ assert mean_iou.shape == (batch_size, num_classes)+ assert_close(mean_iou, mean_iou_real)++ def test_four_classes_one_missing(self, device, dtype):+ batch_size = 1+ num_classes = 4+ actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)++ mean_iou = kornia.metrics.mean_iou(predicted, actual, num_classes)+ mean_iou_real = torch.tensor([[0.0, 1.0, 0.5, 0.5]], device=device, dtype=torch.float32)+ assert mean_iou.shape == (batch_size, num_classes)+ assert_close(mean_iou, mean_iou_real)+++class TestConfusionMatrix:+ def test_two_classes(self, device, dtype):+ num_classes = 2+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long)+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]], device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[3, 1], [0, 4]]], device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_two_classes_batch2(self, device, dtype):+ batch_size = 2+ num_classes = 2+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]], device=device, dtype=torch.long).repeat(batch_size, 1)+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]], device=device, dtype=torch.long).repeat(batch_size, 1)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[3, 1], [0, 4]], [[3, 1], [0, 4]]], device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_three_classes(self, device, dtype):+ num_classes = 3+ actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[4, 1, 2], [3, 0, 2], [1, 2, 1]]],+ device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_four_classes_one_missing(self, device, dtype):+ num_classes = 4+ actual = torch.tensor([[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[0, 0, 0, 0], [0, 4, 1, 2], [0, 3, 0, 2], [0, 1, 2, 1]]],+ device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_three_classes_normalized(self, device, dtype):+ num_classes = 3+ normalized = True+ actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes, normalized)++ conf_mat_real = torch.tensor(+ [[[0.5000, 0.3333, 0.4000], [0.3750, 0.0000, 0.4000], [0.1250, 0.6667, 0.2000]]],+ device=device, dtype=torch.float32)++ assert_close(conf_mat, conf_mat_real)++ def test_four_classes_2d_perfect(self, device, dtype):+ num_classes = 4+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]],+ device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_four_classes_2d_one_class_nonperfect(self, device, dtype):+ num_classes = 4+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[[0, 0, 1, 1], [0, 3, 0, 1], [2, 2, 1, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[3, 0, 0, 1], [1, 3, 0, 0], [0, 0, 4, 0], [0, 1, 0, 3]]],+ device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_four_classes_2d_one_class_missing(self, device, dtype):+ num_classes = 4+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[[3, 3, 1, 1], [3, 3, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[0, 0, 0, 4], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]],+ device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)++ def test_four_classes_2d_one_class_no_predicted(self, device, dtype):+ num_classes = 4+ actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)+ predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]],+ device=device, dtype=torch.long)++ conf_mat = kornia.metrics.confusion_matrix(predicted, actual, num_classes)+ conf_mat_real = torch.tensor([[[0, 0, 4, 4], [0, 0, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]],+ device=device, dtype=torch.float32)+ assert_close(conf_mat, conf_mat_real)+++class TestPsnr:+ def test_metric(self, device, dtype):+ input = torch.ones(1, device=device, dtype=dtype)+ expected = torch.tensor(20.0, device=device, dtype=dtype)+ actual = kornia.metrics.psnr(input, 1.2 * input, 2.0)+ assert_close(actual, expected)diff --git a/test/test_x.py b/test/test_x.pyindex 87ee8f01b..a01295680 100644--- a/test/test_x.py+++ b/test/test_x.py@@ -4,8 +4,8 @@ import torch.nn as nnfrom torch.utils.data import Datasetfrom kornia.contrib import ClassificationHead, VisionTransformer+from kornia.metrics import AverageMeterfrom kornia.x import Configuration, EarlyStopping, ImageClassifierTrainer, ModelCheckpoint-from kornia.x.metrics import AverageMeterfrom kornia.x.utils import TrainerStatediff --git a/test/utils/test_metrics.py b/test/utils/test_metrics.pydeleted file mode 100644index b5cfdd9a5..000000000--- a/test/utils/test_metrics.py+++ /dev/null@@ -1,150 +0,0 @@-import torch--import kornia-from kornia.testing import assert_close---class TestMeanIoU:- def test_two_classes_perfect(self):- batch_size = 1- num_classes = 2- actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])- predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])-- mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)- mean_iou_real = torch.tensor([[1.0, 1.0]], dtype=torch.float32)- assert mean_iou.shape == (batch_size, num_classes)- assert_close(mean_iou, mean_iou_real)-- def test_two_classes_perfect_batch2(self):- batch_size = 2- num_classes = 2- actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)- predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)-- mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)- mean_iou_real = torch.tensor([[1.0, 1.0], [1.0, 1.0]], dtype=torch.float32)- assert mean_iou.shape == (batch_size, num_classes)- assert_close(mean_iou, mean_iou_real)-- def test_two_classes(self):- batch_size = 1- num_classes = 2- actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])- predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]])-- mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)- mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)- mean_iou_real = torch.tensor([[0.75, 0.80]], dtype=torch.float32)- assert mean_iou.shape == (batch_size, num_classes)- assert_close(mean_iou, mean_iou_real)-- def test_four_classes_2d_perfect(self):- batch_size = 1- num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])- predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])-- mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)- mean_iou_real = torch.tensor([[1.0, 1.0, 1.0, 1.0]], dtype=torch.float32)- assert mean_iou.shape == (batch_size, num_classes)- assert_close(mean_iou, mean_iou_real)-- def test_four_classes_one_missing(self):- batch_size = 1- num_classes = 4- actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]])- predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]])-- mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)- mean_iou_real = torch.tensor([[0.0, 1.0, 0.5, 0.5]], dtype=torch.float32)- assert mean_iou.shape == (batch_size, num_classes)- assert_close(mean_iou, mean_iou_real)---class TestConfusionMatrix:- def test_two_classes(self):- num_classes = 2- actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])- predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[3, 1], [0, 4]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_two_classes_batch2(self):- batch_size = 2- num_classes = 2- actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)- predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]]).repeat(batch_size, 1)-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[3, 1], [0, 4]], [[3, 1], [0, 4]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_three_classes(self):- num_classes = 3- actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])- predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[4, 1, 2], [3, 0, 2], [1, 2, 1]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_four_classes_one_missing(self):- num_classes = 4- actual = torch.tensor([[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]])- predicted = torch.tensor([[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[0, 0, 0, 0], [0, 4, 1, 2], [0, 3, 0, 2], [0, 1, 2, 1]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_three_classes_normalized(self):- num_classes = 3- normalized = True- actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])- predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes, normalized)-- conf_mat_real = torch.tensor(- [[[0.5000, 0.3333, 0.4000], [0.3750, 0.0000, 0.4000], [0.1250, 0.6667, 0.2000]]], dtype=torch.float32- )- assert_close(conf_mat, conf_mat_real)-- def test_four_classes_2d_perfect(self):- num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])- predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_four_classes_2d_one_class_nonperfect(self):- num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])- predicted = torch.tensor([[[0, 0, 1, 1], [0, 3, 0, 1], [2, 2, 1, 3], [2, 2, 3, 3]]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[3, 0, 0, 1], [1, 3, 0, 0], [0, 0, 4, 0], [0, 1, 0, 3]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_four_classes_2d_one_class_missing(self):- num_classes = 4- actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])- predicted = torch.tensor([[[3, 3, 1, 1], [3, 3, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[0, 0, 0, 4], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)-- def test_four_classes_2d_one_class_no_predicted(self):- num_classes = 4- actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]])- predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]])-- conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)- conf_mat_real = torch.tensor([[[0, 0, 4, 4], [0, 0, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], dtype=torch.float32)- assert_close(conf_mat, conf_mat_real)