Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of non-zero elements in a tensor along an aixs

I want to find the number of non-zero elements in a tensor along a particular axis. Is there any PyTorch function which can do this?

I tried to use the nonzero() method in PyTorch.

torch.nonzero(losses).size(0)

Here, lossess is a tensor of shape 64 x 1. When I run the above statement, it gives me the following error.

TypeError: Type Variable doesn't implement stateless method nonzero

But if I run, torch.nonzero(losses.data).size(0), then it works fine. Any clue, why this is happening or what the error means?

like image 455
Wasi Ahmad Avatar asked Nov 18 '25 01:11

Wasi Ahmad


1 Answers

Meaning of the error message - TypeError: Type Variable doesn't implement stateless method nonzero is, we cannot use torch.nonzero() on autograd.Variable but only on simple tensors. Also it should be noted that, tensors are stateless while the Variables are stateful.

like image 110
Wasi Ahmad Avatar answered Nov 20 '25 17:11

Wasi Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!