The torch.empty_like() method returns an uninitialized tensor the same size as input. torch.empty_like(input) is equivalent to torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device).
Syntax
torch.empty_like(input, *, dtype=None, layout=None, device=None,
requires_grad=False, memory_format=torch.preserve_format)
Parameters
- input (Tensor): The input tensor whose shape will be used to define the shape of the output tensor.
- dtype (torch.dtype, optional): The desired data type of the output tensor.
- layout (torch.layout, optional): The desired layout of the output tensor.
- device (torch.device, optional): The desired device of the output tensor.
- requires_grad (bool, optional): If True, the resulting tensor will require a gradient.
- memory_format (torch.memory_format, optional): Specifies the memory format of the produced tensor.
Example 1: How to Use torch.empty_like() method
import torch
# Create a tensor
tensor = torch.tensor([[1, 2], [3, 4]])
# Use empty_like to create a new tensor with the same shape
empty_tensor = torch.empty_like(tensor)
print(empty_tensor)
Output
tensor([[0, 0],
[0, 0]])
This will produce a tensor with the same shape as the tensor but with uninitialized values.
Example 2: Basic usage of the torch.empty_like()
import torch
# Create a tensor
tensor_1 = torch.tensor([[1, 2], [3, 4], [5, 6]])
# Use empty_like to create a new tensor with the same shape
empty_tensor_1 = torch.empty_like(tensor_1)
print("Original Tensor:")
print(tensor_1)
print("\nEmpty Tensor with Same Shape:")
print(empty_tensor_1)
Output
Example 3: Using additional parameters with a torch.empty_like()
import torch
# Create a tensor of float type
tensor_2 = torch.tensor([[1.1, 2.2], [3.3, 4.4]], dtype=torch.float32)
# Use empty_like to create a new tensor with the same shape but different dtype
empty_tensor_2 = torch.empty_like(tensor_2, dtype=torch.int64)
print("Original Tensor:")
print(tensor_2)
print("\nEmpty Tensor with Same Shape but Different Dtype:")
print(empty_tensor_2)
Output
Original Tensor:
tensor([[1.1000, 2.2000],
[3.3000, 4.4000]])
Empty Tensor with Same Shape but Different Dtype:
tensor([[0, 0],
[0, 0]])
Conclusion
PyTorch torch.empty_like() method is “used to create a new tensor with the same shape as the input tensor but without initializing the values.”
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.