# torch.normal() Method in Python PyTorch

PyTorchServer Side ProgrammingProgramming

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.

• mean is a tensor with the mean of each output element’s normal distribution, and

• std is a tensor with the standard deviation of each output element’s normal distribution.

It returns a tensor of random numbers drawn from separate normal distributions whose mean and standard deviation are mean and std.

### Syntax

torch.normal(mean, std)

### Steps

We could use the following steps to create a tensor of random numbers drawn from separate normal distributions −

• Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it.

import torch
• Define two torch tensors − mean and std. The number of elements in both the tensors must be the same.

mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)
• Compute the tensor of random numbers drawn from separate normal distributions with the given mean and std.

tensor = torch.normal(mean, std)
• Print the computed tensor of random numbers.

print("Tensor:\n",tensor)

## Example 1

# torch.normal(mean, std, *, generator=None, out=None) → Tensor
import torch

# define mean and std
mean=torch.arange(1., 11.)
std=torch.arange(1, 0, -0.1)

# print mean and std
print("Mean:\n", mean)
print("STD:\n", std)

# compute the tensor of random numbers
tensor = torch.normal(mean, std)

# print the computed tensor
print("Tensor:\n",tensor)

## Output

Mean:
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
STD:
tensor([1.0000, 0.9000, 0.8000, 0.7000, 0.6000, 0.5000,0.4000, 0.3000, 0.2000,
0.1000])
Tensor:
tensor([ 0.8557, 1.1373, 2.5573, 3.3513, 4.3764, 5.4221, 6.5343, 7.9068,
8.6984, 10.1292])

Notice in the above example, both the mean and std are given and the elements on both the tensors are same.

## Example 2

# torch.normal(mean=0.0, std, *, out=None) → Tensor
import torch
tensor = torch.normal(mean=0.5, std=torch.arange(1., 6.))
print(tensor)

## Output

tensor([ 0.4357, 1.1931, 2.8821, -2.3777, -1.8948])

Notice that in the above example, the mean is shared along all drawn elements.

## Example 3

# torch.normal(mean, std=1.0, *, out=None) → Tensor
import torch
tensor = torch.normal(mean=torch.arange(1., 6.))
print(tensor)

## Output

tensor([1.3951, 2.0769, 2.4525, 3.6972, 7.7257])

Notice that in the above example, the standard deviation is given as a parameter. Here, the default std is set to 1. The std is shared along all drawn elements.

## Example 4

# torch.normal(mean, std, size, *, out=None) → Tensor
import torch
tensor = torch.normal(2, 3, size=(1, 4))
print(tensor)

## Output

tensor([1.3951, 2.0769, 2.4525, 3.6972, 7.7257])

Notice that in the above example, the mean and the standard deviations are shared among all drawn elements.