How to use accuracy with PyTorch?

Chris Staff asked 6 months ago
1 Answers
Best Answer
Chris Staff answered 6 months ago

You can compute accuracy in the custom testing loop that you add to your code for model testing:

  # Testing loop
  correct, total = 0, 0
  with torch.no_grad():
    
    # Iterate over the test data and generate predictions
    for i, data in enumerate(trainloader_test, 0):
      
      # Get inputs
      inputs, targets = data
      
      # Generate outputs
      outputs = mlp(inputs)
      
      # Set total and correct
      _, predicted = torch.max(outputs.data, 1)
      total += targets.size(0)
      correct += (predicted == targets).sum().item()
      
    # Print accuracy
    print('Accuracy: %d %%' % (100 * correct / total))

In the code, we set correct & total samples tested to zero, use no gradients, and then iterate over the testing data in our testing DataLoader. Per minibatch, we decompose the data into inputs and targets, generate the outputs (here, mlp is the initialization of our nn.Module), generate the indices of the class predictions and update total and correct. Finally, we print the accuracy.

Your Answer

1 + 14 =