I want to know the number of zeros and non-zero values in a given tensor. How can I find it?

+2 votes

Best answer

You can use the **count_nonzero()** function of the torch to count the non-zero values in a given tensor. The **numel()** returns the number of elements in the tensor. So, by subtracting the count of non-zero from the total count, you can get the count of zeros in the tensor.

Here is an example:

>>> import numpy as np

>>> import torch

>>> f=torch.tensor([[1,0,2,3],[0,0,3,4],[8,0,2,1],[6,0,1,0]])

>>> f

tensor([[1, 0, 2, 3],

[0, 0, 3, 4],

[8, 0, 2, 1],

[6, 0, 1, 0]])>>> torch.count_nonzero(f)

tensor(10)>>> torch.numel(f)-torch.count_nonzero(f)

tensor(6)

In the above example, tensor 'f' has 6 zeroes and 10 non-zero elements.