PyTorch torch.zeros_like() Method

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

  1. input: The input tensor whose properties (size, dtype, etc.) will be used to create the output tensor.
  2. dtype: Overrides the data type of the result tensor. The default is None.
  3. layout: Overrides the layout of the result tensor. The default is None.
  4. device: Overrides the device of the result tensor. The default is None.
  5. requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.
  6. 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

torch.zeros()

torch.as_tensor()

torch.from_numpy()

Leave a Comment