Tutorial Example

Understand PyTorch Tensor.zero_() with Examples – PyTorch Tutorial

In this tutorial, we will use some examples to help you understand Tensor.zero_() in pytorch. You can learn how to use it correctly.

PyTorch Tensor.zero_()

It will fill current tensor with zero, then it will return current tensor.

Here is an example code:

import torch
x = torch.tensor([[1.0, 2.0],[2.0, 3.0]])
print(x)
print(type(x))
print(id(x))
y = x.zero_()
print(id(y))
print(y)

Run this code, we will see:

tensor([[1., 2.],
        [2., 3.]])
<class 'torch.Tensor'>
1833447961208
1833447961208
tensor([[0., 0.],
        [0., 0.]])

We can find:

By y = x.zero_(), tensor x will be filled with 0, then x will be returned.

We will se id(x) = id(y).