log_normal.py 1.9 KB

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