Rate this Page

torch.bernoulli#

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

Draws binary random numbers (0 or 1) from a Bernoulli distribution.

Theinput tensor should be a tensor containing probabilitiesto be used for drawing the binary random number.Hence, all values ininput have to be in the range:0inputi10 \leq \text{input}_i \leq 1.

Theith\text{i}^{th} element of the output tensor will draw avalue11 according to theith\text{i}^{th} probability value givenininput.

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

The returnedout tensor only has values 0 or 1 and is of the sameshape asinput.

out can have integraldtype, butinput must have floatingpointdtype.

Parameters

input (Tensor) – the input tensor of probability values for the Bernoulli distribution

Keyword Arguments
  • generator (torch.Generator, optional) – a pseudorandom number generator for sampling

  • out (Tensor,optional) – the output tensor.

Example:

>>>a=torch.empty(3,3).uniform_(0,1)# generate a uniform random matrix with range [0, 1]>>>atensor([[ 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.]])