pytorch
80 строк · 2.4 Кб
1import torch2from torch.distributions import constraints3from torch.distributions.gamma import Gamma4from torch.distributions.transformed_distribution import TransformedDistribution5from torch.distributions.transforms import PowerTransform6
7
8__all__ = ["InverseGamma"]9
10
11class InverseGamma(TransformedDistribution):12r"""13Creates an inverse gamma distribution parameterized by :attr:`concentration` and :attr:`rate`
14where::
15
16X ~ Gamma(concentration, rate)
17Y = 1 / X ~ InverseGamma(concentration, rate)
18
19Example::
20
21>>> # xdoctest: +IGNORE_WANT("non-deterinistic")
22>>> m = InverseGamma(torch.tensor([2.0]), torch.tensor([3.0]))
23>>> m.sample()
24tensor([ 1.2953])
25
26Args:
27concentration (float or Tensor): shape parameter of the distribution
28(often referred to as alpha)
29rate (float or Tensor): rate = 1 / scale of the distribution
30(often referred to as beta)
31"""
32arg_constraints = {33"concentration": constraints.positive,34"rate": constraints.positive,35}36support = constraints.positive37has_rsample = True38
39def __init__(self, concentration, rate, validate_args=None):40base_dist = Gamma(concentration, rate, validate_args=validate_args)41neg_one = -base_dist.rate.new_ones(())42super().__init__(43base_dist, PowerTransform(neg_one), validate_args=validate_args44)45
46def expand(self, batch_shape, _instance=None):47new = self._get_checked_instance(InverseGamma, _instance)48return super().expand(batch_shape, _instance=new)49
50@property51def concentration(self):52return self.base_dist.concentration53
54@property55def rate(self):56return self.base_dist.rate57
58@property59def mean(self):60result = self.rate / (self.concentration - 1)61return torch.where(self.concentration > 1, result, torch.inf)62
63@property64def mode(self):65return self.rate / (self.concentration + 1)66
67@property68def variance(self):69result = self.rate.square() / (70(self.concentration - 1).square() * (self.concentration - 2)71)72return torch.where(self.concentration > 2, result, torch.inf)73
74def entropy(self):75return (76self.concentration77+ self.rate.log()78+ self.concentration.lgamma()79- (1 + self.concentration) * self.concentration.digamma()80)81