【问题标题】:"Runtimeerror: bool value of tensor with more than one value is ambiguous" fastai“运行时错误:具有多个值的张量的布尔值不明确”fastai
【发布时间】:2019-10-01 07:42:24
【问题描述】:

我正在使用 fastai 中的城市景观数据集进行语义分割。我想在计算准确性时忽略一些类。这就是我根据 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

有什么办法解决这个问题吗?

【问题讨论】:

    标签: pytorch fast-ai


    【解决方案1】:

    问题可能是因为你的张量包含超过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([])
    

    希望对你有帮助。

    【讨论】:

    • 就是这样。非常感谢王慧波
    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 2019-11-14
    • 2019-06-08
    • 2019-03-27
    • 2022-01-12
    • 1970-01-01
    • 2019-10-12
    • 2020-02-16
    相关资源
    最近更新 更多