torch.bernoulli() function

This function simply makes all the inputs into binary random numbers(0 or 1) from a Bernoulli Distribution. The output shape is same as the data inputted in the code.

Syntax-

torch.bernoulli(input, *, generator=None, out=None) → Tensor

Parameters-

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

Key Argument-

  • generator (torch.Generator, optional) – a pseudorandom number generator for sampling
  • out (Tensor, optional) – the output tensor.

Example:

In this example, let’s see a basic simple random generated shape and output it in Bernoulli distribution.

Python3




import torch
 
# this function will make a
# tensor of 5X5 array with
# random numbers
rand_matrix = torch.rand(5, 5)
 
print(rand_matrix)
 
# Bernoulli distribution
# this function will do the bernoulli
# distribution on the given matrix and
# form the new tensor
torch.bernoulli(rand_matrix)


Output:

tensor([[0.5010, 0.0622, 0.3710, 0.3325, 0.5136],

        [0.0790, 0.6433, 0.8819, 0.3770, 0.8236],

        [0.3458, 0.9933, 0.2282, 0.6544, 0.6823],

        [0.5454, 0.5916, 0.2471, 0.6174, 0.1676],

        [0.8980, 0.4162, 0.8114, 0.3744, 0.9957]])

tensor([[0., 0., 0., 0., 0.],

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

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

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

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

5 Statistical Functions for Random Sampling in PyTorch

PyTorch is an open source machine learning library used for deep learning with more flexibility and feasibility. This is an extension of NumPy.

For Statistical Functions for Random Sampling, let’s see what they are along with their easy implementations. To run all these the first step is to import Pytorch by import torch. There are 5 functions:

  • torch.bernoulli()
  • torch.normal()
  • torch.poisson()
  • torch.randn()
  • torch.randperm()

Similar Reads

1) torch.bernoulli() function:

This function simply makes all the inputs into binary random numbers(0 or 1) from a Bernoulli Distribution. The output shape is same as the data inputted in the code....

2) torch.normal() function :

...

3) torch.poisson() function :

This function works on the Normal Distribution theory. The function returns a tensor of random numbers in which the mean and the standard deviation is given. In this there are 2 parameters – a) mean – is a tensor with the mean of each output element’s normal distribution. b) std- tensor with a standard deviation...

4) torch.randn() function:

...

5) torch.randperm() function:

The output of this function is of the same size as the input with each element got from Poisson Distribution. This distribution shows how many times an event is likely to occur in the given time period....

Contact Us