Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Added distribution mapper (#1667)

Jian Shi2c7d7d6d0705
diff --git a/kornia/augmentation/random_generator/__init__.py b/kornia/augmentation/random_generator/__init__.py
index 88f47289f..3f694e803 100644
--- a/kornia/augmentation/random_generator/__init__.py
+++ b/kornia/augmentation/random_generator/__init__.py
@@ -1,2 +1,4 @@
from kornia.augmentation.random_generator._2d import *
from kornia.augmentation.random_generator._3d import *
+
+from .base import DistributionWithMapper
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 9ed492b24..10376343c 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -1,7 +1,8 @@
-from typing import Dict
+from typing import Callable, Dict, Optional
import torch
import torch.nn as nn
+from torch.distributions import Distribution
class _PostInitInjectionMetaClass(type):
@@ -37,3 +38,57 @@ class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
raise NotImplementedError
+
+
+class DistributionWithMapper(Distribution):
+ """Wraps a distribution with a value mapper function.
+
+ This is used to restrict the output values of a given distribution by a value mapper function.
+ The value mapper function can be functions like sigmoid, tanh, etc.
+
+ Args:
+ dist: the target distribution.
+ map_fn: the callable function to adjust the output from distributions.
+
+ Example:
+ >>> from torch.distributions import Normal
+ >>> import torch.nn as nn
+ >>> # without mapper
+ >>> dist = DistributionWithMapper(Normal(0., 1.,), map_fn=None)
+ >>> _ = torch.manual_seed(0)
+ >>> dist.rsample((8,))
+ tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845, -1.3986, 0.4033, 0.8380])
+ >>> # with sigmoid mapper
+ >>> dist = DistributionWithMapper(Normal(0., 1.,), map_fn=nn.Sigmoid())
+ >>> _ = torch.manual_seed(0)
+ >>> dist.rsample((8,))
+ tensor([0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980])
+ """
+
+ def __init__(self, dist: Distribution, map_fn: Optional[Callable] = None) -> None:
+ self.dist = dist
+ self.map_fn = map_fn
+
+ def rsample(self, sample_shape: torch.Size) -> torch.Tensor: # type:ignore
+ out = self.dist.rsample(sample_shape)
+ if self.map_fn is not None:
+ out = self.map_fn(out)
+ return out
+
+ def sample(self, sample_shape: torch.Size) -> torch.Tensor: # type:ignore
+ out = self.dist.sample(sample_shape)
+ if self.map_fn is not None:
+ out = self.map_fn(out)
+ return out
+
+ def sample_n(self, n) -> torch.Tensor:
+ out = self.dist.sample_n(n)
+ if self.map_fn is not None:
+ out = self.map_fn(out)
+ return out
+
+ def __getattr__(self, attr):
+ try:
+ return getattr(self, attr)
+ except AttributeError:
+ return getattr(self.dist, attr)
diff --git a/test/augmentation/test_dist_mapper.py b/test/augmentation/test_dist_mapper.py
new file mode 100644
index 000000000..050878bac
--- /dev/null
+++ b/test/augmentation/test_dist_mapper.py
@@ -0,0 +1,18 @@
+import torch
+import torch.nn as nn
+from torch.distributions import Normal
+from torch.testing import assert_allclose
+
+from kornia.augmentation.random_generator import DistributionWithMapper
+
+
+class TestDistMapper:
+
+ def test_mapper(self,):
+ _ = torch.manual_seed(0)
+ dist = DistributionWithMapper(Normal(0., 1.,), map_fn=nn.Sigmoid())
+ out = dist.rsample((8,))
+ exp = torch.tensor([
+ 0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980
+ ])
+ assert_allclose(out, exp, rtol=1e-4, atol=1e-4)