SoFunction
Updated on 2025-03-02

How to create a normal distributed random number in PyTorch

()How to create a normal distributed random number

(*size) Gets a random number from a normal distribution with mean of 0 and variance of 1

【sample】

In [1]: import torch
In [2]: (3)
Out[2]: tensor([1.7896, 0.7974, 0.7416])
In [3]: (2,3)
Out[3]: tensor([[ 0.4030, -0.3138, -0.7579],
        [-0.1486,  1.0306,  0.0734]])
In [4]: (())
Out[4]: tensor(-0.8383) # The dimension is0

Torch's random number generation method

()    

()

()

()

1. Even distribution

(*sizes, out=None) → Tensor

Returns a tensor containing a set of random numbers extracted from the uniform distribution of intervals [0, 1). The shape of a tensor is defined by the parameter sizes.

parameter:

  • sizes (int...)- Integer sequence, defining the shape of the output tensor
  • out (Tensor, optinal)- Result Tensor

example:

(2, 3)
0.0836 0.6151 0.6958
0.6998 0.2560 0.0139
[ of size 2x3]

2. Standard normal distribution

(*sizes, out=None) → Tensor

Returns a tensor containing a set of random numbers extracted from a standard normal distribution (mean value is 0, variance is 1, i.e. Gaussian white noise). The shape of a tensor is defined by the parameter sizes.

parameter:

  • sizes (int...)- Integer sequence, defining the shape of the output tensor
  • out (Tensor, optinal)- Result Tensor

example:

(2, 3)
0.5419 0.1594 -0.0413
-2.7937 0.9534 0.4561
[ of size 2x3]

3. Discrete normal distribution

(means, std, out=None) → → Tensor

Returns a tensor containing a set of random numbers extracted from a discrete normal distribution of the specified mean means and standard deviation std.

The standard deviation std is a tensor containing the standard deviation of the normal distribution associated with each output element.

parameter:

  • means (float, optional)- Mean
  • std (Tensor)- Standard deviation
  • out (Tensor)- Output tensor

example:

(mean=0.5, std=(1, 6))
-0.1505
-1.2949
-4.4880
-0.5697
-0.8996
[ of size 5]

4. Linear spacing vector

(start, end, steps=100, out=None) → Tensor

Returns a 1-dimensional tensor containing evenly spaced step points on intervals start and end.

The length of the output tensor is determined by steps.

parameter:

  • start (float)- The starting point of the interval
  • end (float)- End point of interval
  • steps (int)- Number of samples generated between start and end
  • out (Tensor, optional)- Result Tensor

example:

(3, 10, steps=5)
3.0000
4.7500
6.5000
8.2500
10.0000
[ of size 5]

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.