当我使用交叉熵损失作为损失函数时出现问题

时间:2020-04-26 02:16:36

标签: pytorch

当我使用交叉熵损失作为损失函数时,我得到的尺寸超出范围误差

Traceback (most recent call last):
  File "e:\testcode\cnn.py", line 122, in <module>
    loss = loss_func(output, b_y)   # cross entropy loss
  File "D:\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
    result = self.forward(*input, **kwargs)
  File "D:\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\modules\loss.py", line 916, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "D:\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\functional.py", line 2021, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
  File "D:\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\functional.py", line 1317, in log_softmax
    ret = input.log_softmax(dim)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

,损失函数为

loss = loss_func(output, b_y) 

输出值为

tensor([-0.3507,  0.2214,  0.3781,  0.3057], grad_fn=<SelectBackward>)

b_y的值为

tensor([3])

1 个答案:

答案 0 :(得分:0)

传递给CrossEntropyLoss的第一个参数必须是形状为[batch size x number of classes]的2d张量。如果仅计算单个批次的损失,请先将unsqueeze的logit传递给损失函数。

logits = torch.tensor([-0.3507,  0.2214,  0.3781,  0.3057]).unsqueeze(0)
targets = torch.tensor([3])
loss_func = torch.nn.CrossEntropyLoss()

loss_func(logits, targets)