Usage of torch.rand() and torch.randn()

1. Similarities

torch.rand() and torch.randn() are both functions used to generate random tensors.

2. Differences

1.torch.rand() generates random numbers uniformly distributed  within the interval [0, 1) , also It can be said that the elements in the generated tensor conform to a uniform distribution.

  Parameter size: tuple or integer of desired tensor shape.

import torch

x = torch.rand(2, 3)
print(x)
-------------------------------
tensor([[0.2755, 0.6407, 0.1348],
        [0.7009, 0.3745, 0.3707]])

2.torch.randn() generates random numbers sampled from the standard normal distribution (mean 0, standard deviation 1). It can also be said that the elements in the generated tensor conform to the standard normal distribution.

   Parameter size: a tuple or integer of the desired tensor shape.

import torch

x = torch.randn(2, 3)
print(x)
-------------------------------------
tensor([[-0.7634,  0.4938,  2.0363],
        [-0.0975,  1.8824,  2.0274]])

3. Attention

Since torch.randn generates random numbers sampled from the standard normal distribution, its value can range from negative infinity to positive infinity, while torch.rand The generated random number range is within [0, 1) .

Random numbers uniformly distributed within the interval [0, 1) is a random number generation method in which the generated random numbers are any value within the interval [0, 1) all have the same probability distribution. This means that any value within [0, 1) may be generated, including all real values. Therefore, the generated random numbers can be decimals, not just integers

Guess you like

Origin blog.csdn.net/m0_62278731/article/details/134327305