IndexError: index out of bounds error

am getting this error :
IndexError: index 28 is out of bounds for dimension 0 with size 28

when i run on test_loader
for data, target in test_loader:
data, target = data.cuda(), target.cuda()

output = model(data)

loss = criterion(output, target)

test_loss += loss.item()

_, pred = torch.max(output, 1)    

correct_tensor = pred.eq(target.data.view_as(pred))
correct = np.squeeze(correct_tensor.cpu().numpy())

for i in range(64):
    label = target.data[i]
    class_correct[label] += correct[i].item()
    class_total[label] += 1

the error occur at label = target.data[i] how to solve it.

Hi, you could change range(64) to range(28) to solve that

It appears that target is of size 28. Don’t hesitate to print(target.shape) to check.

That 64 is batch_size, at full connected layer start with input 64x28x28

and this occurs when i run on cuda on google colab but on my PC with CPU it run ok

Well I’m sure at that time, the batch size is 28, you can print both data and target shape to verify
PS, quick fix is to simply add “if data_batch_size < 64 or target_batch_size < 64: continue”
or replace range(64) with range(len(target.data)). Boom done, you don’t need to care what the size is

Print shape of target.data and post it here please.

Thanks i change the range(64) to range(len(target.data)) it work