1# mypy: allow-untyped-defs 2from numbers import Number 3 4import torch 5from torch.distributions import constraints 6from torch.distributions.exp_family import ExponentialFamily 7from torch.distributions.utils import broadcast_all 8from torch.types import _size 9 10 11__all__ = ["Gamma"] 12 13 14def _standard_gamma(concentration): 15 return torch._standard_gamma(concentration) 16 17 18class Gamma(ExponentialFamily): 19 r""" 20 Creates a Gamma distribution parameterized by shape :attr:`concentration` and :attr:`rate`. 21 22 Example:: 23 24 >>> # xdoctest: +IGNORE_WANT("non-deterministic") 25 >>> m = Gamma(torch.tensor([1.0]), torch.tensor([1.0])) 26 >>> m.sample() # Gamma distributed with concentration=1 and rate=1 27 tensor([ 0.1046]) 28 29 Args: 30 concentration (float or Tensor): shape parameter of the distribution 31 (often referred to as alpha) 32 rate (float or Tensor): rate = 1 / scale of the distribution 33 (often referred to as beta) 34 """ 35 arg_constraints = { 36 "concentration": constraints.positive, 37 "rate": constraints.positive, 38 } 39 support = constraints.nonnegative 40 has_rsample = True 41 _mean_carrier_measure = 0 42 43 @property 44 def mean(self): 45 return self.concentration / self.rate 46 47 @property 48 def mode(self): 49 return ((self.concentration - 1) / self.rate).clamp(min=0) 50 51 @property 52 def variance(self): 53 return self.concentration / self.rate.pow(2) 54 55 def __init__(self, concentration, rate, validate_args=None): 56 self.concentration, self.rate = broadcast_all(concentration, rate) 57 if isinstance(concentration, Number) and isinstance(rate, Number): 58 batch_shape = torch.Size() 59 else: 60 batch_shape = self.concentration.size() 61 super().__init__(batch_shape, validate_args=validate_args) 62 63 def expand(self, batch_shape, _instance=None): 64 new = self._get_checked_instance(Gamma, _instance) 65 batch_shape = torch.Size(batch_shape) 66 new.concentration = self.concentration.expand(batch_shape) 67 new.rate = self.rate.expand(batch_shape) 68 super(Gamma, new).__init__(batch_shape, validate_args=False) 69 new._validate_args = self._validate_args 70 return new 71 72 def rsample(self, sample_shape: _size = torch.Size()) -> torch.Tensor: 73 shape = self._extended_shape(sample_shape) 74 value = _standard_gamma(self.concentration.expand(shape)) / self.rate.expand( 75 shape 76 ) 77 value.detach().clamp_( 78 min=torch.finfo(value.dtype).tiny 79 ) # do not record in autograd graph 80 return value 81 82 def log_prob(self, value): 83 value = torch.as_tensor(value, dtype=self.rate.dtype, device=self.rate.device) 84 if self._validate_args: 85 self._validate_sample(value) 86 return ( 87 torch.xlogy(self.concentration, self.rate) 88 + torch.xlogy(self.concentration - 1, value) 89 - self.rate * value 90 - torch.lgamma(self.concentration) 91 ) 92 93 def entropy(self): 94 return ( 95 self.concentration 96 - torch.log(self.rate) 97 + torch.lgamma(self.concentration) 98 + (1.0 - self.concentration) * torch.digamma(self.concentration) 99 ) 100 101 @property 102 def _natural_params(self): 103 return (self.concentration - 1, -self.rate) 104 105 def _log_normalizer(self, x, y): 106 return torch.lgamma(x + 1) + (x + 1) * torch.log(-y.reciprocal()) 107 108 def cdf(self, value): 109 if self._validate_args: 110 self._validate_sample(value) 111 return torch.special.gammainc(self.concentration, self.rate * value) 112