pytorch
84 строки · 2.4 Кб
1from numbers import Number
2
3import torch
4from torch.distributions import constraints
5from torch.distributions.exp_family import ExponentialFamily
6from torch.distributions.utils import broadcast_all
7
8__all__ = ["Exponential"]
9
10
11class Exponential(ExponentialFamily):
12r"""
13Creates a Exponential distribution parameterized by :attr:`rate`.
14
15Example::
16
17>>> # xdoctest: +IGNORE_WANT("non-deterministic")
18>>> m = Exponential(torch.tensor([1.0]))
19>>> m.sample() # Exponential distributed with rate=1
20tensor([ 0.1046])
21
22Args:
23rate (float or Tensor): rate = 1 / scale of the distribution
24"""
25arg_constraints = {"rate": constraints.positive}
26support = constraints.nonnegative
27has_rsample = True
28_mean_carrier_measure = 0
29
30@property
31def mean(self):
32return self.rate.reciprocal()
33
34@property
35def mode(self):
36return torch.zeros_like(self.rate)
37
38@property
39def stddev(self):
40return self.rate.reciprocal()
41
42@property
43def variance(self):
44return self.rate.pow(-2)
45
46def __init__(self, rate, validate_args=None):
47(self.rate,) = broadcast_all(rate)
48batch_shape = torch.Size() if isinstance(rate, Number) else self.rate.size()
49super().__init__(batch_shape, validate_args=validate_args)
50
51def expand(self, batch_shape, _instance=None):
52new = self._get_checked_instance(Exponential, _instance)
53batch_shape = torch.Size(batch_shape)
54new.rate = self.rate.expand(batch_shape)
55super(Exponential, new).__init__(batch_shape, validate_args=False)
56new._validate_args = self._validate_args
57return new
58
59def rsample(self, sample_shape=torch.Size()):
60shape = self._extended_shape(sample_shape)
61return self.rate.new(shape).exponential_() / self.rate
62
63def log_prob(self, value):
64if self._validate_args:
65self._validate_sample(value)
66return self.rate.log() - self.rate * value
67
68def cdf(self, value):
69if self._validate_args:
70self._validate_sample(value)
71return 1 - torch.exp(-self.rate * value)
72
73def icdf(self, value):
74return -torch.log1p(-value) / self.rate
75
76def entropy(self):
77return 1.0 - torch.log(self.rate)
78
79@property
80def _natural_params(self):
81return (-self.rate,)
82
83def _log_normalizer(self, x):
84return -torch.log(-x)
85