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.
Syntax
torch.randn_like(input, dtype=None, layout=None,
device=None, requires_grad=False)
Parameters
- input (Tensor): The size of the output tensor will be inferred from this tensor.
- dtype (optional): The desired data type of returned tensor. Default: if None, use a global default (e.g., torch.float32).
- layout (optional): The desired layout of the returned tensor. Default: if None, defaults to the layout of input.
- device (optional): The desired device of returned tensor. Default: if None, use the current device for the default tensor type.
- 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)
print(random_tensor)
Output
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)
print(random_tensor)
Output
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(random_tensor)
print("Requires gradient:", random_tensor.requires_grad)
Output
tensor([[-0.1987, 1.0235, -0.8507],
[ 0.5298, 1.4625, -1.6958]], requires_grad=True)
Requires gradient: True
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.