数值错误:目标尺寸(torch.Size([16]))必须与输入尺寸(torch.Size([16,1]))相同。

46
ValueError                                Traceback (most recent call last)
<ipython-input-30-33821ccddf5f> in <module>
     23         output = model(data)
     24         # calculate the batch loss
---> 25         loss = criterion(output, target)
     26         # backward pass: compute gradient of the loss with respect to model parameters
     27         loss.backward()

C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    487             result = self._slow_forward(*input, **kwargs)
    488         else:
--> 489             result = self.forward(*input, **kwargs)
    490         for hook in self._forward_hooks.values():
    491             hook_result = hook(self, input, result)

C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
    593                                                   self.weight,
    594                                                   pos_weight=self.pos_weight,
--> 595                                                   reduction=self.reduction)
    596 
    597 

C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
   2073 
   2074     if not (target.size() == input.size()):
-> 2075         raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
   2076 
   2077     return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)

ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1]))

我正在训练一个CNN,使用的是马和人的数据集。 这是我的代码。 我使用了criterion = nn.BCEWithLogitsLoss()optimizer = optim.RMSprop(model.parameters(), lr=0.01)。我的最后一层是self.fc2 = nn.Linear(512, 1)。我们的最后一个神经元会输出1表示马,0表示人,对吗?还是我应该选择2个神经元作为输出?

16是批量大小。由于错误提示是:ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1]))。我不明白,在哪里需要进行更改以纠正这个错误。

3个回答

65

target = target.unsqueeze(1) 在将目标张量传递给损失函数之前,将目标张量从 [16] 改变为[16,1] 的大小。这样做解决了问题。此外,我还需要在将其传递给损失函数之前执行 target = target.float(),因为我们的输出是浮点数。除此之外,代码中还存在另一个错误。我在最后一层使用了sigmoid激活函数,但实际上不应该这样做,因为我正在使用的损失函数已经内置了sigmoid函数。


1
target.unsqueeze(1) 中的 1 表示类别数吗?同样地,将目标张量大小从 [16] 更改为 [16,1] 中的 1 是什么意思? - Irfan Umar
1
@Irfan Umar,它将在第1个维度上添加一个新的维度。因此张量将变为2D。 - Khan

0

您也可以尝试使用 _, pred = torch.max(output, 1),然后将 pred 变量传递到损失函数中。


0

当我运行我的模型时,我遇到了同样的错误。通过在数据集类中返回torch.tensor([target]).float().to(device),我成功地纠正了它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接