Bool value of Variable objects containing non-empty torch.ByteTensor is ambiguous runtime error

I am getting ‘bool value of Variable objects containing non-empty torch.ByteTensor is ambiguous’ runtime error when I run the below code.

elif mask[i] ==1 and var[i] - mu[i] > 5:

Not sure what this means.

mask[i], var[i] or mu[i] will most likely return a non-scalar tensor, which cannot be converted to bool.
Have a look at this dummy example:

x = torch.randn(1, 2)
if x[0]==1:
    print('passed')

As x[0] returns a tensor of shape torch.Size([2]), the comparison will also have the same shape, e.g. tensor([0, 0], dtype=torch.uint8).

If you want to check, if all values are equal to 1, you can use:

if (x[0]==1).all():
    print('passed')

, but obviously this depends on your use case.

1 Like

Thanks. But what if I do something like mask[0][1] ==1? I still get the same error where mask is a Variable

Could you print mask[0][1]? Is it a 0-dim tensor?

Ah. Ok. I figured it out. No it is a 1-dim tensor. But the if statement gives weird results if mask is a Variable. If its a tensor, it works fine.

m=Variable(torch.rand(3,4))
if m[0][1] > 0:
print(‘passed’)

vs

m=torch.rand(3,4)
if m[0][1] > 0:
print(‘passed’)

Not sure how to make it work with variables.

I’m not sure, but you should update to the latest release.
Variables and tensors were already merged in 0.4.0.
You can find the install instructions on the website.