损失函数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参数调好
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值