logistic_normal.py 1.9 KB

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