The normal distribution is the most commonly used probability distribution in statistics. It is Symmetrical and Bell-shaped. If we create a plot of the normal distribution, it will look something like this:

PyTorch Normal Distribution

Normal Distribution is a probability distribution where the probability of x is highest at the center and lowest at the ends.

PyTorch has a number of built-in distributions. You can build a tensor of the desired shape with elements drawn from a distribution. Use the torch.distributions package to generate samples from different distributions.

For example, try the following sample code to sample a 2d PyTorch tensor of size [a,b] from a Normal distribution.

import torch

m = torch.distributions.normal.Normal(torch.tensor(0.0), torch.tensor(1.0))
m.sample(sample_shape=(10,2))  # normally distributed with loc=0 and scale=1

#output
tensor([[-0.8596,  0.4606],
        [ 0.5337, -0.5248],
        [ 0.0535, -0.2472],
        [-1.5757, -0.3661],
        [-0.8937, -1.4933],
        [ 0.5081,  0.9339],
        [-0.8493,  0.9772],
        [-0.0069, -0.2202],
        [ 0.0538, -1.4181],
        [ 1.0918,  0.8666]])

Creates a normal or Gaussian distribution parameterized by loc: the mean of the distribution and scale: the standard deviation of the distribution.sample() generates a sample_shape of the sample.

Uniform Distribution

The uniform distribution is a probability distribution in which every value between an interval from a to b is equally likely to occur. It has Symmetrical and Rectangular-shaped. If we create a plot of the uniform distribution, it will look something like this:

PyTorch Uniform Distribution

Uniform distribution is a probability distribution where the probability of x is constant. Let’s create a matrix of dimension 10 × 2, filled with random elements samples from the Uniform distribution parameterized by low = 0.0 and high = 5.0.

m = torch.distributions.uniform.Uniform(low=torch.tensor([0.0]),high=torch.tensor([5.0]))
m.sample(sample_shape=(10,2)).numpy()  # uniformly distributed in the range [0.0, 5.0)

Generates uniformly distributed random samples from the half-open interval.

  • low – lower range (inclusive).
  • high – upper range (exclusive).

Plot Uniform Distribution

import seaborn as sns

sns.set()

m = torch.distributions.uniform.Uniform(low=torch.tensor([0.0]),high=torch.tensor([5.0]))
uniform_dis=m.sample(sample_shape=([100000])).numpy()  # uniformly distributed in the range [0.0, 5.0)

sns.displot(uniform_dis, kind='kde')

Both distributions are symmetrical. That is, if we were to draw a line down the distribution’s center, the distribution’s left and right sides would perfectly mirror each other.

Related Post