2

I get:

RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed. at /opt/conda/conda-bld/pytorch_1550796191843/work/aten/src/THNN/generic/ClassNLLCriterion.c:93

When running this code:

    criterion = nn.CrossEntropyLoss()
    #Define the optimizer
    optimizer=optim.SGD(net.parameters(),lr=0.01,momentum=0.9)
    epochs=20
    for epoch in range(epochs):
        print ("epoch #", epoch)
        running_loss=0.0
        for i, data in enumerate(train_loader,0):
            inputs,labels=data
            inputs,labels= inputs.to(device),labels.to(device)
            optimizer.zero_grad()   
            #train
            output=net(inputs)
            loss=criterion(output,labels)

    print ("loss: ", loss.item())
    running_loss+=loss.item()
    loss.backward()
    optimizer.step()
    print ('Finished Training')
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • I am facing same problem and still it's unsolved. I don't know how to solve that as well. – Ananda G Jul 16 '19 at 04:26
  • You are not indicating which library this module comes from. It's not a problem in Python or Anaconda, it's in the library which contains the code which emits the message (quick googling suggests Pytorch?) – tripleee Nov 14 '19 at 05:03

2 Answers2

1

The exception says that one of your labels is out of bounds. Maybe they start from 1 instead of 0? Try printing them out.

Zac R.
  • 538
  • 3
  • 17
0

I ran into this exact error (yes, it's from Pytorch), I'll post my solution in case anyone else can benefit from it.

Mine was due to a mistake where I only had 2 outputs to the classifier, but the data had 3 labels.

Fixed by making sure the classifier gave 3 classes.

N Blake
  • 141
  • 4