5 Statistical Functions for Random Sampling in PyTorch

An short introduction about PyTorch and about the chosen functions.

  • torch.bernoulli()
  • torch.normal()
  • torch.poisson()
  • torch.randn()
  • torch.randperm()
# Import torch and other required modules
import torch

Function 1 - torch.bernoulli(input, *, generator=None, out=None)

It draws binary random numbers (0 or 1) from a Bernoulli distribution and the output is of the same shape as input.

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 1 - working
rand_m = torch.rand(4, 4) # generate a random matrix of shape 4x4
print(rand_m)

torch.bernoulli(rand_m) # draws a binary random number (0 or 1)
tensor([[0.0643, 0.0690, 0.5069, 0.0323], [0.3004, 0.6761, 0.1933, 0.7579], [0.2958, 0.8812, 0.2917, 0.3713], [0.8113, 0.0845, 0.9176, 0.9883]])
tensor([[0., 0., 1., 0.],
        [1., 1., 0., 1.],
        [0., 1., 0., 0.],
        [1., 1., 1., 1.]])

Draws a binary random number (0 or 1) for given random matrix.