Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.randn function

PyTorch torch.randn function


PyTorch torch reference manual 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:

Return Value:


Usage examples

Example 1: Create a random tensor

Example

import

torch

Create a 3x4 random tensor

x

=

torch.

randn

(

3

,

4

)

print

(

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

)

print

(

"Weight shape:"

,

linear.

weight

.

shape

)

print

(

"Weight mean:"

,

linear.

weight

.

mean

(

)

.

item

(

)

)

print

(

"Weight standard deviation:"

,

linear.

weight

.

std

(

)

.

item

(

)

)


PyTorch torch reference manual PyTorch torch reference manual