calculating percentage error by comparing two arrays

Viewed 23965

I have some data in two numpy arrays.

a = [1, 2, 3, 4, 5, 6, 7]
b = [1, 2, 3, 5, 5, 6, 7]

I say array a is my calculated result and array b are the true result values. I want to calculate the error percentage in my result. Now I can loop through the two arrays and compare them 0 if the values match and 1 for a mismatch then add them up, divide by the total values and calculate percentage error.

Is there any possible faster and elegant method for doing this ?

2 Answers

First calculate the positions where a and b differ using a != b, then find the mean of those values:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7])
>>> b = np.array([1, 2, 3, 5, 5, 6, 7])
>>> error = np.mean( a != b )
>>> error
0.14285714285714285

Something along the lines of:

>>> a = np.array([1, 2, 3, 5, 5, 6, 7])
>>> b = np.array([1, 2, 3, 4, 5, 6, 7])
>>> (a != b).sum()/float(a.size)
0.14285714285714285

Update I'm courious why this one is slightly faster:

a = np.random.randint(4, size=1000)
b = np.random.randint(4, size=1000)
timeit('from __main__ import a, b; (a != b).sum()/float(a.size)', number=10000)
# 0.42409151163039496
timeit('from __main__ import a, b, np; np.mean(a != b)', number=10000)
# 0.5342614773662717
Related