PyTorch torch.zeros_like() method “returns a tensor filled with the scalar value 0, the same size as the input.”
torch.zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format)
- 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)
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)
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)
tensor([0., 0., 0.], requires_grad=True)