heisenberg
heisenberg

Reputation: 135

"Runtimeerror: bool value of tensor with more than one value is ambiguous" fastai

I am doing semantic segmentation using cityscapes dataset in fastai. I want to ignore some classes while calculating accuracy. this is how I defined accuracy according to fastai deep learning course:

name2id = {v:k for k,v in enumerate(classes)}
unlabeled = name2id['unlabeled']
ego_v = name2id['ego vehicle']
rectification = name2id['rectification border']
roi = name2id['out of roi']
static = name2id['static']
dynamic = name2id['dynamic']
ground = name2id['ground']

def acc_cityscapes(input, target):
    target = target.squeeze(1)

    mask=(target!=unlabeled and target!= ego_v and target!= rectification
    and target!=roi and target !=static and target!=dynamic and 
    target!=ground)

return (input.argmax(dim=1)[mask]==target[mask]).float().mean()

This code works if I ignore only one of the classes:

mask=target!=unlabeled

But when I am trying to ignore multiple classes like this:

mask=(target!=unlabeled and target!= ego_v and target!= rectification
    and target!=roi and target !=static and target!=dynamic and 
    target!=ground)

I am getting this error:

runtimeError: bool value of tensor with more than one value is ambiguous

Any Idea how do I solve this?

Upvotes: 1

Views: 17443

Answers (1)

hpwww
hpwww

Reputation: 565

The problem is probably because your tensor contains more than 1 bool values, which will lead to an error when doing logical operation (and, or). For example,

>>> import torch
>>> a = torch.zeros(2)
>>> b = torch.ones(2)
>>> a == b
tensor([False, False])
>>> a == 0
tensor([True, True])
>>> a == 0 and True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: bool value of Tensor with more than one value is ambiguous
>>> if a == b:
...     print (a)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: bool value of Tensor with more than one value is ambiguous

The potential solution might be using logical operator directly.

>>> (a != b) & (a == b)
tensor([False, False])

>>> mask = (a != b) & (a == b)
>>> c = torch.rand(2)
>>> c[mask]
tensor([])

Hope it helps.

Upvotes: 4

Related Questions