损失函数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 尺寸不匹配,参见官网
解决办法
- 换成支持输入input 和 输出output尺度不匹配的损失函数,torch只有如下损失函数符合要求
交叉熵损失函数 (推导过程)–样例
负对数似然损失函数
评价相似度的损失
三元组损失函数 - 暴力解法,直接 reshape(input) 改变数组的形状,强制 input 形状为 output 的形状,不要觉得仿佛丢失了什么信息量,但实际没有丢失关键特征,不会影响实验效果,前提是reshape参数调好
还没有评论,来说两句吧...