Shortcuts

torch.bernoulli

torch.bernoulli(input, *, generator=None, out=None) 张量

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

The 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

Parameters

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

Keyword Arguments
  • 生成器 (torch.Generator, 可选) – 用于采样的伪随机数生成器

  • 输出 (张量, 可选) – 输出张量。

示例:

>>> a = torch.empty(3, 3).uniform_(0, 1)  # 生成一个范围在[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) # 抽取“1”的概率为1
>>> torch.bernoulli(a)
tensor([[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]])
>>> a = torch.zeros(3, 3) # 抽取“1”的概率为0
>>> torch.bernoulli(a)
tensor([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])