# Calculate accuracy Baseline Chapter 4

I try to create a Baseline for MNIST 10 digits but I don’t know how to calculate accuracy. I need some help

Assuming `zeros`, `ones`, etc. include your input data and that their names correspond to their labels, you could do,

``````// In case you don't already have an input tensor with all your data in it
// Otherwise, you can skip this
x = [zeros, ones, twos, threes, fours, fives,
sixes, sevens, eights, nines]
x = torch.cat(x)

// In case you don't already have a target tensor with all your labels in it
// Otherwise, you can skip this
y_zeros = torch.ones(len(zeros))*0
y_ones = torch.ones(len(ones))*1
y_twos = torch.ones(len(twos))*2
y_threes = torch.ones(len(threes))*3
y_fours = torch.ones(len(fours))*4
y_fives = torch.ones(len(fives))*5
y_sixes = torch.ones(len(sixes))*6
y_sevens = torch.ones(len(sevens))*7
y_eights = torch.ones(len(eights))*8
y_nines = torch.ones(len(nines))*9
y = [y_zeros, y_ones, y_twos, y_threes,
y_fours, y_fives, y_sixes, y_sevens,
y_eights, y_nines]
y = torch.cat(y)

preds = func(x)
// (preds == y) gives an array of booleans where correctly classified examples are True
// sum(preds == y) gives the number of correctly classified examples
// Diving by len(y) gives the percentage of correctly classified examples, which is the formula for accuracy
acc = sum(preds == y)/len(y)
// Alternatively, we could do (.float() is needed since PyTorch can take the mean of only float tensors)
acc = (preds == y).float().mean()
``````

Does this answer your question?

Thanks a lot

1 Like