PyTorch torch.zeros_like() method “returns a tensor filled with the scalar value 0, the same size as the input.”
Syntax
torch.zeros_like(input, *, dtype=None, layout=None, device=None,
requires_grad=False, memory_format=torch.preserve_format)
Parameters
- input: The input tensor whose properties (size, dtype, etc.) will be used to create the output tensor.
- dtype: Overrides the data type of the result tensor. The default is None.
- layout: Overrides the layout of the result tensor. The default is None.
- device: Overrides the device of the result tensor. The default is None.
- requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.
- memory_format: The desired memory format of the returned Tensor. Default: torch.preserve_format.
Example 1: Creating a Tensor of Zeros with the Same Properties as Another Tensor
import torch
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor1 = torch.zeros_like(x)
print(tensor1)
Output
tensor([[0, 0, 0],
[0, 0, 0]])
Example 2: Creating a Tensor of Zeros with the Same Shape but Different Dtype
import torch
x = torch.tensor([1.0, 2.0, 3.0])
tensor2 = torch.zeros_like(x, dtype=torch.int32)
print(tensor2)
Output
tensor([0, 0, 0], dtype=torch.int32)
Example 3: Creating a Tensor of Zeros with Gradient Tracking Enabled
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
tensor3 = torch.zeros_like(x, requires_grad=True)
print(tensor3)
Output
tensor([0., 0., 0.], requires_grad=True)
That’s it!
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.