1.问题描述
在使用torch.nn.BCELoss()
进行训练时遇到了如下问题:
Traceback (most recent call last):
File "train.py", line 34, in <module>
train()
File "train.py", line 28, in train
loss = criteration(output, label)
File "/home/test/anaconda3/envs/ResUnet/lib/python3.6/site-packages/torch/nn/modules/module.py", line 541, in __call__
result = self.forward(*input, **kwargs)
File "/home/test/anaconda3/envs/ResUnet/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 498, in forward
return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
File "/home/test/anaconda3/envs/ResUnet/lib/python3.6/site-packages/torch/nn/functional.py", line 2058, in binary_cross_entropy
"!= input nelement ({})".format(target.numel(), input.numel()))
ValueError: Target and input must have the same number of elements. target nelement (786432) != input nelement (262144)
2.解决方法
查阅官方文档:
Input: (N, *)(N,∗) where *∗ means, any number of additional dimensions
Target: (N, *)(N,∗) , same shape as the input
Output: scalar. If reduction is 'none', then (N, *)(N,∗) , same shape as input.
要求输入和目标的维度一致。
官方文档的示例如下:
>>> m = nn.Sigmoid()
>>> loss = nn.BCELoss()
>>> input = torch.randn(3, requires_grad=True)
>>> target = torch.empty(3).random_(2)
>>> output = loss(m(input), target)
>>> output.backward()
可以看到还对input进行了sigmoid()。
所以尝试进行以下修改:
output = model(img)
output = F.sigmoid(output)
output = output.view(output.size(0), -1)
label = label.view(label.size(0), -1)
问题解决。