Search code examples
pythonmachine-learningpytorchloss-function

IndexError: Target 60972032 is out of bounds


I am trying to call cross entropy loss but it says the index is out of range

loss = nn.CrossEntropyLoss()
target = torch.empty(128, dtype=torch.long)
result = loss(output, target)

Note the output has the shape torch.Size([128, 10])


Solution

  • The target tensor from provided example is not initialized, see torch.empty

    It's empty, to fix that use, for example, .random_ method, like in CrossEntropyLoss docs example:

    ...
    target = torch.empty(128, dtype=torch.long).random_(10)
    ...