Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add normalized_coordinates option to spatial soft-argmax and add integration test

edgarriba14dfd7aa95d0
diff --git a/test/integration/test_soft_argmax2d.py b/test/integration/test_soft_argmax2d.py
new file mode 100644
index 000000000..1bf158bce
--- /dev/null
+++ b/test/integration/test_soft_argmax2d.py
@@ -0,0 +1,63 @@
+import logging
+import pytest
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.optim as optim
+import torchgeometry as tgm
+
+logger = logging.getLogger(__name__)
+
+
+class TestIntegrationSoftArgmax2d:
+ # optimization
+ lr = 1e-3
+ num_iterations = 500
+
+ # data params
+ height = 240
+ width = 320
+
+ def generate_sample(self, base_target, std_val=1.0):
+ """Generates a random sample around the given point.
+ The standard deviation is in pixel.
+ """
+ noise = std_val * torch.rand_like(base_target)
+ return base_target + noise
+
+ def test_regression_2d(self):
+ # create the parameters to estimate: the heatmap
+ params = nn.Parameter(torch.rand(1, 1, self.height, self.width))
+
+ # generate base sample
+ target = torch.zeros(1, 1, 2)
+ target[..., 0] = self.width / 2
+ target[..., 1] = self.height / 2
+
+ # create the optimizer and pass the heatmap
+ optimizer = optim.Adam([params], lr=self.lr)
+
+ # loss criterion
+ criterion = nn.MSELoss()
+
+ # spatial soft-argmax2d module
+ soft_argmax2d = tgm.contrib.SpatialSoftArgmax2d(
+ normalized_coordinates=False)
+
+ # NOTE: check where this comes from
+ temperature = (self.height * self.width) ** (0.5)
+
+ for iter_id in range(self.num_iterations):
+ x = params
+ sample = self.generate_sample(target)
+ pred = soft_argmax2d(temperature * x)
+ loss = criterion(pred, sample)
+ logger.debug("Loss: {0:.3f} Pred: {1}".format(loss.item(), pred))
+
+ optimizer.zero_grad()
+ loss.backward()
+ optimizer.step()
+
+ assert pytest.approx(pred[..., 0].item(), target[..., 0].item())
+ assert pytest.approx(pred[..., 1].item(), target[..., 1].item())
diff --git a/test/test_contrib.py b/test/test_contrib.py
index f1716fc92..7ed8feabd 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -17,18 +17,34 @@ class TestSoftArgmax2d:
input = torch.zeros(1, 1, 2, 3)
input[..., 0, 0] = 10.
- coord = tgm.contrib.spatial_soft_argmax2d(input)
+ coord = tgm.contrib.spatial_soft_argmax2d(input, True)
assert pytest.approx(coord[..., 0].item(), -1.0)
assert pytest.approx(coord[..., 1].item(), -1.0)
+ def _test_top_left_normalized(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., 0, 0] = 10.
+
+ coord = tgm.contrib.spatial_soft_argmax2d(input, False)
+ assert pytest.approx(coord[..., 0].item(), 0.0)
+ assert pytest.approx(coord[..., 1].item(), 0.0)
+
def _test_bottom_right(self):
input = torch.zeros(1, 1, 2, 3)
input[..., -1, 1] = 10.
- coord = tgm.contrib.spatial_soft_argmax2d(input)
+ coord = tgm.contrib.spatial_soft_argmax2d(input, True)
assert pytest.approx(coord[..., 0].item(), 1.0)
assert pytest.approx(coord[..., 1].item(), 1.0)
+ def _test_bottom_right_normalized(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., -1, 1] = 10.
+
+ coord = tgm.contrib.spatial_soft_argmax2d(input, False)
+ assert pytest.approx(coord[..., 0].item(), 2.0)
+ assert pytest.approx(coord[..., 1].item(), 1.0)
+
def _test_batch2_n2(self):
input = torch.zeros(2, 2, 2, 3)
input[0, 0, 0, 0] = 10. # top-left
@@ -59,6 +75,8 @@ class TestSoftArgmax2d:
def test_run_all(self):
self._test_smoke()
self._test_top_left()
+ self._test_top_left_normalized()
self._test_bottom_right()
+ self._test_bottom_right_normalized()
self._test_batch2_n2()
self._test_gradcheck()
diff --git a/torchgeometry/contrib/spatial_soft_argmax2d.py b/torchgeometry/contrib/spatial_soft_argmax2d.py
index e3a63b7ed..ebc53241b 100644
--- a/torchgeometry/contrib/spatial_soft_argmax2d.py
+++ b/torchgeometry/contrib/spatial_soft_argmax2d.py
@@ -5,12 +5,19 @@ import torch.nn as nn
import torch.nn.functional as F
-def create_meshgrid(x):
- pos_y, pos_x = torch.meshgrid(
- torch.linspace(-1.0, 1.0, x.size(2), device=x.device, dtype=x.dtype),
- torch.linspace(-1.0, 1.0, x.size(3), device=x.device, dtype=x.dtype))
- return pos_y, pos_x
+def create_meshgrid(
+ x: torch.Tensor,
+ normalized_coordinates: Optional[bool]) -> torch.Tensor:
+ assert len(x.shape) == 4, x.shape
+ _, _, height, width = x.shape
+ _device, _dtype = x.device, x.dtype
+ if normalized_coordinates:
+ xs = torch.linspace(-1.0, 1.0, width, device=_device, dtype=_dtype)
+ ys = torch.linspace(-1.0, 1.0, height, device=_device, dtype=_dtype)
+ else:
+ xs = torch.linspace(0, width - 1, width, device=_device, dtype=_dtype)
+ ys = torch.linspace(0, height - 1, height, device=_device, dtype=_dtype)
+ return torch.meshgrid(ys, xs) # pos_y, pos_x
class SpatialSoftArgmax2d(nn.Module):
@@ -20,6 +27,12 @@ class SpatialSoftArgmax2d(nn.Module):
Returns the index of the maximum 2d coordinates of the give map.
The output order is x-coord and y-coord.
+ Arguments:
+ normalized_coordinates (Optional[bool]): wether to return the
+ coordinates normalized in the range of [-1, 1]. Otherwise,
+ it will return the coordinates in the range of the input shape.
+ Default is True.
+
Shape:
- Input: :math:`(B, N, H, W)`
- Output: :math:`(B, N, 2)`
@@ -31,8 +44,9 @@ class SpatialSoftArgmax2d(nn.Module):
>>> x_coord, y_coord = torch.chunk(coords, dim=-1, chunks=2)
"""
- def __init__(self) -> None:
+ def __init__(self, normalized_coordinates: Optional[bool] = True) -> None:
super(SpatialSoftArgmax2d, self).__init__()
+ self.normalized_coordinates: Optional[bool] = normalized_coordinates
self.eps: float = 1e-6
def forward(self, input: torch.Tensor) -> torch.Tensor:
@@ -51,7 +65,7 @@ class SpatialSoftArgmax2d(nn.Module):
exp_x_sum = 1.0 / (exp_x.sum(dim=-1, keepdim=True) + self.eps)
# create coordinates grid
- pos_y, pos_x = create_meshgrid(input)
+ pos_y, pos_x = create_meshgrid(input, self.normalized_coordinates)
pos_x = pos_x.reshape(-1)
pos_y = pos_y.reshape(-1)
@@ -69,9 +83,11 @@ class SpatialSoftArgmax2d(nn.Module):
######################
-def spatial_soft_argmax2d(input: torch.Tensor) -> torch.Tensor:
+def spatial_soft_argmax2d(
+ input: torch.Tensor,
+ normalized_coordinates: Optional[bool] = True) -> torch.Tensor:
r"""Function that computes the Spatial Soft-Argmax 2D of a given heatmap.
See :class:`torchgeometry.contrib.SpatialSoftArgmax2d` for details.
"""
- return SpatialSoftArgmax2d()(input)
+ return SpatialSoftArgmax2d(normalized_coordinates)(input)