π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): return the exact Euclidean distance instead of sqrt(d^2 + eps) (#4968)
li-lizhea908a443eaed
diff --git a/changelog.d/4968.fixed.md b/changelog.d/4968.fixed.mdnew file mode 100644index 000000000..571d644b5--- /dev/null+++ b/changelog.d/4968.fixed.md@@ -0,0 +1,6 @@+`kornia.geometry.euclidean_distance` now returns the exact Euclidean distance. The previous form+added `eps` (1e-6) inside the square root, which biased every result upwards and floored it at+`sqrt(eps)` = 1e-3: coincident points read 0.001 and a true distance of 1e-4 read 1.005e-3+(+905 %). The singular point is guarded with `torch.where` instead, so coincident points return+exactly 0 with a finite (zero) gradient, as `torch.linalg.norm` does. The `eps` argument is now+unused and is kept for backward compatibility.diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex c76d90246..991960786 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -308,13 +308,19 @@ def euclidean_distance(x: torch.Tensor, y: torch.Tensor, keepdim: bool = False,x: first set of points of shape :math:`(*, N)`.y: second set of points of shape :math:`(*, N)`.keepdim: whether to keep the dimension after reduction.- eps: small value to have numerical stability.+ eps: unused; kept for backward compatibility. The result is the exact Euclidean distance."""KORNIA_CHECK_SHAPE(x, ["*", "N"])KORNIA_CHECK_SHAPE(y, ["*", "N"])- return (x - y).pow(2).sum(dim=-1, keepdim=keepdim).add_(eps).sqrt_()+ d2 = (x - y).pow(2).sum(dim=-1, keepdim=keepdim)+ # Guard the singular point by substituting a safe argument into the square root and taking the+ # value from the other arm of the ``torch.where``, so coincident points return exactly ``0``+ # with a finite (zero) gradient instead of the ``sqrt(eps)`` floor the previous form added.+ positive = d2 > 0+ safe_d2 = torch.where(positive, d2, torch.ones_like(d2))+ return torch.where(positive, safe_d2.sqrt(), torch.zeros_like(d2))# aliasesdiff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex d6bce6b39..f94cc6364 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -428,6 +428,26 @@ class TestEuclideanDistance(BaseTester):dst = kgl.euclidean_distance(pt1, pt2)self.assert_close(dst, torch.tensor(1.0, device=device, dtype=dtype))+ def test_coincident_points_are_zero(self, device, dtype):+ # Exactly 0 with a zero gradient, as torch.linalg.norm gives. Compared exactly: the former sqrt(eps)+ # floor of 1e-3 is inside the default float16 and bfloat16 tolerances.+ pt1 = torch.zeros(3, device=device, dtype=dtype, requires_grad=True)+ pt2 = torch.zeros(3, device=device, dtype=dtype)+ dst = kgl.euclidean_distance(pt1, pt2)+ assert dst.item() == 0.0+ (grad,) = torch.autograd.grad(dst.sum(), pt1)+ assert (grad == 0).all(), grad++ @pytest.mark.parametrize("dist", [1e-4, 1e-3, 1e-2, 1.0])+ def test_distance_is_exact(self, device, dtype, dist):+ if dist**2 < torch.finfo(dtype).tiny:+ pytest.skip(f"the squared distance {dist**2:g} is subnormal in {dtype}")+ pt1 = torch.zeros(3, device=device, dtype=dtype)+ pt2 = torch.tensor([dist, 0.0, 0.0], device=device, dtype=dtype)+ # relative tolerance only: the default half tolerances would absorb the former bias of up to 1e-3+ rtol = 2 * torch.finfo(dtype).eps+ self.assert_close(kgl.euclidean_distance(pt1, pt2), pt2[0], rtol=rtol, atol=0.0)+@pytest.mark.parametrize("shape", [(2,), (3,), (1, 2), (2, 3)])def test_cardinality(self, device, dtype, shape):pt1 = torch.rand(shape, device=device, dtype=dtype)