Class_correct[label] += correct[i].item() IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

#######load the saved model for testing the trained network######
model.load_state_dict(torch.load(‘model_FER_CAN.pt’))

   # initialize lists to monitor test loss and accuracy

test_loss = 0.0
class_correct = list(0. for i in range(len(classes)))
class_total = list(0. for i in range(len(classes)))

model.eval() # prep model for evaluation

for data, target in test_loader:
# move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update test loss
test_loss += loss.item()*data.size(0)
# convert output probabilities to predicted class
_, pred = torch.max(output, 1)
# compare predictions to true label
correct = np.squeeze(pred.eq(target.data.view_as(pred)))

###calculate test accuracy for each object class
print(len(target))
for i in range(len(target)):
    label = target.data[i]
    class_correct[label] += correct[i].item()
    class_total[label] += 1

calculate and print avg test loss

test_loss = test_loss/len(test_loader.sampler)
print(‘Test Loss: {:.6f}\n’.format(test_loss))

for i in range(len(classes)):
if class_total[i] > 0:
print(‘Test Accuracy of %5s: %2d%% (%2d/%2d)’ % (
str(i), 100 * class_correct[i] / class_total[i],
np.sum(class_correct[i]), np.sum(class_total[i])))
else:
print(‘Test Accuracy of %5s: N/A (no training examples)’ % (classes[i]))

print(’\nTest Accuracy (Overall): %2d%% (%2d/%2d)’ % (
100. * np.sum(class_correct) / np.sum(class_total),
np.sum(class_correct), np.sum(class_total)))

error is ==========================================================
class_correct[label] += correct[i].item()
IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

correct seems to be a 0-dim tensor, which you cannot index. This error might be raised, as you are calling np.squeeze to create correct.

Hello, how to solve this problem

The author of the question didn’t follow up so I’m unsure, what the root cause in the posted script was.
However, since you are running into the same issue, check the shapes of all involved tensors and make sure you are not removing dimensions you would like to index later.