+4 votes
in Programming Languages by (17.9k points)
I want to know the number of zeros and non-zero values in a given tensor. How can I find it?

1 Answer

+2 votes
by (48.9k points)

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)
>>> torch.numel(f)-torch.count_nonzero(f)

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