如何在 PyTorch 中从伯努利分布中抽取二进制随机数(0 或 1)?


要从伯努利分布中抽取二进制随机数(0 或 1),我们应用 **torch.bernoulli()** 方法。此方法的输入是一个 torch 张量,包含抽取 1 的概率。这些概率用于抽取二进制随机数(0 或 1)。

由于输入张量包含概率,因此所有元素都应在 [0,1] 范围内。它返回一个张量,其元素(0 或 1)是从具有输入概率的伯努利分布中随机选择的。

语法

torch.bernoulli(input)

其中,参数 **input** 是一个 torch 张量,包含抽取 1 的概率。这些概率用于从伯努利分布中抽取元素。

步骤

我们可以使用以下步骤从伯努利分布中抽取二进制随机数(0 或 1):

  • 导入所需的库。在以下所有示例中,所需的 Python 库是 **torch**。确保你已安装它。

import torch
  • 定义一个概率的 torch 张量 **input**。我们将 **input** 元素定义在 0 和 1 之间。

input = torch.randn(5,5).uniform_(0,1)
  • 计算 **torch.bernoulli(input)** 以从伯努利分布中抽取二进制随机数(0 或 1)。

random_numbers = torch.bernoulli(input)
  • 打印计算出的随机数张量。

print(random_numbers)

示例 1

import torch

# define tensor containing the probabilities to be
# used for drawing the binary random number.
t = torch.randn(5,5).uniform_(0,1)
print(t)

# generate random numbers (0,1) from Bernoulli
# distribution using above probabilities
random_numbers = torch.bernoulli(t)
print(random_numbers)

输出

tensor([[0.0080, 0.2254, 0.2143, 0.8664, 0.9297],
   [0.5881, 0.7574, 0.9916, 0.6557, 0.7281],
   [0.0656, 0.9466, 0.6378, 0.1693, 0.3333],
   [0.9914, 0.9468, 0.6381, 0.6448, 0.4003],
   [0.4401, 0.1261, 0.0787, 0.9409, 0.2434]])
tensor([[0., 0., 0., 0., 1.],
   [0., 1., 1., 1., 1.],
   [0., 1., 1., 1., 0.],
   [1., 1., 0., 1., 0.],
   [0., 0., 0., 1., 0.]])

请注意,我们使用 **.uniform_(0,1)** 生成概率的输入张量。它生成 [0,1] 范围内的数字。

示例 2

# Import the required library
import torch
# define tensor containing the probabilities to be
# used for drawing the binary random number.
t = torch.randn(2,4,4).uniform_(0,1)
print(t)

# generate random numbers (0,1) from Bernoulli
# distribution using above probabilities
random_numbers = torch.bernoulli(t)
print(random_numbers)

输出

tensor([[[0.5937, 0.5897, 0.9741, 0.2749],
   [0.5659, 0.9343, 0.7971, 0.4183],
   [0.4684, 0.4700, 0.0858, 0.1492],
   [0.9859, 0.4440, 0.0871, 0.4186]],

   [[0.1498, 0.5788, 0.7917, 0.4689],
   [0.2375, 0.7465, 0.0773, 0.3620],
   [0.6607, 0.0263, 0.4370, 0.9952],
   [0.0920, 0.5408, 0.7088, 0.2246]]])
tensor([[[1., 1., 1., 0.],
   [1., 1., 1., 0.],
   [0., 1., 0., 0.],
   [1., 0., 0., 1.]],

   [[0., 1., 1., 0.],
   [0., 0., 0., 0.],
   [1., 0., 1., 1.],
   [0., 0., 0., 0.]]])

示例 3

import torch
a = torch.ones(3, 3) # probability of drawing "1" is 1
print(a)
print(torch.bernoulli(a))

b = torch.zeros(3, 3) # probability of drawing "1" is 0
print(b)
print(torch.bernoulli(b))

输出

tensor([[1., 1., 1.],
   [1., 1., 1.],
   [1., 1., 1.]])
tensor([[1., 1., 1.],
   [1., 1., 1.],
   [1., 1., 1.]])
tensor([[0., 0., 0.],
   [0., 0., 0.],
   [0., 0., 0.]])
tensor([[0., 0., 0.],
   [0., 0., 0.],
   [0., 0., 0.]])

更新于: 2022年1月27日

1K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.