Skip to content

[Solved][PyTorch] IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

Today I got an error message as following (In a team project source code):

IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

I searched it on the Internet, I found it is so easy to solve. This error may be occurred frequently when using CrossEntropyLoss().

And the first entry of CrossEntropyLoss() should be “Probability Distribution of Predicted Classification“. If you directly use argmax() to input the label result, this error may occur.


Example

For example, we input the following data to CrossEntropyLoss() function:

import torch
import torch.nn as nn

a = torch.tensor([1, 2, 3])
b = torch.tensor([1, 0, 1])

print(nn.CrossEntropyLoss()(a, b))



Output:

IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

We can got this error message.

So, our variable a should be a probability distribution. We fixed it as following:

import torch
import torch.nn as nn

a = torch.tensor([[-0.8, -0.2], [-0.2, -0.3], [-0.24, -0.35]]).float()
b = torch.tensor([1, 0, 1])

print(nn.CrossEntropyLoss()(a, b))



Output:

tensor(0.6105)

As you can see, if variable a is a probability distribution, CrossEntropyLoss() function can be worked.


References


Read More

Leave a ReplyCancel reply

Exit mobile version