PyTorch torch.randn function
PyTorch torch reference manual
torch.randn is a function in PyTorch used to create a random tensor from a standard normal distribution (a Gaussian distribution with mean 0 and variance 1).
This is commonly used in deep learning for initializing weights, generating random inputs, and similar scenarios.
Function definition
torch.randn(*size, dtype=None, device=None, requires_grad=False)
Parameters:
*size(int): The shape of the tensor.dtype(torch.dtype, optional): Data type, default istorch.float32.device(torch.device, optional): Device.requires_grad(bool, optional): Whether gradients need to be computed.
Return Value:
torch.Tensor: Returns a tensor containing random numbers.
Usage examples
Example 1: Create a random tensor
Example
import
torch
Create a 3x4 random tensor
x
=
torch.
randn
(
3
,
4
)
(
x
)
The output is:
tensor([[-0.2107, -0.6198, 0.2103, 0.4513],
[-0.0124, -1.1746, 0.1844, -0.6199],
[ 1.1729, -0.7669, 0.3034, -0.0808]])
Example 2: Neural network weight initialization
Example
import
torch
import
torch.
nn
as
nn
Initialize neural network weights with randn
linear
=
nn.
Linear
(
10
,
5
)
Initialize weights with random values
nn.
init
.
randn_
(
linear.
weight
)
nn.
init
.
zeros_
(
linear.
bias
)
(
"Weight shape:"
,
linear.
weight
.
shape
)
(
"Weight mean:"
,
linear.
weight
.
mean
(
)
.
item
(
)
)
(
"Weight standard deviation:"
,
linear.
weight
.
std
(
)
.
item
(
)
)