使用unittest Python的numpy数组的ValueError
我有以下问题 我有以下功能:使用unittest Python的numpy数组的ValueError,python,arrays,numpy,unit-testing,Python,Arrays,Numpy,Unit Testing,我有以下问题 我有以下功能: def string_to_2Darray(flat_string): """converts a string of type '0,1,0,1,1,1,0,1,0'""" array1d = np.fromstring(flat_string, dtype=int, sep=',') return np.reshape(array1d, (-1,3)) 我为这个函数编写了一个unittest类,如下所示: class String
def string_to_2Darray(flat_string):
"""converts a string of type '0,1,0,1,1,1,0,1,0'"""
array1d = np.fromstring(flat_string, dtype=int, sep=',')
return np.reshape(array1d, (-1,3))
我为这个函数编写了一个unittest类,如下所示:
class StringTo2DArray(unittest.TestCase):
def test_string_2DArray(self):
string_example_0 = '0,1,0,1,1,1,0,1,0'
array_example_0 = string_to_2Darray(string_example_0)
print(array_example_0)
print(type(array_example_0))
self.assertEqual([[0,1,0],[1,1,1],[0,1,0]], array_example_0)
请注意,我在unittest中的StringTo2DArray类中的test_string_2Darray模块主体中添加了一些打印语句
当我运行python-m unittest时,会收到以下错误消息:
ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()
我不知道为什么会发生这种情况,因为字符串已正确转换为2D numpy数组,并且与我在断言中传递的数组
[[0,1,0],[1,1],[0,1,0]]
不匹配。和我的考试一样 您可以使用套件中的函数检查两个numpy数组是否相等
在你的情况下,你可以替换
self.assertEqual([[0,1,0],[1,1,1],[0,1,0]], array_example_0)
与
@罗杰·阿尔门戈
正如@llll所回答的,这是Python测试用例实现中的一个已知错误。
assertEqual(a,b)实现假定a==b操作将返回一个True或一个False,但如果它返回一个包含多个布尔值的合成值,则会引发此错误。例如,如果a、b是numpy的数据数组或Tensorflow的张量,则会触发此错误
有两种解决方案可以解决此缺陷:
重复:我喜欢使用tensorflow.test.TestCase'assertAllEqual()、assertAllClose()、assertAllXXXXX()函数来处理numpy的数据数组和tensor的值比较工作。
numpy.testing.assert_array_equal([[0,1,0],[1,1,1],[0,1,0]], array_example_0)