Registration#
Similarity losses for image registration: the negative mutual information and the negative normalized mutual
information of two signals, estimated from a kernel (Parzen-window) joint histogram. The functions take flat signals,
2D images or 3D volumes; each module stores the target once and compares other signals with it. The Convention block
of mutual_information_loss() states the rules that all of them share.
Porting from scikit-learn and scikit-image#
The losses use the natural logarithm, as scikit-learn’s mutual_info_score does.
normalized_mutual_information_loss() negates Studholme’s \(\mathrm{NMI} = (H(X) + H(Y)) / H(X, Y)\), which
is scikit-image’s normalized_mutual_information. scikit-learn’s normalized_mutual_info_score divides the mutual
information by the arithmetic mean of the two entropies, its default, and equals \(2 - 2 / \mathrm{NMI}\)
for the same joint histogram with nonzero joint entropy. If both signals are constant, scikit-image returns NaN
(\(0 / 0\)) and scikit-learn returns 1.0, while kornia gives a finite value below -1 that changes with the
dtype, num_bins and the number of samples.
Both libraries count a hard histogram. scikit-image’s bins defaults to 100, kornia’s num_bins to 64. With the
default kernel and window_radius, kornia’s histogram is a hard one when every value sits on a bin centre, as on
integer images whose values span 0, ..., K (both ends present) with num_bins=K + 1.
Functions#
- kornia.losses.mutual_information_loss(input, target, input_mask=None, target_mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the mutual-information loss of two flat signals
(*, N).loss = mutual_information_loss(input, target)returns the negative mutual information ofinputandtargetfrom their kernel (Parzen-window) joint histogram, one value per leading index.\[\text{loss} = -(H(X) + H(Y) - H(X, Y))\]- Convention:
The loss is in nats: minimising it maximises the mutual information. It is symmetric in
inputandtarget. Registration maps the losses onto scikit-learn and scikit-image.inputandtargetare(*, N)tensors of one shape and one floating dtype; a singletargetis not broadcast over a batch of inputs. There is noreduction(Losses and metrics lists the defaults of the other losses).Each signal is min-max normalised per sample, over its mask, so no data range is assumed. A positive rescaling and a shift of one sample leave its loss unchanged up to roundoff when both its original and transformed ranges exceed the absolute threshold
torch.finfo(dtype).eps. One outlier squeezes the other values of its sample into a few bins. A sample whose range is at most that threshold counts as constant: its MI is 0 and it gets a zero gradient.The joint histogram has
num_binsbins per signal, and each value spreads over the bins withinwindow_radiusbin widths of it, weighted bykernel_function, aMIKernelmember. With continuous values and the defaultwindow_radius, this soft histogram scores an image against itself below its entropy. Values compare only at equalnum_bins,window_radiusand kernel.With
MIKernel.xu(the default) andMIKernel.truncated_gaussian,inputandtargetboth get gradients.MIKernel.rectangularis piecewise constant: its loss has no gradient and serves for evaluation only.input_maskandtarget_maskare boolean(N,)masks, common to the batch. The histogram counts the positions inside both masks, while each signal is normalised over its own mask: a value inside one mask only is not counted, but it changes the loss when it is that signal’s minimum or maximum. Values outside both masks have no effect. Masks of another shape, or with no position in common, raise an error.For float16 and bfloat16 inputs, min-max normalisation, kernel evaluation, histogram accumulation and entropy arithmetic use float32, including under autocast, and the final loss is cast back to the input dtype. The empty-bin floor uses the histogram’s computation dtype rather than the input dtype. The constant-signal threshold remains
torch.finfo(input dtype).eps.
- Parameters:
input (
Tensor) – flat signals(*, N).target (
Tensor) – flat signals with the shape ofinput.input_mask (
Tensor|None, optional) – boolean region of interest(N,)ofinput, common to the batch;Nonekeeps every position. Default:Nonetarget_mask (
Tensor|None, optional) – boolean region of interest(N,)oftarget, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Return type:
- Returns:
the loss per leading index, with shape
*, in the input dtype.
See also
MILossFromRef: the module form, built on the target.normalized_mutual_information_loss(): Studholme’s normalization, in[-2, -1].mutual_information_loss_2d(): the same loss for images(*, H, W).mutual_information_loss_3d(): the same loss for volumes(*, D, H, W).
Example
>>> input = torch.rand(2, 3, 64) >>> target = torch.rand(2, 3, 64) >>> loss = mutual_information_loss(input, target)
- kornia.losses.mutual_information_loss_2d(input, target, input_mask=None, target_mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the mutual-information loss of two images
(*, H, W).loss = mutual_information_loss_2d(input, target)returns the negative mutual information ofinputandtargetfrom their kernel (Parzen-window) joint histogram, one value per image.\[\text{loss} = -(H(X) + H(Y) - H(X, Y))\]- Convention:
See the Convention block of
mutual_information_loss(); this function applies it toinput.flatten(-2)andtarget.flatten(-2). Every axis before the last two is a batch axis, so a(B, C, H, W)input gives one loss per image and channel,(B, C).
- Parameters:
input (
Tensor) – images(*, H, W).target (
Tensor) – images with the shape ofinput.input_mask (
Tensor|None, optional) – boolean region of interest(H, W)ofinput, common to the batch;Nonekeeps every position. Default:Nonetarget_mask (
Tensor|None, optional) – boolean region of interest(H, W)oftarget, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Return type:
- Returns:
the loss per image, with shape
*, in the input dtype.
See also
MILossFromRef2D: the module form, built on the target.normalized_mutual_information_loss_2d(): Studholme’s normalization, in[-2, -1].mutual_information_loss(): the same loss for flat signals(*, N).mutual_information_loss_3d(): the same loss for volumes(*, D, H, W).
- kornia.losses.mutual_information_loss_3d(input, target, input_mask=None, target_mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the mutual-information loss of two volumes
(*, D, H, W).loss = mutual_information_loss_3d(input, target)returns the negative mutual information ofinputandtargetfrom their kernel (Parzen-window) joint histogram, one value per volume.\[\text{loss} = -(H(X) + H(Y) - H(X, Y))\]- Convention:
See the Convention block of
mutual_information_loss(); this function applies it toinput.flatten(-3)andtarget.flatten(-3). Every axis before the last three is a batch axis, so a(B, C, H, W)tensor is read asBvolumes of depthCand gives(B,).
- Parameters:
input (
Tensor) – volumes(*, D, H, W).target (
Tensor) – volumes with the shape ofinput.input_mask (
Tensor|None, optional) – boolean region of interest(D, H, W)ofinput, common to the batch;Nonekeeps every position. Default:Nonetarget_mask (
Tensor|None, optional) – boolean region of interest(D, H, W)oftarget, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Return type:
- Returns:
the loss per volume, with shape
*, in the input dtype.
See also
MILossFromRef3D: the module form, built on the target.normalized_mutual_information_loss_3d(): Studholme’s normalization, in[-2, -1].mutual_information_loss(): the same loss for flat signals(*, N).mutual_information_loss_2d(): the same loss for images(*, H, W).
- kornia.losses.normalized_mutual_information_loss(input, target, input_mask=None, target_mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the normalized mutual-information loss of two flat signals
(*, N).loss = normalized_mutual_information_loss(input, target)returns the negative normalized mutual information ofinputandtargetfrom their kernel (Parzen-window) joint histogram, one value per leading index.\[\text{loss} = -\frac{H(X) + H(Y)}{H(X, Y)}\]- Convention:
The loss is the negative of Studholme’s normalized mutual information, which lies in \([1, 2]\): the loss lies in
[-2, -1]and is-1when one signal is constant and the other is not. Two constant signals give a finite value below-1that changes with the dtype,num_binsand the number of samples, because histogram cells are floored at machine epsilon. With continuous values and the defaultwindow_radius, even an image against itself scores above-2. Registration maps this normalisation onto scikit-image and scikit-learn.Everything else is as in the Convention block of
mutual_information_loss().
- Parameters:
input (
Tensor) – flat signals(*, N).target (
Tensor) – flat signals with the shape ofinput.input_mask (
Tensor|None, optional) – boolean region of interest(N,)ofinput, common to the batch;Nonekeeps every position. Default:Nonetarget_mask (
Tensor|None, optional) – boolean region of interest(N,)oftarget, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Return type:
- Returns:
the loss per leading index, with shape
*, in the input dtype.
See also
NMILossFromRef: the module form, built on the target.mutual_information_loss(): the unnormalized mutual information, in nats.normalized_mutual_information_loss_2d(): the same loss for images(*, H, W).normalized_mutual_information_loss_3d(): the same loss for volumes(*, D, H, W).
Example
>>> input = torch.rand(2, 3, 64) >>> target = torch.rand(2, 3, 64) >>> loss = normalized_mutual_information_loss(input, target)
- kornia.losses.normalized_mutual_information_loss_2d(input, target, input_mask=None, target_mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the normalized mutual-information loss of two images
(*, H, W).loss = normalized_mutual_information_loss_2d(input, target)returns the negative normalized mutual information ofinputandtargetfrom their kernel (Parzen-window) joint histogram, one value per image.\[\text{loss} = -\frac{H(X) + H(Y)}{H(X, Y)}\]- Convention:
See the Convention block of
normalized_mutual_information_loss(); the flattening and the batch axes are those ofmutual_information_loss_2d().
- Parameters:
input (
Tensor) – images(*, H, W).target (
Tensor) – images with the shape ofinput.input_mask (
Tensor|None, optional) – boolean region of interest(H, W)ofinput, common to the batch;Nonekeeps every position. Default:Nonetarget_mask (
Tensor|None, optional) – boolean region of interest(H, W)oftarget, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Return type:
- Returns:
the loss per image, with shape
*, in the input dtype.
See also
NMILossFromRef2D: the module form, built on the target.mutual_information_loss_2d(): the unnormalized mutual information, in nats.normalized_mutual_information_loss(): the same loss for flat signals(*, N).normalized_mutual_information_loss_3d(): the same loss for volumes(*, D, H, W).
- kornia.losses.normalized_mutual_information_loss_3d(input, target, input_mask=None, target_mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the normalized mutual-information loss of two volumes
(*, D, H, W).loss = normalized_mutual_information_loss_3d(input, target)returns the negative normalized mutual information ofinputandtargetfrom their kernel (Parzen-window) joint histogram, one value per volume.\[\text{loss} = -\frac{H(X) + H(Y)}{H(X, Y)}\]- Convention:
See the Convention block of
normalized_mutual_information_loss(); the flattening and the batch axes are those ofmutual_information_loss_3d().
- Parameters:
input (
Tensor) – volumes(*, D, H, W).target (
Tensor) – volumes with the shape ofinput.input_mask (
Tensor|None, optional) – boolean region of interest(D, H, W)ofinput, common to the batch;Nonekeeps every position. Default:Nonetarget_mask (
Tensor|None, optional) – boolean region of interest(D, H, W)oftarget, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Return type:
- Returns:
the loss per volume, with shape
*, in the input dtype.
See also
NMILossFromRef3D: the module form, built on the target.mutual_information_loss_3d(): the unnormalized mutual information, in nats.normalized_mutual_information_loss(): the same loss for flat signals(*, N).normalized_mutual_information_loss_2d(): the same loss for images(*, H, W).
Modules#
- class kornia.losses.MILossFromRef(reference_signal, mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the mutual-information loss of signals
(*, N)against a reference (module form).criterion = MILossFromRef(reference_signal, mask)stores the reference.loss = criterion(other_signal)ismutual_information_loss()withinput=other_signalandtarget=reference_signal.- Convention:
See the Convention block of
mutual_information_loss().At construction the reference is restricted to its mask, min-max normalised and stored as the buffer
signal, next to a copy of the mask as the buffermask; later in-place changes to the reference tensor or to the mask tensor are not seen. The cache is not detached: a reference that requires grad receives a gradient from the first backward pass, and a second backward pass through the same module raises. Half-precision references are normalised and cached in float32. The final loss and constant-signal threshold follow the original reference dtype, including after.to(dtype); converting the cache itself to a lower precision can round its stored bin positions.
- Parameters:
reference_signal (
Tensor) – reference signals(*, N).mask (
Tensor|None, optional) – boolean region of interest(N,)of the reference, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Shape:
other_signal: signals with the shape of
reference_signal.other_mask: boolean region of interest
(N,)ofother_signal, orNone.Output: the loss per leading index, in the dtype of the reference.
See also
mutual_information_loss(): the one-call form.NMILossFromRef: Studholme’s normalization, in[-2, -1].MILossFromRef2D: the same loss for images(*, H, W).MILossFromRef3D: the same loss for volumes(*, D, H, W).
Example
>>> reference = torch.rand(2, 64) >>> criterion = MILossFromRef(reference) >>> loss = criterion(torch.rand(2, 64))
- class kornia.losses.MILossFromRef2D(reference_signal, mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1)[source]#
Compute the mutual-information loss of images
(*, H, W)against a reference (module form).criterion = MILossFromRef2D(reference_signal, mask)stores the reference.loss = criterion(other_signal)ismutual_information_loss_2d()withinput=other_signalandtarget=reference_signal.- Convention:
See the Convention block of
MILossFromRef; the flattening and the batch axes are those ofmutual_information_loss_2d().
- Parameters:
reference_signal (
Tensor) – reference images(*, H, W).mask (
Tensor|None, optional) – boolean region of interest(H, W)of the reference, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1
- Shape:
other_signal: images with the shape of
reference_signal.other_mask: boolean region of interest
(H, W)ofother_signal, orNone.Output: the loss per image, in the dtype of the reference.
See also
mutual_information_loss_2d(): the one-call form.NMILossFromRef2D: Studholme’s normalization, in[-2, -1].MILossFromRef: the same loss for signals(*, N).MILossFromRef3D: the same loss for volumes(*, D, H, W).
- class kornia.losses.MILossFromRef3D(reference_signal, mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1)[source]#
Compute the mutual-information loss of volumes
(*, D, H, W)against a reference (module form).criterion = MILossFromRef3D(reference_signal, mask)stores the reference.loss = criterion(other_signal)ismutual_information_loss_3d()withinput=other_signalandtarget=reference_signal.- Convention:
See the Convention block of
MILossFromRef; the flattening and the batch axes are those ofmutual_information_loss_3d().
- Parameters:
reference_signal (
Tensor) – reference volumes(*, D, H, W).mask (
Tensor|None, optional) – boolean region of interest(D, H, W)of the reference, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1
- Shape:
other_signal: volumes with the shape of
reference_signal.other_mask: boolean region of interest
(D, H, W)ofother_signal, orNone.Output: the loss per volume, in the dtype of the reference.
See also
mutual_information_loss_3d(): the one-call form.NMILossFromRef3D: Studholme’s normalization, in[-2, -1].MILossFromRef: the same loss for signals(*, N).MILossFromRef2D: the same loss for images(*, H, W).
- class kornia.losses.NMILossFromRef(reference_signal, mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1.0)[source]#
Compute the normalized mutual-information loss of signals
(*, N)against a reference (module form).criterion = NMILossFromRef(reference_signal, mask)stores the reference.loss = criterion(other_signal)isnormalized_mutual_information_loss()withinput=other_signalandtarget=reference_signal.- Convention:
See the Convention blocks of
normalized_mutual_information_loss()for the loss and ofMILossFromReffor the stored reference.
- Parameters:
reference_signal (
Tensor) – reference signals(*, N).mask (
Tensor|None, optional) – boolean region of interest(N,)of the reference, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1.0
- Shape:
other_signal: signals with the shape of
reference_signal.other_mask: boolean region of interest
(N,)ofother_signal, orNone.Output: the loss per leading index, in the dtype of the reference.
See also
normalized_mutual_information_loss(): the one-call form.MILossFromRef: the unnormalized mutual information, in nats.NMILossFromRef2D: the same loss for images(*, H, W).NMILossFromRef3D: the same loss for volumes(*, D, H, W).
Example
>>> reference = torch.rand(2, 64) >>> criterion = NMILossFromRef(reference) >>> loss = criterion(torch.rand(2, 64))
- class kornia.losses.NMILossFromRef2D(reference_signal, mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1)[source]#
Compute the normalized mutual-information loss of images
(*, H, W)against a reference (module form).criterion = NMILossFromRef2D(reference_signal, mask)stores the reference.loss = criterion(other_signal)isnormalized_mutual_information_loss_2d()withinput=other_signalandtarget=reference_signal.- Convention:
See the Convention block of
NMILossFromRef; the flattening and the batch axes are those ofnormalized_mutual_information_loss_2d().
- Parameters:
reference_signal (
Tensor) – reference images(*, H, W).mask (
Tensor|None, optional) – boolean region of interest(H, W)of the reference, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1
- Shape:
other_signal: images with the shape of
reference_signal.other_mask: boolean region of interest
(H, W)ofother_signal, orNone.Output: the loss per image, in the dtype of the reference.
See also
normalized_mutual_information_loss_2d(): the one-call form.MILossFromRef2D: the unnormalized mutual information, in nats.NMILossFromRef: the same loss for signals(*, N).NMILossFromRef3D: the same loss for volumes(*, D, H, W).
- class kornia.losses.NMILossFromRef3D(reference_signal, mask=None, kernel_function=MIKernel.xu, num_bins=64, window_radius=1)[source]#
Compute the normalized mutual-information loss of volumes
(*, D, H, W)against a reference (module form).criterion = NMILossFromRef3D(reference_signal, mask)stores the reference.loss = criterion(other_signal)isnormalized_mutual_information_loss_3d()withinput=other_signalandtarget=reference_signal.- Convention:
See the Convention block of
NMILossFromRef; the flattening and the batch axes are those ofnormalized_mutual_information_loss_3d().
- Parameters:
reference_signal (
Tensor) – reference volumes(*, D, H, W).mask (
Tensor|None, optional) – boolean region of interest(D, H, W)of the reference, common to the batch;Nonekeeps every position. Default:Nonekernel_function (
MIKernel, optional) – kernel that spreads each value over the bins. Default:MIKernel.xunum_bins (
int, optional) – number of bins per signal. Default:64window_radius (
float, optional) – radius of the kernel in bin widths. Default:1
- Shape:
other_signal: volumes with the shape of
reference_signal.other_mask: boolean region of interest
(D, H, W)ofother_signal, orNone.Output: the loss per volume, in the dtype of the reference.
See also
normalized_mutual_information_loss_3d(): the one-call form.MILossFromRef3D: the unnormalized mutual information, in nats.NMILossFromRef: the same loss for signals(*, N).NMILossFromRef2D: the same loss for images(*, H, W).
Kernels#
- class kornia.losses.MIKernel(value)[source]#
Choose the kernel that spreads a sample over the histogram bins of the mutual-information losses.
Pass a member as the
kernel_functionof a mutual-information loss. The members are not callable: a member’svalueis the kernelf(d, window_radius=1.0), the weight that a sample at distancedfrom a bin centre, in bin widths, gives that bin.- Convention:
Every kernel is 0 outside
|d| <= window_radius. Withu = |d| / window_radius:xu(Xu et al., 2008), the default: \(1 - 0.1 u - 1.8 u^2\) for \(u < 0.5\) and \(1.9 - 3.7 u + 1.8 u^2\) up to \(u = 1\). Atwindow_radius=1the weights of a sample between the first and the last bin centre sum to 1.rectangular: 1 on the closed support, so a sample counts fully in every bin withinwindow_radius. Its loss has no gradient (evaluation only, seemutual_information_loss()).truncated_gaussian: the normal density with standard deviationwindow_radius, cut at one standard deviation.
See also
mutual_information_loss(): takes a member askernel_function, as do the other mutual-information losses and their module forms.