π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
refactor spatial_soft_argmax2d and add temperature factor
edgarriba257586e08e17
diff --git a/kornia/contrib/spatial_soft_argmax2d.py b/kornia/contrib/spatial_soft_argmax2d.pyindex 44cdc0b61..bba2f7d90 100644--- a/kornia/contrib/spatial_soft_argmax2d.py+++ b/kornia/contrib/spatial_soft_argmax2d.py@@ -1,86 +1,87 @@-from typing import Optional, Tuple-import torchimport torch.nn as nn-import torch.nn.functional as Ffrom kornia.utils import create_meshgrid-class SpatialSoftArgmax2d(nn.Module):- r"""Creates a module that computes the Spatial Soft-Argmax 2D+def spatial_soft_argmax2d(+ input: torch.Tensor,+ temperature: torch.Tensor = torch.tensor(1.0),+ normalized_coordinates: bool = True,+ eps: float = 1e-8) -> torch.Tensor:+ r"""Function that computes the Spatial Soft-Argmax 2Dof a given input heatmap.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+ temperature (torch.Tensor): factor to apply to input. Default is 1.+ normalized_coordinates (bool): wether to return thecoordinates normalized in the range of [-1, 1]. Otherwise,it will return the coordinates in the range of the input shape.Default is True.+ eps (float): small value to avoid zero division. Default is 1e-8.Shape:- Input: :math:`(B, N, H, W)`- Output: :math:`(B, N, 2)`- Examples::- >>> input = torch.rand(1, 4, 2, 3)- >>> m = kornia.losses.SpatialSoftArgmax2d()- >>> coords = m(input) # 1x4x2- >>> x_coord, y_coord = torch.chunk(coords, dim=-1, chunks=2)+ Examples:+ >>> input = torch.tensor([[[+ [0., 0., 0.],+ [0., 10., 0.],+ [0., 0., 0.]]]])+ >>> coords = kornia.spatial_soft_argmax2d(input, False)+ tensor([[[1.0000, 1.0000]]])"""-- 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: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # unpack shapes and create view from input tensor- batch_size, channels, height, width = input.shape- x: torch.Tensor = input.view(batch_size, channels, -1)-- # compute softmax with max substraction trick- exp_x = torch.exp(x - torch.max(x, dim=-1, keepdim=True)[0])- exp_x_sum = torch.tensor(- 1.0) / (exp_x.sum(dim=-1, keepdim=True) + self.eps)-- # create coordinates grid- grid: torch.Tensor = create_meshgrid(- height, width, self.normalized_coordinates)- grid = grid.to(input.device).to(input.dtype)-- pos_x: torch.Tensor = grid[..., 0].reshape(-1)- pos_y: torch.Tensor = grid[..., 1].reshape(-1)+ if not torch.is_tensor(input):+ raise TypeError("Input input type is not a torch.Tensor. Got {}"+ .format(type(input)))+ if not len(input.shape) == 4:+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"+ .format(input.shape))+ # unpack shapes and create view from input tensor+ batch_size, channels, height, width = input.shape+ x: torch.Tensor = temperature * input.view(batch_size, channels, -1)++ # compute softmax with max substraction trick+ exp_x = torch.exp(x - torch.max(x, dim=-1, keepdim=True)[0])+ exp_x_sum = torch.tensor(+ 1.0) / (exp_x.sum(dim=-1, keepdim=True) + eps)++ # create coordinates grid+ grid: torch.Tensor = create_meshgrid(+ height, width, normalized_coordinates)+ grid = grid.to(input.device).to(input.dtype)++ pos_x: torch.Tensor = grid[..., 0].reshape(-1)+ pos_y: torch.Tensor = grid[..., 1].reshape(-1)++ # compute the expected coordinates+ expected_y: torch.Tensor = torch.sum(+ (pos_y * exp_x) * exp_x_sum, dim=-1, keepdim=True)+ expected_x: torch.Tensor = torch.sum(+ (pos_x * exp_x) * exp_x_sum, dim=-1, keepdim=True)++ output: torch.Tensor = torch.cat([expected_x, expected_y], dim=-1)+ return output.view(batch_size, channels, 2) # BxNx2- # compute the expected coordinates- expected_y: torch.Tensor = torch.sum(- (pos_y * exp_x) * exp_x_sum, dim=-1, keepdim=True)- expected_x: torch.Tensor = torch.sum(- (pos_x * exp_x) * exp_x_sum, dim=-1, keepdim=True)-- output: torch.Tensor = torch.cat([expected_x, expected_y], dim=-1)- return output.view(batch_size, channels, 2) # BxNx2---######################-# functional interface-######################---def spatial_soft_argmax2d(- input: torch.Tensor,- normalized_coordinates: bool = True) -> torch.Tensor:+class SpatialSoftArgmax2d(nn.Module):r"""Function that computes the Spatial Soft-Argmax 2D of a given heatmap.- See :class:`~kornia.contrib.SpatialSoftArgmax2d` for details.+ See :class:`~kornia.contrib.spatial_soft_argmax2d` for details."""- return SpatialSoftArgmax2d(normalized_coordinates)(input)+ def __init__(self,+ temperature: torch.Tensor = torch.tensor(1.0),+ normalized_coordinates: bool = True,+ eps: float = 1e-8) -> None:+ super(SpatialSoftArgmax2d, self).__init__()+ self.temperature: torch.Tensor = temperature+ self.normalized_coordinates: bool = normalized_coordinates+ self.eps: float = eps++ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore+ return spatial_soft_argmax2d(input, self.temperature,+ self.normalized_coordinates, self.eps)diff --git a/test/test_contrib.py b/test/test_contrib.pyindex 131776500..bd3c4417c 100644--- a/test/test_contrib.py+++ b/test/test_contrib.py@@ -165,6 +165,11 @@ class TestSpatialSoftArgmax2d:m = kornia.contrib.SpatialSoftArgmax2d()assert m(input).shape == (1, 1, 2)+ def test_smoke_batch(self):+ input = torch.zeros(2, 1, 2, 3)+ m = kornia.contrib.SpatialSoftArgmax2d()+ assert m(input).shape == (2, 1, 2)+def test_top_left(self):input = torch.zeros(1, 1, 2, 3)input[..., 0, 0] = 10.@@ -177,7 +182,6 @@ class TestSpatialSoftArgmax2d:input = torch.zeros(1, 1, 2, 3)input[..., 0, 0] = 10.- #import pdb;pdb.set_trace()coord = kornia.contrib.spatial_soft_argmax2d(input, False)assert pytest.approx(coord[..., 0].item(), 0.0)assert pytest.approx(coord[..., 1].item(), 0.0)@@ -217,11 +221,15 @@ class TestSpatialSoftArgmax2d:def test_jit(self):@torch.jit.script- def op_script(input: torch.Tensor, normalize_coords: bool) -> torch.Tensor:- return kornia.spatial_soft_argmax2d(input, normalize_coords)+ def op_script(input: torch.Tensor,+ temperature: torch.Tensor,+ normalize_coords: bool,+ eps: float) -> torch.Tensor:+ return kornia.spatial_soft_argmax2d(+ input, temperature, normalize_coords, eps)input = torch.rand(1, 2, 3, 4)- actual = op_script(input, True)+ actual = op_script(input, torch.tensor(1.0), True, 1e-8)expected = kornia.spatial_soft_argmax2d(input)assert_allclose(actual, expected)