PyTorch .normal()
Published Feb 21, 2025
Contribute to Docs
In PyTorch, the .normal() function is used to generate a tensor of random numbers from a normal (Gaussian) distribution, given the mean and standard deviation. It is useful in scenarios where there is a need to sample from a normal distribution for tasks such as initializing neural network weights, generating synthetic data, or adding noise.
Syntax
torch.normal(mean, std, *, gen=None, out=None)
mean: A tensor containing the means of the normal distribution.std: A tensor containing the standard deviations of the normal distribution.gen(Optional): A pseudorandom number generator for sampling.out(Optional): A tensor where the output will be stored in-place.
Example
The following example demonstrates the usage of the .normal() function:
import torch# Create tensors containing means and standard deviationsmean = torch.tensor([0.1, 0.4, 0.7])std = torch.tensor([0.2, 0.5, 0.8])# Generate samples from the normal distributionres = torch.normal(mean, std)# Print the resultant tensorprint(res)
The above code produces the following output:
tensor([0.3012, 0.3419, 1.6109])
Note: Since the
.normal()function generates a tensor of random numbers from the normal distribution, the output may vary each time the code is run.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
- Intermediate.3 hours