评价此页

torch.bernoulli#

torch.bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) Tensor#

从伯努利分布中抽取二元随机数(0 或 1)。

input 张量应是包含用于抽取二元随机数的概率值的张量。因此,input 中的所有值都必须在以下范围内:0inputi10 \leq \text{input}_i \leq 1

输出张量的第 ith\text{i}^{th} 个元素将根据 input 中给定的第 ith\text{i}^{th} 个概率值抽取一个值 11

outiBernoulli(p=inputi)\text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i})

返回的 out 张量只包含 0 或 1 值,并且形状与 input 相同。

out 可以具有整型 dtype,但 input 必须具有浮点 dtype

参数

input (Tensor) – 伯努利分布的概率值输入张量

关键字参数
  • generator (torch.Generator, 可选) – 用于采样的伪随机数生成器

  • out (Tensor, optional) – 输出张量。

示例

>>> a = torch.empty(3, 3).uniform_(0, 1)  # generate a uniform random matrix with range [0, 1]
>>> a
tensor([[ 0.1737,  0.0950,  0.3609],
        [ 0.7148,  0.0289,  0.2676],
        [ 0.9456,  0.8937,  0.7202]])
>>> torch.bernoulli(a)
tensor([[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 1.,  1.,  1.]])

>>> a = torch.ones(3, 3) # probability of drawing "1" is 1
>>> torch.bernoulli(a)
tensor([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])
>>> a = torch.zeros(3, 3) # probability of drawing "1" is 0
>>> torch.bernoulli(a)
tensor([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])