π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): normalise the MI signals onto the bin centres so samples at the maximum keep their histogram weight (#5569)
εΊζ’ηfc3282623a3b
diff --git a/changelog.d/5569.breaking.md b/changelog.d/5569.breaking.mdnew file mode 100644index 000000000..45ac54aa8--- /dev/null+++ b/changelog.d/5569.breaking.md@@ -0,0 +1,9 @@+The mutual information losses (`mutual_information_loss`, `normalized_mutual_information_loss`, their `_2d` and `_3d`+forms and the `MILossFromRef*` and `NMILossFromRef*` modules) now normalise each signal onto the bin centres+`0 β¦ num_bins - 1`, so every sample contributes to the histogram and the result no longer depends on the intensity+polarity (#5546). Previously the signals were normalised onto `[0, num_bins]`, one bin width past the last centre, so+with the default `MIKernel.xu` the pixels at an image's maximum got no histogram weight, and the other two kernels gave+them only part of it: in float64 a binary mask had mutual information 2.4e-13 with itself instead of its entropy, and+normalised mutual information 1.77 instead of 2. Integer images with levels `0 β¦ K` now sit on the bin centres with+`num_bins=K + 1`, not `num_bins=K`. Every value changes, a little on continuous images and a lot on binary, label or+saturated images.diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.pyindex a3d59a616..da4a58b8c 100644--- a/kornia/losses/mutual_information.py+++ b/kornia/losses/mutual_information.py@@ -120,8 +120,9 @@ def _normalize_signal(data: torch.Tensor, num_bins: int, eps: float = 1e-8) -> tmin_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)+ # Map the range onto the bin centres 0 ... num_bins - 1, so that the maximum lands on the last centre and gets+ # full histogram weight like every other sample. The signal is considered trivial if too low variation.+ return torch.where(diff > eps, (data - min_val.unsqueeze(-1)) / diff * (num_bins - 1), 0)def _joint_histogram_to_entropies(joint_histogram: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.pyindex c7934d408..b252e73bb 100644--- a/tests/losses/test_mutual_information.py+++ b/tests/losses/test_mutual_information.py@@ -146,6 +146,59 @@ class TestMutualInformationLoss(BaseTester):self.assert_close(_normalize_signal(signal, num_bins=64), torch.zeros_like(signal))+ def test_normalizes_onto_bin_centres(self, device, dtype):+ signal = torch.tensor([2.0, 2.5, 3.0], device=device, dtype=dtype)+ expected = torch.tensor([0.0, 31.5, 63.0], device=device, dtype=dtype)++ self.assert_close(_normalize_signal(signal, num_bins=64), expected)++ def test_joint_histogram_counts_every_sample(self, device, dtype):+ # The kernel weights of a sample sum to one over the bin centres, so the histogram counts every sample,+ # including the ones at a signal's maximum, only when the maximum is normalised onto the last centre.+ pred = torch.rand(2, 3, 20, device=device, dtype=dtype)+ target = torch.rand(2, 3, 20, device=device, dtype=dtype)+ module = MILossFromRef(target)+ joint_histogram = module._compute_joint_histogram(pred, module.eps)++ self.assert_close(+ joint_histogram.sum((-2, -1)), torch.full((2, 3), 20.0, device=device, dtype=dtype), low_tolerance=True+ )++ def test_binary_mask_mutual_information_is_its_entropy(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the entropies need full precision to match the hard histogram")+ generator = torch.Generator().manual_seed(0)+ # the float64 oracle is computed on the CPU: MPS has no float64+ mask = (torch.rand(12, 20, generator=generator) > 0.5).double()+ p = mask.mean()+ entropy = -(p * p.log() + (1 - p) * (1 - p).log())+ mask, entropy = mask.to(device, dtype), entropy.to(device, dtype)++ self.assert_close(-mutual_information_loss_2d(mask, mask), entropy)+ self.assert_close(-mutual_information_loss_2d(1 - mask, mask), entropy)+ self.assert_close(+ -normalized_mutual_information_loss_2d(mask, mask), torch.tensor(2.0, device=device, dtype=dtype)+ )++ def test_integer_levels_match_hard_histogram(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the entropies need full precision to match the hard histogram")+ levels = 4+ # the float64 oracle is computed on the CPU: MPS has no float64+ pred = torch.tensor([[0, 1, 2, 3], [3, 2, 1, 0], [0, 0, 3, 3]])+ target = torch.tensor([[0, 1, 1, 3], [3, 3, 1, 0], [0, 2, 3, 3]])+ joint = torch.bincount(pred.flatten() * levels + target.flatten(), minlength=levels**2)+ joint = joint.view(levels, levels).double() / pred.numel()+ independent = joint.sum(-1, keepdim=True) * joint.sum(-2, keepdim=True)+ expected = torch.xlogy(joint, joint / independent).sum().to(device, dtype)+ pred, target = pred.to(device, dtype), target.to(device, dtype)++ mutual_information = -mutual_information_loss_2d(pred, target, num_bins=levels)+ inverted = -mutual_information_loss_2d(levels - 1 - pred, target, num_bins=levels)++ self.assert_close(mutual_information, expected)+ self.assert_close(inverted, mutual_information)+@pytest.mark.parametrize("kernel", [MIKernel.xu, MIKernel.rectangular, MIKernel.truncated_gaussian])@pytest.mark.parametrize("dims", [(5,), (3, 1), (2, 8), (2, 1, 8), (2, 1, 2, 8), (2, 1, 2, 1, 8)])def test_batch_consistency(self, device, dtype, kernel, dims):