【问题标题】:ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1]))ValueError: 目标尺寸 (torch.Size([16])) 必须与输入尺寸 (torch.Size([16, 1])) 相同
【发布时间】:2020-01-07 21:59:36
【问题描述】:
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。研究马与人数据集。 This is my code。我正在使用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]))。我不明白,我需要在哪里进行更改才能纠正错误。

【问题讨论】:

    标签: size conv-neural-network pytorch


    【解决方案1】:

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

    【讨论】:

    • target.unsqueeze(1) 中的 1 表示的是类数吗?同样 1 将目标张量大小从 [16] 更改为 [16,1].. ?
    • @Irfan Umar 它将在维度 1 处添加一个新维度。因此张量将变为 2d。
    猜你喜欢
    • 2021-12-05
    • 2021-04-08
    • 2021-11-12
    • 1970-01-01
    • 2022-01-21
    • 2021-09-29
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多