logistic_normal.py 1.9 KB

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