I'm struggling to calculate accuracy for every epoch in my training function for CNN classifier in Pytorch.
After I run this script, it always prints out 0, 0.25 or 0.75 which is obviously wrong. I'm guessing the problem are the inputs of the get_accuracy function (outputs and labels) as they are not accumulated for the entire epoch but not sure how to fix that.
Ideally, I'd like to print out both train and test accuracy for every epoch.
def get_accuracy(pred, actual):
assert len(pred) == len(actual)
total = len(actual)
_, predicted = torch.max(pred.data, 1)
correct = (predicted == actual).sum().item()
return correct / total
def train_model(model):
for epoch in range(epochs):
running_loss = 0.00
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = cnn(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item() #calculates loss of the batch in average
running_loss /= len(trainloader)
training_accuracy = get_accuracy(outputs, labels)
test_accuracy = 'todo'
print('='*10,'iteration: {0}'.format(epoch+1),'='*10,)
print('\n Loss: {0} \n Training accuracy:{1}% \n Test accuracy: {2}%'.format(running_loss, training_accuracy, test_accuracy))
print('Finished Training')