beta.py 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from numbers import Real, Number
  2. import torch
  3. from torch.distributions import constraints
  4. from torch.distributions.dirichlet import Dirichlet
  5. from torch.distributions.exp_family import ExponentialFamily
  6. from torch.distributions.utils import broadcast_all
  7. class Beta(ExponentialFamily):
  8. r"""
  9. Beta distribution parameterized by :attr:`concentration1` and :attr:`concentration0`.
  10. Example::
  11. >>> m = Beta(torch.tensor([0.5]), torch.tensor([0.5]))
  12. >>> m.sample() # Beta distributed with concentration concentration1 and concentration0
  13. tensor([ 0.1046])
  14. Args:
  15. concentration1 (float or Tensor): 1st concentration parameter of the distribution
  16. (often referred to as alpha)
  17. concentration0 (float or Tensor): 2nd concentration parameter of the distribution
  18. (often referred to as beta)
  19. """
  20. arg_constraints = {'concentration1': constraints.positive, 'concentration0': constraints.positive}
  21. support = constraints.unit_interval
  22. has_rsample = True
  23. def __init__(self, concentration1, concentration0, validate_args=None):
  24. if isinstance(concentration1, Real) and isinstance(concentration0, Real):
  25. concentration1_concentration0 = torch.tensor([float(concentration1), float(concentration0)])
  26. else:
  27. concentration1, concentration0 = broadcast_all(concentration1, concentration0)
  28. concentration1_concentration0 = torch.stack([concentration1, concentration0], -1)
  29. self._dirichlet = Dirichlet(concentration1_concentration0, validate_args=validate_args)
  30. super(Beta, self).__init__(self._dirichlet._batch_shape, validate_args=validate_args)
  31. def expand(self, batch_shape, _instance=None):
  32. new = self._get_checked_instance(Beta, _instance)
  33. batch_shape = torch.Size(batch_shape)
  34. new._dirichlet = self._dirichlet.expand(batch_shape)
  35. super(Beta, new).__init__(batch_shape, validate_args=False)
  36. new._validate_args = self._validate_args
  37. return new
  38. @property
  39. def mean(self):
  40. return self.concentration1 / (self.concentration1 + self.concentration0)
  41. @property
  42. def mode(self):
  43. return self._dirichlet.mode[..., 0]
  44. @property
  45. def variance(self):
  46. total = self.concentration1 + self.concentration0
  47. return (self.concentration1 * self.concentration0 /
  48. (total.pow(2) * (total + 1)))
  49. def rsample(self, sample_shape=()):
  50. return self._dirichlet.rsample(sample_shape).select(-1, 0)
  51. def log_prob(self, value):
  52. if self._validate_args:
  53. self._validate_sample(value)
  54. heads_tails = torch.stack([value, 1.0 - value], -1)
  55. return self._dirichlet.log_prob(heads_tails)
  56. def entropy(self):
  57. return self._dirichlet.entropy()
  58. @property
  59. def concentration1(self):
  60. result = self._dirichlet.concentration[..., 0]
  61. if isinstance(result, Number):
  62. return torch.tensor([result])
  63. else:
  64. return result
  65. @property
  66. def concentration0(self):
  67. result = self._dirichlet.concentration[..., 1]
  68. if isinstance(result, Number):
  69. return torch.tensor([result])
  70. else:
  71. return result
  72. @property
  73. def _natural_params(self):
  74. return (self.concentration1, self.concentration0)
  75. def _log_normalizer(self, x, y):
  76. return torch.lgamma(x) + torch.lgamma(y) - torch.lgamma(x + y)