0

我正在使用 vgg16 进行图像分类。我想使用以下代码测试我的转移模型:

classes = ['A', 'B', 'C']
len(classes) #3
len(test_data)#171
batch_size=10

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

vgg16.eval()

for data, target in test_loader:
    output = vgg16(data)
    loss = criterion(output, target)
    test_loss += loss.item()*data.size(0)
    _, pred = torch.max(output, 1)    
    correct_tensor = pred.eq(target.data.view_as(pred))
    correct = np.squeeze(correct_tensor.numpy())
    for i in range(batch_size):
        label = target.data[i]
        class_correct[label] += correct[i].item()
        class_total[label] += 1

test_loss = test_loss/len(test_loader.dataset)
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)' % (
            classes[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)))

我收到以下错误:

I receive following error:
     15     for i in range(batch_size):
     16         label = target.data[i]
---> 17         class_correct[label] += correct[i].item()
     18         class_total[label] += 1
     19 

IndexError: too many indices for array

我不知道为什么会收到此错误以及如何解决它。如果您能帮助我,我将不胜感激。

4

0 回答 0