I want to judge whether a tensor is an empty tensor
2 Likes
How about this?
len(tensor.size()) == 0
1 Like
Yes, it works
empty_tensor = Variable(torch.FloatTensor())
len(empty_tensor) ==0
True
,I mean if there are other ways like if pytorch keyword about it
x.nelement() == 0
works too.
16 Likes
Hmmm, if length is an issue then len(x)==0
wins.
Plus, it is pythonic, though not specifically pytorchic.
1 Like
just beware that you can have a tensor with no elements and non-trivial size.
t = torch.zeros(size=(1,0))
t.nelement() # returns zero, empty in this sense
len(t.size()) # returns two, not empty in this sense!!
len(t) # returns one, not empty in this sense!!
t = torch.zeros(size=(0,1))
len(t) # returns zero for this one!
3 Likes
as @drevicko mentioned
len(x) == 0
may not be a good choice, since a tensor may have more than 0 dimensions, but still be empty.
x.nelement()
or x.numel()
should be good.
1 Like