Best way to assert for numpy.array equality?

PythonUnit TestingNumpy

Python Problem Overview


I want to make some unit-tests for my app, 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 for equality?

Currently I'm using

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

but I don't really like it

Python Solutions


Solution 1 - Python

check out the assert functions in numpy.testing, e.g.

assert_array_equal

for floating point arrays equality test might fail and assert_almost_equal is more reliable.

update

A few versions ago numpy obtained assert_allclose which is now my favorite since it allows us to specify both absolute and relative error and doesn't require decimal rounding as the closeness criterion.

Solution 2 - Python

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

numpy.allclose(arr1, arr2)

but it's not quite the same.

An alternative, almost the same as your example is:

numpy.alltrue(arr1 == arr2)

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

Solution 3 - Python

I find that using self.assertEqual(arr1.tolist(), arr2.tolist()) is the easiest way of comparing arrays with unittest.

I agree it's not the prettiest solution and it's probably not the fastest but it's probably more uniform with the rest of your test cases, you get all the unittest error description and it's really simple to implement.

Solution 4 - Python

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

This has the added value of showing you the exact items in which the arrays differ.

Solution 5 - Python

self.assertTrue(np.array_equal(x, y, equal_nan=True))

equal_nan = True if you want to np.nan == np.nan returns True

or you can use numpy.allclose to compare with torelance.

Solution 6 - Python

In my tests I use this:

numpy.testing.assert_array_equal(arr1, arr2)

Solution 7 - Python

Use numpy

numpy.array_equal(a, b)

Solution 8 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmakerView Question on Stackoverflow
Solution 1 - PythonJosefView Answer on Stackoverflow
Solution 2 - PythonSiggyFView Answer on Stackoverflow
Solution 3 - PythonasimoneauView Answer on Stackoverflow
Solution 4 - PythonHagaiHView Answer on Stackoverflow
Solution 5 - PythonMarseilleView Answer on Stackoverflow
Solution 6 - PythonEdo user1419293View Answer on Stackoverflow
Solution 7 - Pythona_bView Answer on Stackoverflow
Solution 8 - PythonschiebermcView Answer on Stackoverflow