PyTorch torch.randn_like() Method

The torch.randn_like() method returns a tensor the same size as input filled with random numbers from a normal distribution with mean 0 and variance 1.


torch.randn_like(input, dtype=None, layout=None, 
                 device=None, requires_grad=False)


  1. input (Tensor): The size of the output tensor will be inferred from this tensor.
  2. dtype (optional): The desired data type of returned tensor. Default: if None, use a global default (e.g., torch.float32).
  3. layout (optional): The desired layout of the returned tensor. Default: if None, defaults to the layout of input.
  4. device (optional): The desired device of returned tensor. Default: if None, use the current device for the default tensor type.
  5. requires_grad (bool, optional):  If autograd should record operations on the returned tensor. Default: False.

Example 1: How to Use torch.randn_like() method

import torch

# Create an example tensor
tensor = torch.tensor([[1, 2], [3, 4], [5, 6]], dtype=torch.float32)

random_tensor = torch.randn_like(tensor)



tensor([[-1.0836, 0.9345],
       [ 0.9256, 0.4192],
       [-0.4720, 0.1222]])

Example 2: Using dtype and device parameters

import torch

# Create an example tensor on CPU
tensor = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)

device = 'cuda' if torch.cuda.is_available() else 'cpu'

random_tensor = torch.randn_like(tensor, dtype=torch.float64, device=device)



tensor([[ 0.3059, 0.1648],
       [-0.1239, -1.3309]], dtype=torch.float64)

Example 3: Using the requires_grad parameter

import torch

# Create an example tensor
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)

random_tensor = torch.randn_like(tensor, requires_grad=True)

print("Requires gradient:", random_tensor.requires_grad)


tensor([[-0.1987, 1.0235, -0.8507],
        [ 0.5298, 1.4625, -1.6958]], requires_grad=True)

Requires gradient: True

Related posts




Leave a Comment