How to count elements in a tensor given a certain condition?

Hello,

I am trying to find the accuracy of a regression model with a 10% error margin. So what I am doing to calculate accuracy is this:
abs(model output - target) <= 0.1*target

how can I do that in tensors?

I subtracted the two tensors and got the absolute value using torch.abs and torch.sub() now I want to count how many elements are under the 10% margin. How do I do that?

Thank you!

Your code would work and you call mean() to get the ratio (or sum() to get the number of elements meeting the condition).
Something like this might work:

output = torch.randn(10, 10)
target = torch.randn(10, 10)
res = torch.abs(output - target) <= 0.1*target
res.float().mean()
res.float().sum()
1 Like