PyTorch torch.randn() Method

PyTorch torch.randn() method “returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1.”

Syntax

torch.randn(*size, *, out=None, dtype=None, layout=torch.strided, 
            device=None, requires_grad=False, pin_memory=False)

Parameters

  1. size (int…): A sequence of integers defining the shape of the output tensor.
  2. out (Tensor, optional): It is the output tensor.
  3. dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: If none, use a global default.
  4. layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
  5. device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
  6. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.

Example 1: How to Use the torch.randn() method

import torch

rand_tensor = torch.randn(3, 3)
print(rand_tensor)

Output

tensor([[ 0.2211, 0.1781, 0.3264],
        [ 0.3594, -0.3114, -0.8456],
        [-1.6676, -0.2437, -0.3796]])

Example 2: Generating a 3D tensor

In this example, we’ll generate a 3D tensor with a shape (2, 2, 3).

import torch

rand_tensor_3d = torch.randn(2, 2, 3)
print(rand_tensor_3d)

Output

Generating a 3D tensor

Example 3: Using dtype and device parameters

Here, we’ll generate a tensor of shape (4, 4) with data type as torch.float64 (double precision) and place it on the cuda device (assuming you have a GPU).

import torch

# Check if CUDA is available, if not, use CPU
device = 'cuda' if torch.cuda.is_available() else 'cpu'

rand_tensor_double_on_cuda = torch.randn(4, 4, dtype=torch.float64, device=device)
print(rand_tensor_double_on_cuda)

Output

Using dtype and device parameters

That’s it!

Related posts

torch.stack()

torch.cat()

torch.matmul()

torch.split()

torch.unsqueeze()

torch.nn.Conv2d()

Leave a Comment