【Pytorch-Loss】ValueError: Target and input must have the same number of elements

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)

问题解决。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值