如何在 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.