Learn practical skills, build real-world projects, and advance your career

Top 5 Statistical Functions in PyTorch to Rule in Data Science

PyTorch is an open source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing, primarily developed by Facebook's AI Research lab. In this notebook, for each function three examples are given. Out of which the first two examples work perfectly and the last one shows an error.

  • function 1: torch.bernoulli()
  • function 2: torch.multinomial()
  • function 3: torch.poisson()
  • function 4: torch.normal()
  • function 5: torch.randn()
# Import torch library
import torch

Function 1 - torch.bernoulli()

This function can easily generate binary random numbers (0 or 1) using the Bernoulli Distribution. The input should be a tensor containing probabilities to be used to draw the binary random numbers. Uniform Distribution is applied to generate probabilities.

# Example 1 

# Generate a uniform random matrix with range [0, 1]
a = torch.empty(4, 4).uniform_(0, 1)
print(a)

# Apply torch.bernoulli() to generate binary random numbers
torch.bernoulli(a)
tensor([[0.2611, 0.3850, 0.0344, 0.9343], [0.1265, 0.9931, 0.4137, 0.9732], [0.7244, 0.0056, 0.9736, 0.5632], [0.2036, 0.2579, 0.8645, 0.3188]])
tensor([[1., 0., 0., 1.],
        [0., 1., 0., 1.],
        [1., 0., 1., 1.],
        [0., 0., 1., 0.]])

In the above example, we can see using uniform_(0,1) function we have generated a sqaure matrix of order 4. The elements are probabilities and hence belongs to the range [0,1]. Applying torch.bernoulli() on a, we obtained a matrix whose elements are binary random numbers.