PyTorch torch.randn Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.randnis a function in PyTorch used to create a random tensor from the standard normal distribution (a Gaussian distribution with mean 0 and variance 1).

This is often used in deep learning for scenarios such as initializing weights and generating random inputs.

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, defaults totorch.float32。
  • device(torch.device, optional): Device.
  • requires_grad(bool, optional): Whether gradient computation is needed.

Return Value:

  • torch.Tensor: Returns a tensor containing random numbers.

Usage Examples

Example 1: Create 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

# Use randn to initialize neural network weights
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 参考手册Pytorch torch Reference Manual

Other Extensions