log_normal.py 2.2 KB

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