Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

New features: Mutual information losses and normalized mutual information losses. (#3398)

Gaël Cousinfeb79cf03324
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 12cc5dd96..5bacec895 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -34,6 +34,20 @@ from .hausdorff import HausdorffERLoss, HausdorffERLoss3D
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 (
+ MILossFromRef,
+ MILossFromRef2D,
+ MILossFromRef3D,
+ NMILossFromRef,
+ NMILossFromRef2D,
+ NMILossFromRef3D,
+ mutual_information_loss,
+ mutual_information_loss_2d,
+ mutual_information_loss_3d,
+ normalized_mutual_information_loss,
+ normalized_mutual_information_loss_2d,
+ normalized_mutual_information_loss_3d,
+)
from .psnr import PSNRLoss, psnr_loss
from .ssim import SSIMLoss, ssim_loss
from .ssim3d import SSIM3DLoss, ssim3d_loss
@@ -53,7 +67,13 @@ __all__ = [
"InverseDepthSmoothnessLoss",
"LovaszHingeLoss",
"LovaszSoftmaxLoss",
+ "MILossFromRef",
+ "MILossFromRef2D",
+ "MILossFromRef3D",
"MS_SSIMLoss",
+ "NMILossFromRef",
+ "NMILossFromRef2D",
+ "NMILossFromRef3D",
"PSNRLoss",
"SSIM3DLoss",
"SSIMLoss",
@@ -71,6 +91,12 @@ __all__ = [
"kl_div_loss_2d",
"lovasz_hinge_loss",
"lovasz_softmax_loss",
+ "mutual_information_loss",
+ "mutual_information_loss_2d",
+ "mutual_information_loss_3d",
+ "normalized_mutual_information_loss",
+ "normalized_mutual_information_loss_2d",
+ "normalized_mutual_information_loss_3d",
"psnr_loss",
"ssim3d_loss",
"ssim_loss",
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
new file mode 100644
index 000000000..3b63c7ee7
--- /dev/null
+++ b/kornia/losses/mutual_information.py
@@ -0,0 +1,638 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from __future__ import annotations
+
+from enum import Enum, member
+
+import torch
+
+
+def xu_kernel(x: torch.Tensor, window_radius: float = 1.0) -> torch.Tensor:
+ """Implementation of a 2nd-order polynomial kernel for Kernel density estimate (Xu et al., 2008).
+
+ Support: [-window_radius, window_radius]. Returns 0 outside this range.
+ Ref: "Parzen-Window Based Normalized Mutual Information for Medical Image Registration", Eq. 22.
+
+ 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) / window_radius
+
+ kernel_val = torch.zeros_like(x)
+
+ mask1 = x < 0.5
+ x_mask1 = x[mask1]
+ kernel_val[mask1] = -1.8 * (x_mask1**2) - 0.1 * x_mask1 + 1.0
+ mask2 = (x >= 0.5) & (x <= 1.0)
+ x_mask2 = x[mask2]
+ kernel_val[mask2] = 1.8 * (x_mask2**2) - 3.7 * x_mask2 + 1.9
+
+ return kernel_val
+
+
+class Kernel(Enum):
+ xu = member(xu_kernel)
+
+
+def _normalize_signal(data: torch.Tensor, num_bins: int, eps: float = 1e-8) -> torch.Tensor:
+ min_val, _ = data.min(dim=-1)
+ max_val, _ = data.max(dim=-1)
+ diff = (max_val - min_val).unsqueeze(-1)
+ # signal is considered trivial if too low variation
+ return torch.where(diff > eps, (data - min_val.unsqueeze(-1)) / diff * num_bins, 0)
+
+
+def _joint_histogram_to_entropies(joint_histogram: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+ P_xy = joint_histogram
+ # clamp for numerical stability
+ P_xy = P_xy.clamp(eps)
+ # divide by sum to get a density
+ P_xy /= P_xy.sum(dim=(-1, -2), keepdim=True)
+
+ P_x = P_xy.sum(dim=-2)
+ P_y = P_xy.sum(dim=-1)
+ H_xy = torch.sum(-P_xy * torch.log(P_xy), dim=(-1, -2))
+ H_x = torch.sum(-P_x * torch.log(P_x), dim=-1)
+ H_y = torch.sum(-P_y * torch.log(P_y), dim=-1)
+
+ return H_x, H_y, H_xy
+
+
+class EntropyBasedLossBase(torch.nn.Module):
+ """A base class for entropy-based loss functions using kernel density estimation.
+
+ This class provides the foundation for computing entropy-based losses between signals
+ by estimating probability distributions using kernel density estimation (KDE). It
+ computes joint histograms and derives entropy measures that can be used to quantify
+ the similarity or dissimilarity between signals.
+
+ The class pre-processes a reference signal and provides methods to compute joint
+ histograms with other signals, from which various entropy measures (joint, marginal,
+ conditional, mutual information) can be derived in subclasses.
+ """
+
+ def __init__(
+ self,
+ reference_signal: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+ ) -> None:
+ """Initialize the entropy-based loss base 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
+ 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.
+ """
+ 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:
+ raise ValueError(
+ f"The passed_kernel_function is not an accepted Kernel, the available options are {list(Kernel)}."
+ )
+ self.kernel_function = kernel_function.value
+ self.window_radius = window_radius
+ self.bin_centers = torch.arange(self.num_bins, device=self.signal.device)
+
+ def _compute_joint_histogram(self, other_signal: torch.Tensor, eps: float) -> torch.Tensor:
+ """Compute the joint histogram between the reference signal and another signal.
+
+ Uses kernel density estimation to estimate the joint probability distribution
+ between the reference signal and the provided other signal. The histogram is
+ computed by evaluating kernel functions at discretized signal values.
+
+ Args:
+ other_signal (torch.Tensor): Signal to compare with the reference signal.
+ Must have the same shape as the reference signal.
+ eps (float): Epsilon value for numerical stability in computations.
+
+ Returns:
+ torch.Tensor: Joint histogram tensor with shape [..., num_bins, num_bins]
+ representing the estimated joint probability distribution.
+
+ Raises:
+ ValueError: If other_signal has incompatible shape with reference signal.
+ """
+ if other_signal.shape != self.signal.shape:
+ raise ValueError(f"The two signals have incompatible shapes: {other_signal.shape} and {self.signal.shape}.")
+ other_signal = _normalize_signal(other_signal, num_bins=self.num_bins, eps=eps)
+
+ diff_1 = self.bin_centers.unsqueeze(-1) - self.signal.unsqueeze(-2)
+ diff_2 = self.bin_centers.unsqueeze(-1) - other_signal.unsqueeze(-2)
+
+ vals_1 = self.kernel_function(diff_1, window_radius=self.window_radius)
+ vals_2 = self.kernel_function(diff_2, window_radius=self.window_radius)
+
+ joint_histogram = torch.einsum("...in,...jn->...ij", vals_1, vals_2)
+
+ return joint_histogram
+
+ def entropies(self, other_signal: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Compute entropy measures between the reference signal and another signal.
+
+ Calculates joint entropy and marginal entropies based on the joint histogram of the two signals.
+
+ Args:
+ other_signal (torch.Tensor): Signal to compare with the reference signal.
+ Must have the same shape as the reference_signal passed at instantiation.
+
+ Returns:
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor]: A tuple containing:
+ - Marginal entropy H(X) of reference signal
+ - Marginal entropy H(Y) of other signal
+ - Joint entropy H(X,Y)
+
+ All tensors have the same batch dimensions as the input signals.
+
+ Note:
+ Subclasses should implement specific loss functions based on these entropy
+ measures (e.g., mutual information).
+ """
+ joint_histogram = self._compute_joint_histogram(other_signal, self.eps)
+ return _joint_histogram_to_entropies(joint_histogram, eps=self.eps)
+
+
+class MILossFromRef(EntropyBasedLossBase):
+ def forward(self, other_signal: torch.Tensor) -> torch.Tensor:
+ """Compute differentiable mutual information for self.signal and other_signal.
+
+ mi = (H(X) + H(Y) - H(X,Y))
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ other_signal: Batch of flat tensors shape (B,N) where B is
+ the tuple of batch dimensions for self.signal, possibly empty.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B as above
+ """
+ H_x, H_y, H_xy = self.entropies(other_signal)
+ mi = H_x + H_y - H_xy
+
+ return -mi
+
+
+class NMILossFromRef(EntropyBasedLossBase):
+ def forward(self, other_signal: torch.Tensor) -> torch.Tensor:
+ """Compute differentiable normalized mutual information for self.signal and other_signal.
+
+ nmi = (H(X) + H(Y)) / H(X,Y)
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ other_signal: Batch of flat tensors shape (B,N) where B is
+ the tuple of batch dimensions for self.signal, possibly empty.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B as above
+ """
+ H_x, H_y, H_xy = self.entropies(other_signal)
+ nmi = (H_x + H_y) / H_xy
+
+ return -nmi
+
+
+class MILossFromRef2D(MILossFromRef):
+ """Mutual Information loss module specifically designed for 2D image data.
+
+ This class extends MILossFromRef to handle 2D image inputs by automatically
+ reshaping batched 2D images into the format expected by the base entropy
+ computation methods. It computes mutual information between reference 2D images
+ and other images using kernel density estimation.
+ """
+
+ def __init__(
+ self,
+ reference_signal: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1,
+ ) -> None:
+ """Initialize the 2D Mutual Information loss module.
+
+ Args:
+ reference_signal (torch.Tensor): reference signal to which
+ 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
+ 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
+ """
+ super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)
+
+ @staticmethod
+ def arrange_shape(tensor: torch.Tensor) -> torch.Tensor:
+ return tensor.reshape(tensor.shape[:-2] + (-1,))
+
+ def forward(self, other_signal: torch.Tensor) -> torch.Tensor:
+ """Compute differentiable mutual information for reference_signal and other_signal (both supposed 2D).
+
+ mi = (H(X) + H(Y) - H(X,Y))
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ other_signal: Batch of flat tensors same shape (B,H,W) as
+ reference_signal passed for instantiation
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B as above
+ """
+ return super().forward(self.arrange_shape(other_signal))
+
+
+class MILossFromRef3D(MILossFromRef):
+ """Mutual Information loss module specifically designed for 3D image data.
+
+ This class extends MILossFromRef to handle 3D image inputs by automatically
+ reshaping batched 3D images into the format expected by the base entropy
+ computation methods. It computes normalized mutual information between reference 3D images
+ and other images using kernel density estimation.
+ """
+
+ def __init__(
+ self,
+ reference_signal: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1,
+ ) -> None:
+ """Initialize the 3D Mutual Information loss module.
+
+ Args:
+ reference_signal (torch.Tensor): reference signal to which
+ 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
+ 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
+ """
+ super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)
+
+ @staticmethod
+ def arrange_shape(tensor: torch.Tensor) -> torch.Tensor:
+ return tensor.reshape(tensor.shape[:-3] + (-1,))
+
+ def forward(self, other_signal: torch.Tensor) -> torch.Tensor:
+ """Compute differentiable mutual information for reference_signal and other_signal (both supposed 3D).
+
+ mi = (H(X) + H(Y) - H(X,Y))
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ other_signal: Batch of flat tensors same shape (B,D,H,W) as
+ reference_signal passed for instantiation
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B as above
+ """
+ return super().forward(self.arrange_shape(other_signal))
+
+
+class NMILossFromRef2D(NMILossFromRef):
+ """Normalized Mutual Information loss module specifically designed for 2D image data.
+
+ This class extends NMILossFromRef to handle 2D image inputs by automatically
+ reshaping batched 2D images into the format expected by the base entropy
+ computation methods. It computes normalized mutual information between reference 2D images
+ and other images using kernel density estimation.
+ """
+
+ def __init__(
+ self,
+ reference_signal: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1,
+ ) -> None:
+ """Initialize the 2D Normalized Mutual Information loss module.
+
+ Args:
+ reference_signal (torch.Tensor): reference signal to which
+ 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
+ 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
+ """
+ super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)
+
+ @staticmethod
+ def arrange_shape(tensor: torch.Tensor) -> torch.Tensor:
+ return tensor.reshape(tensor.shape[:-2] + (-1,))
+
+ def forward(self, other_signal: torch.Tensor) -> torch.Tensor:
+ """Compute differentiable mutual information for reference_signal and other_signal (both supposed 2D).
+
+ nmi = (H(X) + H(Y)) / H(X,Y)
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of tensors, then a batch of loss values is returned.
+
+ Args:
+ other_signal: Batch of tensors same shape (B,H,W) as
+ reference_signal passed for instantiation
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B as above
+ """
+ return super().forward(self.arrange_shape(other_signal))
+
+
+class NMILossFromRef3D(NMILossFromRef):
+ """Normalized Mutual Information loss module specifically designed for 3D image data.
+
+ This class extends NMILossFromRef to handle 3D image inputs by automatically
+ reshaping batched 3D images into the format expected by the base entropy
+ computation methods. It computes mutual information between reference 3D images
+ and other images using kernel density estimation.
+ """
+
+ def __init__(
+ self,
+ reference_signal: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1,
+ ) -> None:
+ """Initialize the 3D Normalized Mutual Information loss module.
+
+ Args:
+ reference_signal (torch.Tensor): reference signal to which
+ 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
+ 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
+ """
+ super().__init__(self.arrange_shape(reference_signal), kernel_function, num_bins, window_radius)
+
+ @staticmethod
+ def arrange_shape(tensor: torch.Tensor) -> torch.Tensor:
+ return tensor.reshape(tensor.shape[:-3] + (-1,))
+
+ def forward(self, other_signal: torch.Tensor) -> torch.Tensor:
+ """Compute differentiable mutual information for reference_signal and other_signal (both supposed 3D).
+
+ nmi = (H(X) + H(Y)) / H(X,Y)
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ other_signal: Batch of tensors, same shape (B,D,H,W) as
+ reference_signal passed for instantiation
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B as above
+ """
+ return super().forward(self.arrange_shape(other_signal))
+
+
+def mutual_information_loss(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+) -> torch.Tensor:
+ """Compute differentiable mutual information for flat tensors.
+
+ mi = (H(X) + H(Y) - H(X,Y))
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ input (torch.Tensor): Batch of flat tensors shape (B,N) where B
+ 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
+ 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.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B (common batch dims tuple
+ of input and target)
+ """
+ module = MILossFromRef(
+ reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius
+ )
+ return module.forward(input)
+
+
+def mutual_information_loss_2d(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+) -> torch.Tensor:
+ """Compute differentiable mutual information for 2d tensors.
+
+ nmi = (H(X) + H(Y)) / H(X,Y)
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of 2d tensors, then a batch of loss values is returned.
+
+ Args:
+ 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
+ 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.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B (common batch dims tuple
+ of input and target)
+ """
+ module = MILossFromRef2D(
+ reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius
+ )
+ return module.forward(input)
+
+
+def mutual_information_loss_3d(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+) -> torch.Tensor:
+ """Compute differentiable mutual information for 3d tensors.
+
+ nmi = (H(X) + H(Y)) / H(X,Y)
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of 3d tensors, then a batch of loss values is returned.
+
+ Args:
+ 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
+ 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.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B (common batch dims tuple
+ of input and target)
+ """
+ module = MILossFromRef3D(
+ reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius
+ )
+ return module.forward(input)
+
+
+def normalized_mutual_information_loss(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+) -> torch.Tensor:
+ """Compute differentiable normalized mutual information for flat tensors.
+
+ nmi = (H(X) + H(Y)) / H(X,Y)
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of flat tensors, then a batch of loss values is returned.
+
+ Args:
+ input (torch.Tensor): Batch of flat tensors shape (B,N) where B
+ 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
+ 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.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B (common batch dims tuple
+ of input and target)
+ """
+ module = NMILossFromRef(
+ reference_signal=target,
+ kernel_function=kernel_function,
+ num_bins=num_bins,
+ window_radius=window_radius,
+ )
+ return module.forward(input)
+
+
+def normalized_mutual_information_loss_2d(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+) -> torch.Tensor:
+ """Compute differentiable normalized mutual information for 2d tensors.
+
+ mi = (H(X) + H(Y) - H(X,Y))
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of 2d tensors, then a batch of loss values is returned.
+
+ Args:
+ 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
+ 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.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B (common batch dims tuple
+ of input and target)
+ """
+ module = NMILossFromRef2D(
+ reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius
+ )
+ return module.forward(input)
+
+
+def normalized_mutual_information_loss_3d(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ kernel_function: Kernel = Kernel.xu,
+ num_bins: int = 64,
+ window_radius: float = 1.0,
+) -> torch.Tensor:
+ """Compute differentiable normalized mutual information for 3d tensors.
+
+ mi = (H(X) + H(Y) - H(X,Y))
+ To have a loss function, the opposite is returned.
+ Can also handle two batches of 3d tensors, then a batch of loss values is returned.
+
+ Args:
+ 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
+ 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.
+
+ Returns:
+ torch.Tensor: tensor of losses, shape B (common batch dims tuple
+ of input and target)
+ """
+ module = NMILossFromRef3D(
+ reference_signal=target, kernel_function=kernel_function, num_bins=num_bins, window_radius=window_radius
+ )
+ return module.forward(input)
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
new file mode 100644
index 000000000..2440b7063
--- /dev/null
+++ b/tests/losses/test_mutual_information.py
@@ -0,0 +1,210 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import pytest
+import torch
+
+from kornia.losses.mutual_information import (
+ MILossFromRef,
+ NMILossFromRef,
+ mutual_information_loss,
+ normalized_mutual_information_loss,
+)
+
+from testing.base import BaseTester
+
+
+class TestMutualInformationLoss(BaseTester):
+ @staticmethod
+ def relative_mi(img_1, img_2, window_radius):
+ """Should theoretically be 0 if img_1 and img_2 are independent and 1 if img_1 = f(img_2), f one to one."""
+ numerator = mutual_information_loss(img_1, img_2, window_radius=window_radius)
+ denominator = mutual_information_loss(img_2, img_2, window_radius=window_radius)
+ return numerator / denominator
+
+ @staticmethod
+ def sampling_function(n_samples, device, dtype):
+ data = torch.rand(n_samples, device=device, dtype=dtype)
+ return 400 * torch.sin(data * torch.pi)
+
+ def value_ranges_check(self, device, dtype, n_samples=10000, num_bins=64):
+ img_1 = self.sampling_function(n_samples, device, dtype)
+ img_2 = 50 * img_1 + 1
+ img_3 = self.sampling_function(n_samples, device, dtype)
+
+ for radius in [1 / 2, 1, 2, 3]:
+ # relative MI, expect 1
+ assert torch.allclose(self.relative_mi(img_1, img_2, window_radius=radius), torch.ones(1).to(dtype)), (
+ "Wrong MI behaviour, correlated case."
+ )
+ # relative MI, expect 0
+ # NOTE: mutual_information_loss is a finite-sample, histogram-based estimator applied to random data.
+ # For independent variables the theoretical value is 0, but sampling noise and binning effects across
+ # radii introduce noticeable variance, so we use a slightly looser atol here for test robustness.
+ assert torch.allclose(
+ self.relative_mi(img_1, img_3, window_radius=radius), torch.zeros(1).to(dtype), atol=0.2
+ ), "Wrong MI behaviour, uncorrelated case."
+
+ assert torch.allclose(
+ self.relative_mi(img_2, img_3, window_radius=radius), torch.zeros(1).to(dtype), atol=0.2
+ ), "Wrong MI behaviour, uncorrelated case."
+
+ # NMI, expect -2
+ assert torch.allclose(
+ normalized_mutual_information_loss(img_1, img_2, window_radius=radius, num_bins=num_bins),
+ -2 * torch.ones(1).to(dtype),
+ atol=0.2 * radius + 0.15,
+ ), "Wrong NMI behaviour, correlated case."
+
+ # NMI, expect -1
+ assert torch.allclose(
+ normalized_mutual_information_loss(img_1, img_3, window_radius=radius, num_bins=num_bins),
+ -torch.ones(1).to(dtype),
+ atol=0.1,
+ ), "Wrong NMI behaviour, uncorrelated case."
+ assert torch.allclose(
+ normalized_mutual_information_loss(img_2, img_3, window_radius=radius, num_bins=num_bins),
+ -torch.ones(1).to(dtype),
+ atol=0.1,
+ ), "Wrong NMI behaviour, uncorrelated case."
+
+ def test_smoke(self, device, dtype):
+ """Basic functionality test"""
+ img1 = torch.rand(100, device=device, dtype=dtype)
+ img2 = torch.rand(100, device=device, dtype=dtype)
+
+ loss = mutual_information_loss(img1, img2, num_bins=64)
+ assert isinstance(loss, torch.Tensor)
+ assert loss.shape == torch.Size([])
+
+ normalized_loss = normalized_mutual_information_loss(img1, img2, num_bins=64)
+ assert isinstance(normalized_loss, torch.Tensor)
+ assert normalized_loss.shape == torch.Size([])
+
+ def test_exception(self, device, dtype):
+ """Test error conditions"""
+ # Test with mismatched shapes
+ img1 = torch.rand(10, device=device, dtype=dtype)
+ img2 = torch.rand(20, device=device, dtype=dtype)
+
+ with pytest.raises(Exception):
+ mutual_information_loss(img1, img2)
+
+ with pytest.raises(Exception):
+ normalized_mutual_information_loss(img1, img2)
+
+ def test_gradcheck(self, device):
+ """Gradient checking"""
+ img1 = torch.rand(50, device=device, dtype=torch.float64, requires_grad=True)
+ img2 = torch.rand(50, device=device, dtype=torch.float64)
+
+ self.gradcheck(mutual_information_loss, (img1, img2))
+ self.gradcheck(normalized_mutual_information_loss, (img1, img2))
+
+ def test_differentiability(self, device, dtype):
+ for _ in range(10):
+ img_1 = self.sampling_function(10000, device, dtype)
+ img_2 = self.sampling_function(10000, device, dtype)
+ param = torch.tensor(1 / 2.0, requires_grad=True)
+ mi = mutual_information_loss(img_1 + param * img_2, img_2)
+ mi.backward()
+ # negative gradient, order of magnitude 1/2
+ assert -1 < param.grad < -1 / 10, f"Differentiability issue for mi, {param.grad=}."
+ param = torch.tensor(1 / 2.0, requires_grad=True)
+ nmi = normalized_mutual_information_loss(img_1 + param * img_2, img_2)
+ nmi.backward()
+ # negative gradient, order of magnitude 1/20
+ assert -1 / 10 < param.grad < -1 / 100, f"Differentiability issue for nmi, {param.grad=}."
+
+ def test_value_ranges(self, device, dtype):
+ for _ in range(10):
+ self.value_ranges_check(device, dtype)
+
+ def test_batch_consistency(self, device, dtype):
+ 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}"
+ )
+ 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)
+ target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+
+ args = (pred, target)
+
+ op = normalized_mutual_information_loss
+ op_module = NMILossFromRef(target)
+
+ self.assert_close(op(*args), op_module(pred))
+
+ op = mutual_information_loss
+ op_module = MILossFromRef(target)
+
+ self.assert_close(op(*args), op_module(pred))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+ target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
+
+ args = (pred, target)
+
+ op = mutual_information_loss
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(*args), op_optimized(*args))
+
+ op = normalized_mutual_information_loss
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(*args), op_optimized(*args))