How to calculate accuracy in pytorch?

I want to calculate training accuracy and testing accuracy.In calculating in my code,training accuracy is tensor,not a number.Moreover,in converting numpy(),the accuracy is 2138.0 ,I used ypred and target in calculating accuracy.Why does the problem appear?Please answer how I solve.Thanks in advance!

Could you please share the code where you calculate your accuracy?

As a general knowledge, you can calculate the accuracy on the training set based on your your metric defined beforehand. As an example, you can use the L1,L2 difference between two numpy arrays as a metric.

Thanks a lot for answering.Accuracy is calculated as seperate function,and it is called in train epoch in the following loop:
for batch_idx,(input, target) in enumerate(loader):
output = model(input)
# measure accuracy and record loss
batch_size = target.size(0)
_, pred =, dim=1)
pred = pred.t()
y_pred = model(input)
Please answer how can I calculate?Thanks in advance!

1 Like
train_acc = torch.sum(y_pred == target)

At the end

final_train_acc = train_acc/number_of_datapoints
1 Like

Thanks a lot for answering! Isnumber_of_datapoints total number of data samples?Thanks!

read this answer: