normal.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import math
  2. from numbers import Real
  3. from numbers import Number
  4. import torch
  5. from torch.distributions import constraints
  6. from torch.distributions.exp_family import ExponentialFamily
  7. from torch.distributions.utils import _standard_normal, broadcast_all
  8. __all__ = ['Normal']
  9. class Normal(ExponentialFamily):
  10. r"""
  11. Creates a normal (also called Gaussian) distribution parameterized by
  12. :attr:`loc` and :attr:`scale`.
  13. Example::
  14. >>> # xdoctest: +IGNORE_WANT("non-deterinistic")
  15. >>> m = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
  16. >>> m.sample() # normally distributed with loc=0 and scale=1
  17. tensor([ 0.1046])
  18. Args:
  19. loc (float or Tensor): mean of the distribution (often referred to as mu)
  20. scale (float or Tensor): standard deviation of the distribution
  21. (often referred to as sigma)
  22. """
  23. arg_constraints = {'loc': constraints.real, 'scale': constraints.positive}
  24. support = constraints.real
  25. has_rsample = True
  26. _mean_carrier_measure = 0
  27. @property
  28. def mean(self):
  29. return self.loc
  30. @property
  31. def mode(self):
  32. return self.loc
  33. @property
  34. def stddev(self):
  35. return self.scale
  36. @property
  37. def variance(self):
  38. return self.stddev.pow(2)
  39. def __init__(self, loc, scale, validate_args=None):
  40. self.loc, self.scale = broadcast_all(loc, scale)
  41. if isinstance(loc, Number) and isinstance(scale, Number):
  42. batch_shape = torch.Size()
  43. else:
  44. batch_shape = self.loc.size()
  45. super().__init__(batch_shape, validate_args=validate_args)
  46. def expand(self, batch_shape, _instance=None):
  47. new = self._get_checked_instance(Normal, _instance)
  48. batch_shape = torch.Size(batch_shape)
  49. new.loc = self.loc.expand(batch_shape)
  50. new.scale = self.scale.expand(batch_shape)
  51. super(Normal, new).__init__(batch_shape, validate_args=False)
  52. new._validate_args = self._validate_args
  53. return new
  54. def sample(self, sample_shape=torch.Size()):
  55. shape = self._extended_shape(sample_shape)
  56. with torch.no_grad():
  57. return torch.normal(self.loc.expand(shape), self.scale.expand(shape))
  58. def rsample(self, sample_shape=torch.Size()):
  59. shape = self._extended_shape(sample_shape)
  60. eps = _standard_normal(shape, dtype=self.loc.dtype, device=self.loc.device)
  61. return self.loc + eps * self.scale
  62. def log_prob(self, value):
  63. if self._validate_args:
  64. self._validate_sample(value)
  65. # compute the variance
  66. var = (self.scale ** 2)
  67. log_scale = math.log(self.scale) if isinstance(self.scale, Real) else self.scale.log()
  68. return -((value - self.loc) ** 2) / (2 * var) - log_scale - math.log(math.sqrt(2 * math.pi))
  69. def cdf(self, value):
  70. if self._validate_args:
  71. self._validate_sample(value)
  72. return 0.5 * (1 + torch.erf((value - self.loc) * self.scale.reciprocal() / math.sqrt(2)))
  73. def icdf(self, value):
  74. return self.loc + self.scale * torch.erfinv(2 * value - 1) * math.sqrt(2)
  75. def entropy(self):
  76. return 0.5 + 0.5 * math.log(2 * math.pi) + torch.log(self.scale)
  77. @property
  78. def _natural_params(self):
  79. return (self.loc / self.scale.pow(2), -0.5 * self.scale.pow(2).reciprocal())
  80. def _log_normalizer(self, x, y):
  81. return -0.25 * x.pow(2) / y + 0.5 * torch.log(-math.pi / y)