"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?

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,

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


The potential solution might be using logical operator directly.

&gt;&gt;&gt; (a != b) &amp; (a == b)
tensor([False, False])

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


Hope it helps.
