Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a normal distribution in pytorch

I want to create a random normal distribution with a given mean and std.

like image 510
dq.shen Avatar asked Jul 02 '18 12:07

dq.shen


People also ask

How do you create a normal distribution in Python PyTorch?

To create a tensor of random numbers drawn from separate normal distributions whose mean and std are given, we apply the torch. normal() method. This method takes two input parameters − mean and std. std is a tensor with the standard deviation of each output element's normal distribution.

What is Torch normal?

Returns a tensor of random numbers drawn from separate normal distributions whose mean and standard deviation are given. The mean is a tensor with the mean of each output element's normal distribution.

How do you generate a random sample from a normal distribution in Python?

This distribution is also called the Bell Curve this is because of its characteristics shape. To generate five random numbers from the normal distribution we will use numpy. random. normal() method of the random module.

What is Torch Randn?

PyTorch torch. randn() returns a tensor defined by the variable argument size (sequence of integers defining the shape of the output tensor), containing random numbers from standard normal distribution.


2 Answers

You can easily use torch.Tensor.normal_() method.

Let's create a matrix Z (a 1d tensor) of dimension 1 × 5, filled with random elements samples from the normal distribution parameterized by mean = 4 and std = 0.5.

torch.empty(5).normal_(mean=4,std=0.5)

Result:

tensor([4.1450, 4.0104, 4.0228, 4.4689, 3.7810])
like image 134
Furkan Avatar answered Sep 20 '22 17:09

Furkan


For a standard normal distribution (i.e. mean=0 and variance=1), you can use torch.randn()

For your case of custom mean and std, you can use torch.distributions.Normal()


Init signature:
tdist.Normal(loc, scale, validate_args=None)

Docstring:
Creates a normal (also called Gaussian) distribution parameterized by loc and scale.

Args:
loc (float or Tensor): mean of the distribution (often referred to as mu)
scale (float or Tensor): standard deviation of the distribution (often referred to as sigma)


Here's an example:

In [32]: import torch.distributions as tdist

In [33]: n = tdist.Normal(torch.tensor([4.0]), torch.tensor([0.5]))

In [34]: n.sample((2,))
Out[34]: 
tensor([[ 3.6577],
        [ 4.7001]])
like image 44
kmario23 Avatar answered Sep 19 '22 17:09

kmario23