Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: add rectangular and gaussian kernels for mutual information loss (#3478)

Pawan Parida8856d821bcea
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 5bacec895..310b30fc8 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -35,6 +35,7 @@ from .lovasz_hinge import LovaszHingeLoss, lovasz_hinge_loss
from .lovasz_softmax import LovaszSoftmaxLoss, lovasz_softmax_loss
from .ms_ssim import MS_SSIMLoss
from .mutual_information import (
+ MIKernel,
MILossFromRef,
MILossFromRef2D,
MILossFromRef3D,
@@ -67,6 +68,7 @@ __all__ = [
"InverseDepthSmoothnessLoss",
"LovaszHingeLoss",
"LovaszSoftmaxLoss",
+ "MIKernel",
"MILossFromRef",
"MILossFromRef2D",
"MILossFromRef3D",
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index 6e0000665..994d59147 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -49,8 +49,47 @@ def xu_kernel(x: torch.Tensor, window_radius: float = 1.0) -> torch.Tensor:
return kernel_val
-class Kernel(Enum):
+def rectangular_kernel(x: torch.Tensor, window_radius: float = 1.0) -> torch.Tensor:
+ """Implementation of a rectangular kernel.
+
+ Support: [-window_radius, window_radius]. Returns 1.0 inside this range, 0.0 otherwise.
+
+ Args:
+ x (torch.Tensor): signal, any shape
+ window_radius (float): radius of window for the kernel
+
+ Returns:
+ torch.Tensor: transformed signal
+ """
+ x = torch.abs(x)
+ return torch.where(x <= window_radius, 1.0, 0.0)
+
+
+def truncated_gaussian_kernel(x: torch.Tensor, window_radius: float = 1.0) -> torch.Tensor:
+ """Implementation of a truncated Gaussian kernel.
+
+ Support: [-window_radius, window_radius]. Returns Gaussian value inside this range, 0.0 otherwise.
+ Sigma is set to window_radius.
+
+ Args:
+ x (torch.Tensor): signal, any shape
+ window_radius (float): radius of window for the kernel (used as sigma)
+
+ Returns:
+ torch.Tensor: transformed signal
+ """
+ sigma = window_radius
+ mask = torch.abs(x) <= window_radius
+
+ gaussian_val = torch.exp(-0.5 * (x / sigma) ** 2) / (sigma * (2 * torch.pi) ** 0.5)
+
+ return torch.where(mask, gaussian_val, 0.0)
+
+
+class MIKernel(Enum):
xu = member(xu_kernel)
+ rectangular = member(rectangular_kernel)
+ truncated_gaussian = member(truncated_gaussian_kernel)
def _normalize_signal(data: torch.Tensor, num_bins: int, eps: float = 1e-8) -> torch.Tensor:
@@ -93,7 +132,7 @@ class EntropyBasedLossBase(torch.nn.Module):
def __init__(
self,
reference_signal: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> None:
@@ -102,23 +141,23 @@ class EntropyBasedLossBase(torch.nn.Module):
Args:
reference_signal (torch.Tensor): reference signal to which
other signals will be compared by the forward method
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): number of signal value bins in kernel
density estimate, by default 64
window_radius (float): radius of the kernel's support
interval, by default 1.0
Raises:
- ValueError: If kernel_function is not a valid Kernel member.
+ ValueError: If kernel_function is not a valid MIKernel member.
"""
super().__init__()
self.eps = torch.finfo(reference_signal.dtype).eps
self.register_buffer("signal", _normalize_signal(reference_signal, num_bins, self.eps))
self.num_bins = num_bins
- if kernel_function not in Kernel:
+ if kernel_function not in MIKernel:
raise ValueError(
- f"The passed_kernel_function is not an accepted Kernel, the available options are {list(Kernel)}."
+ f"The passed_kernel_function is not an accepted MIKernel, the available options are {list(MIKernel)}."
)
self.kernel_function = partial(kernel_function.value, window_radius=window_radius)
self.window_radius = window_radius
@@ -236,7 +275,7 @@ class MILossFromRef2D(MILossFromRef):
def __init__(
self,
reference_signal: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1,
) -> None:
@@ -247,8 +286,8 @@ class MILossFromRef2D(MILossFromRef):
other signals will be compared by the forward method.
batch of 2D images, shape (B,H,W) where B are the batch
dimensions.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): number of signal value bins in kernel
density estimate, by default 64
window_radius (float): radius of the kernel's support
@@ -289,7 +328,7 @@ class MILossFromRef3D(MILossFromRef):
def __init__(
self,
reference_signal: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1,
) -> None:
@@ -300,8 +339,8 @@ class MILossFromRef3D(MILossFromRef):
other signals will be compared by the forward method.
batch of 3D images, shape (B,D,H,W) where B are the
batch dimensions.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): number of signal value bins in kernel
density estimate, by default 64
window_radius (float): radius of the kernel's support
@@ -342,7 +381,7 @@ class NMILossFromRef2D(NMILossFromRef):
def __init__(
self,
reference_signal: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1,
) -> None:
@@ -353,8 +392,8 @@ class NMILossFromRef2D(NMILossFromRef):
other signals will be compared by the forward method.
batch of 2D images, shape (B,H,W) where B are the batch
dimensions.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): number of signal value bins in kernel
density estimate, by default 64
window_radius (float): radius of the kernel's support
@@ -395,7 +434,7 @@ class NMILossFromRef3D(NMILossFromRef):
def __init__(
self,
reference_signal: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1,
) -> None:
@@ -406,8 +445,8 @@ class NMILossFromRef3D(NMILossFromRef):
other signals will be compared by the forward method.
batch of 3D images, shape (B,D,H,W) where B are the
batch dimensions.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): number of signal value bins in kernel
density estimate, by default 64
window_radius (float): radius of the kernel's support
@@ -439,7 +478,7 @@ class NMILossFromRef3D(NMILossFromRef):
def mutual_information_loss(
input: torch.Tensor,
target: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> torch.Tensor:
@@ -454,8 +493,8 @@ def mutual_information_loss(
is any batch dimensions tuple, possibly empty.
target (torch.Tensor): Batch of flat tensors, same shape as
input.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): The number of bins used for KDE, defaults to 64.
window_radius (float): The smoothing window radius in KDE, in
terms of bin width units, defaults to 1.
@@ -473,7 +512,7 @@ def mutual_information_loss(
def mutual_information_loss_2d(
input: torch.Tensor,
target: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> torch.Tensor:
@@ -487,8 +526,8 @@ def mutual_information_loss_2d(
input (torch.Tensor): Batch of 2d tensors shape (B,H,W) where B
is any batch dimensions tuple, possibly empty.
target (torch.Tensor): Batch of 2d tensors, same shape as input.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): The number of bins used for KDE, defaults to 64.
window_radius (float): The smoothing window radius in KDE, in
terms of bin width units, defaults to 1.
@@ -506,7 +545,7 @@ def mutual_information_loss_2d(
def mutual_information_loss_3d(
input: torch.Tensor,
target: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> torch.Tensor:
@@ -520,8 +559,8 @@ def mutual_information_loss_3d(
input (torch.Tensor): Batch of 3d tensors shape (B,D,H,W) where
B is any batch dimensions tuple, possibly empty.
target (torch.Tensor): Batch of 3d tensors, same shape as input.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): The number of bins used for KDE, defaults to 64.
window_radius (float): The smoothing window radius in KDE, in
terms of bin width units, defaults to 1.
@@ -539,7 +578,7 @@ def mutual_information_loss_3d(
def normalized_mutual_information_loss(
input: torch.Tensor,
target: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> torch.Tensor:
@@ -554,8 +593,8 @@ def normalized_mutual_information_loss(
is any batch dimensions tuple, possibly empty.
target (torch.Tensor): Batch of flat tensors, same shape as
input.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): The number of bins used for KDE, defaults to 64.
window_radius (float): The smoothing window radius in KDE, in
terms of bin width units, defaults to 1.
@@ -576,7 +615,7 @@ def normalized_mutual_information_loss(
def normalized_mutual_information_loss_2d(
input: torch.Tensor,
target: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> torch.Tensor:
@@ -590,8 +629,8 @@ def normalized_mutual_information_loss_2d(
input (torch.Tensor): Batch of 2d tensors shape (B,H,W) where B
is any batch dimensions tuple, possibly empty.
target (torch.Tensor): Batch of 2d tensors, same shape as input.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): The number of bins used for KDE, defaults to 64.
window_radius (float): The smoothing window radius in KDE, in
terms of bin width units, defaults to 1.
@@ -609,7 +648,7 @@ def normalized_mutual_information_loss_2d(
def normalized_mutual_information_loss_3d(
input: torch.Tensor,
target: torch.Tensor,
- kernel_function: Kernel = Kernel.xu,
+ kernel_function: MIKernel = MIKernel.xu,
num_bins: int = 64,
window_radius: float = 1.0,
) -> torch.Tensor:
@@ -623,8 +662,8 @@ def normalized_mutual_information_loss_3d(
input (torch.Tensor): Batch of 3d tensors shape (B,D,H,W) where
B is any batch dimensions tuple, possibly empty.
target (torch.Tensor): Batch of 3d tensors, same shape as input.
- kernel_function (Kernel): Used kernel function for kernel
- density estimate, by default Kernel.xu
+ kernel_function (MIKernel): Used kernel function for kernel
+ density estimate, by default MIKernel.xu
num_bins (int): The number of bins used for KDE, defaults to 64.
window_radius (float): The smoothing window radius in KDE, in
terms of bin width units, defaults to 1.
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index 2440b7063..5a07fa6bd 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -18,6 +18,7 @@ import pytest
import torch
from kornia.losses.mutual_information import (
+ MIKernel,
MILossFromRef,
NMILossFromRef,
mutual_information_loss,
@@ -133,49 +134,53 @@ class TestMutualInformationLoss(BaseTester):
for _ in range(10):
self.value_ranges_check(device, dtype)
- def test_batch_consistency(self, device, dtype):
+ @pytest.mark.parametrize("kernel", [MIKernel.xu, MIKernel.rectangular, MIKernel.truncated_gaussian])
+ @pytest.mark.parametrize("dim_param", range(5))
+ def test_batch_consistency(self, device, dtype, kernel, dim_param):
torch.manual_seed(0) # Fix seed for reproducibility
- for dim_param in range(5):
- # 1. Create random batch with n_dims = i+1
- dims = torch.randint(low=1, high=8, size=(dim_param + 1,))
- dims = tuple(map(int, dims))
- for _ in range(10):
- img1 = torch.rand(dims, device=device, dtype=dtype)
- img2 = torch.rand(dims, device=device, dtype=dtype)
-
- # flatten batch dims
- unique_batch_dim_1 = img1.reshape((-1,) + img1.shape[-1:])
- unique_batch_dim_2 = img2.reshape((-1,) + img1.shape[-1:])
-
- # 2. Compute Batch Loss (The "Vectorized" way)
- # This will likely return a scalar computed on the flattened batch (Incorrect behavior)
- loss_batch = mutual_information_loss(img1, img2, num_bins=64)
- normalized_loss_batch = normalized_mutual_information_loss(img1, img2, num_bins=64)
-
- # 3. Compute Iterative Loss (The "Slow but Correct" way)
- losses = []
- normalized_losses = []
- for i in range(unique_batch_dim_1.shape[0]):
- loss = mutual_information_loss(unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64)
- normalized_loss = normalized_mutual_information_loss(
- unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64
- )
- losses.append(loss)
- normalized_losses.append(normalized_loss)
-
- loss_iterative = torch.stack(losses)
- normalized_loss_iterative = torch.stack(normalized_losses)
-
- # 4. Compare
- assert loss_batch.shape == dims[:-1], "The shape of the batched losses for mi is wrong."
- assert normalized_loss_batch.shape == dims[:-1], "The shape of the batched losses for nmi is wrong."
-
- assert torch.allclose(loss_batch.flatten(), loss_iterative, atol=1e-4), (
- f"Batch mismatch for mi! Batch: {loss_batch}, Iterative: {loss_iterative}"
+
+ # Create random dimensions
+ dims = torch.randint(low=1, high=8, size=(dim_param + 1,))
+ dims = tuple(map(int, dims))
+
+ for _ in range(3):
+ img1 = torch.rand(dims, device=device, dtype=dtype)
+ img2 = torch.rand(dims, device=device, dtype=dtype)
+
+ # flatten batch dims
+ unique_batch_dim_1 = img1.reshape((-1,) + img1.shape[-1:])
+ unique_batch_dim_2 = img2.reshape((-1,) + img1.shape[-1:])
+
+ # Compute batch loss
+ loss_batch = mutual_information_loss(img1, img2, num_bins=64, kernel_function=kernel)
+ normalized_loss_batch = normalized_mutual_information_loss(img1, img2, num_bins=64, kernel_function=kernel)
+
+ # Compute iterative loss for verification
+ losses = []
+ normalized_losses = []
+ for i in range(unique_batch_dim_1.shape[0]):
+ loss = mutual_information_loss(
+ unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64, kernel_function=kernel
)
- assert torch.allclose(normalized_loss_batch.flatten(), normalized_loss_iterative, atol=1e-4), (
- f"Batch mismatch for nmi! Batch: {normalized_loss_batch}, Iterative: {normalized_loss_iterative}"
+ normalized_loss = normalized_mutual_information_loss(
+ unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64, kernel_function=kernel
)
+ losses.append(loss)
+ normalized_losses.append(normalized_loss)
+
+ loss_iterative = torch.stack(losses)
+ normalized_loss_iterative = torch.stack(normalized_losses)
+
+ # Compare
+ assert loss_batch.shape == dims[:-1], "The shape of the batched losses for mi is wrong."
+ assert normalized_loss_batch.shape == dims[:-1], "The shape of the batched losses for nmi is wrong."
+
+ assert torch.allclose(loss_batch.flatten(), loss_iterative, atol=1e-4), (
+ f"Batch mismatch for mi! Batch: {loss_batch}, Iterative: {loss_iterative}"
+ )
+ assert torch.allclose(normalized_loss_batch.flatten(), normalized_loss_iterative, atol=1e-4), (
+ f"Batch mismatch for nmi! Batch: {normalized_loss_batch}, Iterative: {normalized_loss_iterative}"
+ )
def test_module(self, device, dtype):
pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)