pytorch
128 строк · 4.5 Кб
1from numbers import Number2
3import torch4from torch.distributions import constraints5from torch.distributions.distribution import Distribution6from torch.distributions.utils import (7broadcast_all,8lazy_property,9logits_to_probs,10probs_to_logits,11)
12from torch.nn.functional import binary_cross_entropy_with_logits13
14__all__ = ["Geometric"]15
16
17class Geometric(Distribution):18r"""19Creates a Geometric distribution parameterized by :attr:`probs`,
20where :attr:`probs` is the probability of success of Bernoulli trials.
21
22.. math::
23
24P(X=k) = (1-p)^{k} p, k = 0, 1, ...
25
26.. note::
27:func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success
28hence draws samples in :math:`\{0, 1, \ldots\}`, whereas
29:func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`.
30
31Example::
32
33>>> # xdoctest: +IGNORE_WANT("non-deterministic")
34>>> m = Geometric(torch.tensor([0.3]))
35>>> m.sample() # underlying Bernoulli has 30% chance 1; 70% chance 0
36tensor([ 2.])
37
38Args:
39probs (Number, Tensor): the probability of sampling `1`. Must be in range (0, 1]
40logits (Number, Tensor): the log-odds of sampling `1`.
41"""
42arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}43support = constraints.nonnegative_integer44
45def __init__(self, probs=None, logits=None, validate_args=None):46if (probs is None) == (logits is None):47raise ValueError(48"Either `probs` or `logits` must be specified, but not both."49)50if probs is not None:51(self.probs,) = broadcast_all(probs)52else:53(self.logits,) = broadcast_all(logits)54probs_or_logits = probs if probs is not None else logits55if isinstance(probs_or_logits, Number):56batch_shape = torch.Size()57else:58batch_shape = probs_or_logits.size()59super().__init__(batch_shape, validate_args=validate_args)60if self._validate_args and probs is not None:61# Add an extra check beyond unit_interval62value = self.probs63valid = value > 064if not valid.all():65invalid_value = value.data[~valid]66raise ValueError(67"Expected parameter probs "68f"({type(value).__name__} of shape {tuple(value.shape)}) "69f"of distribution {repr(self)} "70f"to be positive but found invalid values:\n{invalid_value}"71)72
73def expand(self, batch_shape, _instance=None):74new = self._get_checked_instance(Geometric, _instance)75batch_shape = torch.Size(batch_shape)76if "probs" in self.__dict__:77new.probs = self.probs.expand(batch_shape)78if "logits" in self.__dict__:79new.logits = self.logits.expand(batch_shape)80super(Geometric, new).__init__(batch_shape, validate_args=False)81new._validate_args = self._validate_args82return new83
84@property85def mean(self):86return 1.0 / self.probs - 1.087
88@property89def mode(self):90return torch.zeros_like(self.probs)91
92@property93def variance(self):94return (1.0 / self.probs - 1.0) / self.probs95
96@lazy_property97def logits(self):98return probs_to_logits(self.probs, is_binary=True)99
100@lazy_property101def probs(self):102return logits_to_probs(self.logits, is_binary=True)103
104def sample(self, sample_shape=torch.Size()):105shape = self._extended_shape(sample_shape)106tiny = torch.finfo(self.probs.dtype).tiny107with torch.no_grad():108if torch._C._get_tracing_state():109# [JIT WORKAROUND] lack of support for .uniform_()110u = torch.rand(shape, dtype=self.probs.dtype, device=self.probs.device)111u = u.clamp(min=tiny)112else:113u = self.probs.new(shape).uniform_(tiny, 1)114return (u.log() / (-self.probs).log1p()).floor()115
116def log_prob(self, value):117if self._validate_args:118self._validate_sample(value)119value, probs = broadcast_all(value, self.probs)120probs = probs.clone(memory_format=torch.contiguous_format)121probs[(probs == 1) & (value == 0)] = 0122return value * (-probs).log1p() + self.probs.log()123
124def entropy(self):125return (126binary_cross_entropy_with_logits(self.logits, self.probs, reduction="none")127/ self.probs128)129