簡體   English   中英

Pytorch nn.CrossEntropyLoss 給出,ValueError: 預期目標大小 (x, y),得到 3d 張量的 torch.Size([x, z])

[英]Pytorch nn.CrossEntropyLoss giving, ValueError: Expected target size (x, y), got torch.Size([x, z]) for 3d tensor

我正在按照此處的示例進行操作,其中文檔說:

輸入:(N, C) 其中 C = 類數

目標:(N) 其中每個值為 0 ≤ targets[i] ≤ C−1

這就是為 2d 張量給出的例子的情況

loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
output = loss(input, target)
output.backward()

但是對於二維張量,我收到了一個錯誤

import torch.nn as nn
import torch
loss = nn.CrossEntropyLoss(ignore_index=0)

inputs = torch.rand(32, 128, 3)
targets = torch.ones(32, 128)

loss(inputs, targets.long())
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-26-61e7f03039a6> in <module>
      7 targets = torch.ones(32, 128)
      8 
----> 9 loss(inputs, targets.long())

/opt/conda/lib/python3.8/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    725             result = self._slow_forward(*input, **kwargs)
    726         else:
--> 727             result = self.forward(*input, **kwargs)
    728         for hook in itertools.chain(
    729                 _global_forward_hooks.values(),

/opt/conda/lib/python3.8/site-packages/torch/nn/modules/loss.py in forward(self, input, target)
    959 
    960     def forward(self, input: Tensor, target: Tensor) -> Tensor:
--> 961         return F.cross_entropy(input, target, weight=self.weight,
    962                                ignore_index=self.ignore_index, reduction=self.reduction)
    963 

/opt/conda/lib/python3.8/site-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   2466     if size_average is not None or reduce is not None:
   2467         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2468     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   2469 
   2470 

/opt/conda/lib/python3.8/site-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   2271         out_size = (n,) + input.size()[2:]
   2272         if target.size()[1:] != input.size()[2:]:
-> 2273             raise ValueError('Expected target size {}, got {}'.format(
   2274                 out_size, target.size()))
   2275         input = input.contiguous()

ValueError: Expected target size (32, 3), got torch.Size([32, 128])

據我所知,我在設置尺寸方面做得很好。 錯誤信息似乎認為我給的是一個 2d 向量,但我給了它一個 3d 向量,缺少 128 大小的維度。

有什么我沒有為這個損失函數正確設置的嗎?

這是文檔中關於 K 維損失的內容:

也可用於更高維度的輸入,例如 2D 圖像,通過提供大小為 (minibatch, C, d_1, d_2, ..., d_K) 且 K ≥ 1 的輸入,其中 K 是維數,以及適當形狀的目標(見下文)。

如果您有 3 個類,則正確的輸入應該具有(32, 3, 128)形狀:

import torch.nn as nn
import torch
loss = nn.CrossEntropyLoss(ignore_index=0)

inputs = torch.rand(32, 3, 128)
targets = torch.ones(32, 128)

loss(inputs, targets.long())

或者目標應該有一個(32, 3)形狀,如果你有 128 個類:

inputs = torch.rand(32, 128, 3)
targets = torch.ones(32, 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM