【问题标题】:Target and input must have the same number of elements目标和输入必须具有相同数量的元素
【发布时间】:2018-06-03 20:53:51
【问题描述】:

我的输入标签大小是torch.size([30, 2, 96, 96, 96])

我的标签大小是torch.size([30, 96, 96, 96]),我将它们提供给我的损失函数,如下所示:

loss = F.binary_cross_entropy(F.sigmoid(output),labels,torch.FloatTensor(CLASS_WEIGHTS).cuda())

当我运行它时,我得到了

Value error:Target and input must have the same number of elements.target nelement(26542080) != input nelement(53084160)

我在这里有点困惑。我得到的输入值是目标值的两倍,因为它将[30,96,96] 乘以类数,但我不确定为什么会这样,以及如何纠正它。任何建议都会有所帮助,在此先感谢。

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    与采用目标标签值的torch.nn.CrossEntropyLoss 层不同(即,如果input 的形状为(30, C, 96, 96, 96)C 类数,target 必须是(30, 96, 96, 96)),torch.nn.functional.binary_cross_entropy() 需要inputtarget 具有相同的形状(即 target 的形状 (30, C, 96, 96, 96)),因此它需要目标标签的 one-hot 表示。

    除非您选择torch.nn.CrossEntropyLoss,否则您有多种方法可以一次性使用您的目标标签(例如,请参阅此thread)。个人解决方案:

    def to_one_hot(x, C=2, tensor_class=torch.FloatTensor):
        """ One-hot a batched tensor of shape (B, ...) into (B, C, ...) """
        x_one_hot = tensor_class(x.size(0), C, *x.shape[1:]).zero_()
        x_one_hot = x_one_hot.scatter_(1, x.unsqueeze(1), 1)
        return x_one_hot
    
    # Demonstration:
    num_classes = 2
    labels = torch.LongTensor(30, 96, 96, 96).random_(0, num_classes)
    one_hot_labels = to_one_hot(labels, C=num_classes)
    print(one_hot_labels.shape)
    # > torch.Size([30, 2, 96, 96, 96])
    

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 2018-05-15
      • 2020-07-27
      • 2020-09-24
      • 2019-03-14
      • 1970-01-01
      • 2016-12-15
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多