Shortcuts

torch.distributions.negative_binomial 的源代码

```html
import torch
import torch.nn.functional as F
from torch.distributions import constraints
from torch.distributions.distribution import Distribution
from torch.distributions.utils import (
    broadcast_all,
    lazy_property,
    logits_to_probs,
    probs_to_logits,
)

__all__ = ["NegativeBinomial"]


[docs]class NegativeBinomial(Distribution): r""" 创建一个负二项分布,即在达到 :attr:`total_count` 次失败之前,独立且相同伯努利试验成功的次数的分布。每次伯努利试验成功的概率为 :attr:`probs`。 参数: total_count (float 或 Tensor): 非负的伯努利试验失败次数,尽管分布对于实数值的计数仍然有效 probs (Tensor): 事件成功的概率,在半开区间 [0, 1) logits (Tensor): 事件成功的概率对数 """ arg_constraints = { "total_count": constraints.greater_than_eq(0), "probs": constraints.half_open_interval(0.0, 1.0), "logits": constraints.real, } support = constraints.nonnegative_integer def __init__(self, total_count, probs=None, logits=None, validate_args=None): if (probs is None) == (logits is None): raise ValueError( "Either `probs` or `logits` must be specified, but not both." ) if probs is not None: ( self.total_count, self.probs, ) = broadcast_all(total_count, probs) self.total_count = self.total_count.type_as(self.probs) else: ( self.total_count, self.logits, ) = broadcast_all(total_count, logits) self.total_count = self.total_count.type_as(self.logits) self._param = self.probs if probs is not None else self.logits batch_shape = self._param.size() super().__init__(batch_shape, validate_args=validate_args)
[docs] def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(NegativeBinomial, _instance) batch_shape = torch.Size(batch_shape) new.total_count = self.total_count.expand(batch_shape) if "probs" in self.__dict__: new.probs = self.probs.expand(batch_shape) new._param = new.probs if "logits" in self.__dict__: new.logits = self.logits.expand(batch_shape) new._param = new.logits super(NegativeBinomial, new).__init__(batch_shape, validate_args=False) new._validate_args = self._validate_args return new
def _new(self, *args, **kwargs): return self._param.new(*args, **kwargs) @property def mean(self): return self.total_count * torch.exp(self.logits) @property def mode(self): return ((self.total_count - 1) * self.logits.exp()).floor().clamp(min=0.0) @property