损失函数Target size must be the same as input size

出错程序

criterion_modality = torch.nn.BCEWithLogitsLoss()

label = Variable(label.cuda())

loss = criterion_modality(outRGB, label) # 出错行

问题

File "C:\Users\Rain\AppData\Local\Programs\Python\Anaconda.3.5.1\envs\python35\python35\lib\site-packages\torch\nn\modules\module.py", line 491, in __call__
    result = self.forward(*input, **kwargs)
  File "C:\Users\Rain\AppData\Local\Programs\Python\Anaconda.3.5.1\envs\python35\python35\lib\site-packages\torch\nn\modules\loss.py", line 500, in forward
    reduce=self.reduce)

  File "C:\Users\Rain\AppData\Local\Programs\Python\Anaconda.3.5.1\envs\python35\python35\lib\site-packages\torch\nn\functional.py", line 1514, in binary_cross_entropy_with_logits

    raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))

ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 2]))

在这里插入图片描述

原因

input 和 target 尺寸不匹配,参见官网
在这里插入图片描述

解决办法

  1. 换成支持输入input 和 输出output尺度不匹配的损失函数,torch只有如下损失函数符合要求
    交叉熵损失函数
    负对数似然损失函数
    评价相似度的损失
    三元组损失函数
    在这里插入图片描述
  2. 暴力解法,直接 reshape(input) 改变数组的形状,强制 input 形状为 output 的形状,不要觉得仿佛丢失了什么信息量,但实际没有丢失关键特征,不会影响实验效果,前提是reshape参数调好