pytorch
97 строк · 3.2 Кб
1# mypy: allow-untyped-defs
2from numbers import Number3
4import torch5from torch.distributions import constraints6from torch.distributions.distribution import Distribution7from torch.distributions.utils import broadcast_all8from torch.types import _size9
10
11__all__ = ["Laplace"]12
13
14class Laplace(Distribution):15r"""16Creates a Laplace distribution parameterized by :attr:`loc` and :attr:`scale`.
17
18Example::
19
20>>> # xdoctest: +IGNORE_WANT("non-deterministic")
21>>> m = Laplace(torch.tensor([0.0]), torch.tensor([1.0]))
22>>> m.sample() # Laplace distributed with loc=0, scale=1
23tensor([ 0.1046])
24
25Args:
26loc (float or Tensor): mean of the distribution
27scale (float or Tensor): scale of the distribution
28"""
29arg_constraints = {"loc": constraints.real, "scale": constraints.positive}30support = constraints.real31has_rsample = True32
33@property34def mean(self):35return self.loc36
37@property38def mode(self):39return self.loc40
41@property42def variance(self):43return 2 * self.scale.pow(2)44
45@property46def stddev(self):47return (2**0.5) * self.scale48
49def __init__(self, loc, scale, validate_args=None):50self.loc, self.scale = broadcast_all(loc, scale)51if isinstance(loc, Number) and isinstance(scale, Number):52batch_shape = torch.Size()53else:54batch_shape = self.loc.size()55super().__init__(batch_shape, validate_args=validate_args)56
57def expand(self, batch_shape, _instance=None):58new = self._get_checked_instance(Laplace, _instance)59batch_shape = torch.Size(batch_shape)60new.loc = self.loc.expand(batch_shape)61new.scale = self.scale.expand(batch_shape)62super(Laplace, new).__init__(batch_shape, validate_args=False)63new._validate_args = self._validate_args64return new65
66def rsample(self, sample_shape: _size = torch.Size()) -> torch.Tensor:67shape = self._extended_shape(sample_shape)68finfo = torch.finfo(self.loc.dtype)69if torch._C._get_tracing_state():70# [JIT WORKAROUND] lack of support for .uniform_()71u = torch.rand(shape, dtype=self.loc.dtype, device=self.loc.device) * 2 - 172return self.loc - self.scale * u.sign() * torch.log1p(73-u.abs().clamp(min=finfo.tiny)74)75u = self.loc.new(shape).uniform_(finfo.eps - 1, 1)76# TODO: If we ever implement tensor.nextafter, below is what we want ideally.77# u = self.loc.new(shape).uniform_(self.loc.nextafter(-.5, 0), .5)78return self.loc - self.scale * u.sign() * torch.log1p(-u.abs())79
80def log_prob(self, value):81if self._validate_args:82self._validate_sample(value)83return -torch.log(2 * self.scale) - torch.abs(value - self.loc) / self.scale84
85def cdf(self, value):86if self._validate_args:87self._validate_sample(value)88return 0.5 - 0.5 * (value - self.loc).sign() * torch.expm1(89-(value - self.loc).abs() / self.scale90)91
92def icdf(self, value):93term = value - 0.594return self.loc - self.scale * (term).sign() * torch.log1p(-2 * term.abs())95
96def entropy(self):97return 1 + torch.log(2 * self.scale)98