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

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

我正在使用 fastai 中的 cityscapes 数据集进行语义分割。我想在计算准确度时忽略一些 类。这就是我根据 fastai 深度学习课程定义准确性的方式:

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()

如果我只忽略 类:

中的一个,则此代码有效
mask=target!=unlabeled

但是当我试图像这样忽略多个 类 时:

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

我收到这个错误:

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

知道如何解决这个问题吗?

问题可能是因为你的tensor包含了1个以上的bool值,在做逻辑运算(and,or)的时候会出错。例如,

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

潜在的解决方案可能是直接使用逻辑运算符。

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

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

希望对您有所帮助。