断言numpy.array相等的最佳方法?

问题:断言numpy.array相等的最佳方法?

我想为我的应用程序做一些单元测试,并且需要比较两个数组。由于array.__eq__返回一个新数组(因此TestCase.assertEqual失败),为相等性断言的最佳方法是什么?

目前我正在使用

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

但我不是很喜欢

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


回答 0

在中检出assert函数numpy.testing,例如

assert_array_equal

对于浮点数组,相等性测试可能会失败,并且 assert_almost_equal更加可靠。

更新

之前获得了一些版本的numpy assert_allclose,现在它是我的最爱,因为它允许我们指定绝对误差和相对误差,并且不需要十进制舍入作为接近度标准。

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.


回答 1

我觉得(arr1 == arr2).all()很好看。但是您可以使用:

numpy.allclose(arr1, arr2)

但是不完全一样。

与您的示例几乎相同的替代方法是:

numpy.alltrue(arr1 == arr2)

请注意,scipy.array实际上是一个引用numpy.array。这样可以更轻松地找到文档。

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.


回答 2

我发现使用 self.assertEqual(arr1.tolist(), arr2.tolist()) 是比较数组与unittest的最简单方法。

我同意这不是最漂亮的解决方案,并且可能不是最快的解决方案,但是与其余测试用例相比,它可能更统一,您可以获得所有unittest错误描述,并且实现起来非常简单。

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.


回答 3

从Python 3.2开始,您可以使用assertSequenceEqual(array1.tolist(), array2.tolist())

这具有向您显示数组不同的确切项目的附加价值。

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.


回答 4

在我的测试中,我使用以下代码:

try:
    numpy.testing.assert_array_equal(arr1, arr2)
    res = True
except AssertionError as err:
    res = False
    print (err)
self.assertTrue(res)

In my tests I use this:

numpy.testing.assert_array_equal(arr1, arr2)

回答 5

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

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