Multi-target not supported at ClassNLLCriterion.c:22

Hi,
I’m trying to use the function:
loss = criterion(outputs, labels)
where the inputs are:
labels=
tensor([[2]])
outputs=
tensor([[274.3095, 842.6060, -52.4284]], grad_fn=<AddmmBackward>)

but I get the error:

multi-target not supported at /Users/distiller/project/conda/conda-bld/pytorch_1570710797334/work/aten/src/THNN/generic/ClassNLLCriterion.c:22

Any help
Thanks

Hi Shar!

Your labels has one too many dimensions. It appears that
you are using a cross–entropy-type loss criterion. Pytorch’s
CrossEntropyLoss (and related loss criteria) expect your
outputs to have shape [nBatch, nClass] and your labels
to have shape [nBatch] (with no nClass dimension). If, for
some reason, your labels naturally has a trailing singleton
dimension, you can squeeze() it away.

Thus:

>>> import torch
>>> torch.__version__
'1.9.0'
>>> labels = torch.tensor ([[2]])
>>> outputs = torch.tensor ([[274.3095, 842.6060, -52.4284]])
>>> criterion = torch.nn.CrossEntropyLoss()
>>> labels.shape
torch.Size([1, 1])
>>> outputs.shape
torch.Size([1, 3])
>>> loss = criterion (outputs, labels.squeeze (1))
>>> loss
tensor(895.0344)

Best.

K. Frank

1 Like

It worked. Many thanks!