logistic_normal.py 2.2 KB

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