log_normal.py 2.1 KB

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