Best way to declare numpy.array equality?

I want to do some unit tests for my application, and I need to compare two arrays. Since array.__eq__ returns a new array (so TestCase.assertEqual fails), what is the best way to assert equality?

I am currently using

 self.assertTrue((arr1 == arr2).all()) 

but i don't really like it

+76
python numpy unit-testing
Jul 21 '10 at 19:18
source share
6 answers

check assert functions in numpy.testing e.g.

assert_array_equal

for floating point arrays, equality checking may fail and assert_almost_equal more reliable.

Refresh

A few versions ago, numpy got assert_allclose which is now my favorite, because it allows us to indicate both absolute and relative error and does not require decimal rounding as a criterion for proximity.

+94
Jul 22 2018-10-22T00:
source share

I think (arr1 == arr2).all() looks pretty pretty. But you can use:

 numpy.allclose(arr1, arr2) 

but it’s not exactly the same.

An alternative is almost the same as your example:

 numpy.alltrue(arr1 == arr2) 

Note that scipy.array is actually a numpy.array reference. This makes it easier to find documentation.

+17
Jul 21 '10 at 19:34
source share

I believe that using self.assertEqual(arr1.tolist(), arr2.tolist()) is the easiest way to compare arrays with unittest.

I agree that this is not the best solution, and it is probably not the fastest, but probably more uniform with the rest of your test cases, you get the whole unittest error description and it is really easy to implement.

+10
Sep 25 '14 at 19:01
source share

With Python 3.2, you can use assertSequenceEqual(array1.tolist(), array2.tolist()) .

This adds a value showing the exact elements in which the arrays differ.

+5
Jul 02 '17 at 15:10
source share

In my tests, I use this:

 try: numpy.testing.assert_array_equal(arr1, arr2) res = True except AssertionError as err: res = False print (err) self.assertTrue(res) 
+2
Mar 07 '18 at 11:22
source share

np.linalg.norm(arr1 - arr2) < 1e-6

0
Dec 10 '18 at 21:33
source share



All Articles