logistic_normal.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # mypy: allow-untyped-defs
  2. from typing import Optional, Union
  3. from torch import Tensor
  4. from torch.distributions import constraints, Independent
  5. from torch.distributions.normal import Normal
  6. from torch.distributions.transformed_distribution import TransformedDistribution
  7. from torch.distributions.transforms import StickBreakingTransform
  8. __all__ = ["LogisticNormal"]
  9. class LogisticNormal(TransformedDistribution):
  10. r"""
  11. Creates a logistic-normal distribution parameterized by :attr:`loc` and :attr:`scale`
  12. that define the base `Normal` distribution transformed with the
  13. `StickBreakingTransform` such that::
  14. X ~ LogisticNormal(loc, scale)
  15. Y = log(X / (1 - X.cumsum(-1)))[..., :-1] ~ Normal(loc, scale)
  16. Args:
  17. loc (float or Tensor): mean of the base distribution
  18. scale (float or Tensor): standard deviation of the base distribution
  19. Example::
  20. >>> # logistic-normal distributed with mean=(0, 0, 0) and stddev=(1, 1, 1)
  21. >>> # of the base Normal distribution
  22. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  23. >>> m = LogisticNormal(torch.tensor([0.0] * 3), torch.tensor([1.0] * 3))
  24. >>> m.sample()
  25. tensor([ 0.7653, 0.0341, 0.0579, 0.1427])
  26. """
  27. arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
  28. support = constraints.simplex
  29. has_rsample = True
  30. base_dist: Independent[Normal]
  31. def __init__(
  32. self,
  33. loc: Union[Tensor, float],
  34. scale: Union[Tensor, float],
  35. validate_args: Optional[bool] = None,
  36. ) -> None:
  37. base_dist = Normal(loc, scale, validate_args=validate_args)
  38. if not base_dist.batch_shape:
  39. base_dist = base_dist.expand([1])
  40. super().__init__(
  41. base_dist, StickBreakingTransform(), validate_args=validate_args
  42. )
  43. def expand(self, batch_shape, _instance=None):
  44. new = self._get_checked_instance(LogisticNormal, _instance)
  45. return super().expand(batch_shape, _instance=new)
  46. @property
  47. def loc(self) -> Tensor:
  48. return self.base_dist.base_dist.loc
  49. @property
  50. def scale(self) -> Tensor:
  51. return self.base_dist.base_dist.scale