PyTorch torch.zeros() Method

PyTorch torch.zeros() method “returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.”

Syntax

torch.zeros(*size, *, out=None, dtype=None, layout=torch.strided, 
            device=None, requires_grad=False)

Parameters

  1. *size: The shape of the output tensor.
  2. out: Optional tensor to write the result into.
  3. dtype: The desired data type of the tensor. The default is torch.float32.
  4. layout: Memory layout of the tensor. The default is torch.strided.
  5. device: The desired device for the tensor. Default is the current default device.
  6. requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.

Example 1: Creating a 2×3 Tensor Filled with Zeros

import torch

tensor1 = torch.zeros(2, 3)
print(tensor1)

Output

tensor([[0., 0., 0.],
       [0., 0., 0.]])

Example 2: Creating a 2x3x4 Tensor Filled with Zeros of Int Type on CPU

import torch

tensor2 = torch.zeros(2, 3, 4, dtype=torch.int32, device='cpu')

print(tensor2)

Output

Creating a 2x3x4 Tensor Filled with Zeros of Int Type on CPU

Example 3: Creating a Tensor with Gradient Tracking Enabled

import torch

tensor3 = torch.zeros(2, 2, requires_grad=True)

print(tensor3)

Output

tensor([[0., 0.],
        [0., 0.]], requires_grad=True)

That’s it!

Related posts

torch.as_tensor()

torch.from_numpy()

torch.asarray()

Leave a Comment