# Count nonzeros element along an axis

Hi!
I have a `(32x750)` tensor

``````tensor([[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0043],
[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0043],
[ 0.0000,  0.0044,  0.0000,  ...,  0.0044,  0.0000,  0.0000],
...,
[ 0.0059,  0.0000,  0.0059,  ...,  0.0059,  0.0000,  0.0000],
[ 0.0059,  0.0000,  0.0059,  ...,  0.0059,  0.0000,  0.0000],
[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0056,  0.0000]], device='cuda:0')
``````

And I want to get the number of nonzero elements along each rows. Something like that
`[12 47 0 5 .... 8 7 50]`
This discussion didn’t solve my problem and concerned the number of nonzero elements for 1-D tensor.

Thanks

1 Like

Maybe something like this:

`750 - (tensor == 0).sum(dim=1)`

3 Likes

Oh, you want differentiable counting

Thanks,
It worked
I’m using smooth label regularization and the idea is to normalize the output with target values which will contribute to the grad

1 Like

`(tensor != 0).sum(dim=1)` works as well and you don’t have to mention dimentionality (750).