torch.distributions.binomial 的源代码
```html
import torch 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__ = ["Binomial"] def _clamp_by_zero(x): # 类似于 clamp(x, min=0) 但 grad 在 0 处为 0.5 return (x.clamp(min=0) + x - x.clamp(max=0)) / 2[docs]class Binomial(Distribution): r""" 创建一个由 :attr:`total_count` 和 :attr:`probs` 或 :attr:`logits`(但不能同时使用两者)参数化的二项分布。:attr:`total_count` 必须与 :attr:`probs`/:attr:`logits` 广播兼容。 示例:: >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> m = Binomial(100, torch.tensor([0 , .2, .8, 1])) >>> x = m.sample() tensor([ 0., 22., 71., 100.]) >>> m = Binomial(torch.tensor([[5.], [10.]]), torch.tensor([0.5, 0.8])) >>> x = m.sample() tensor([[ 4., 5.], [ 7., 6.]]) 参数: total_count (int 或 Tensor): 伯努利试验次数 probs (Tensor): 事件概率 logits (Tensor): 事件对数几率 """ arg_constraints = { "total_count": constraints.nonnegative_integer, "probs": constraints.unit_interval, "logits": constraints.real, } has_enumerate_support = True def __init__(self, total_count=1, 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(Binomial, _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(Binomial, new).__init__(batch_shape, validate_args=False) new._validate_args = self._validate_args return newdef _new(self, *args, **kwargs): return self._param.new(*args, **kwargs) @constraints.dependent_property(is