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

拼搏现实的明天。 2022-02-25 08:57 1399阅读 0赞

出错程序

  1. criterion_modality = torch.nn.BCEWithLogitsLoss()
  2. label = Variable(label.cuda())
  3. loss = criterion_modality(outRGB, label) # 出错行

问题

  1. 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__
  2. result = self.forward(*input, **kwargs)
  3. 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
  4. reduce=self.reduce)
  5. 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
  6. raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
  7. 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参数调好

发表评论

表情:
评论列表 (有 0 条评论,1399人围观)

还没有评论,来说两句吧...

相关阅读