2015-04-05 16 views
0

当比较2个不同大小的numpy数组时,我会期望基于广播的布尔数组或将引发错误的布尔数组。有时候我会得到False,好像它将它们比作对象一样。当比较具有不同形状的numpy数组时意外的结果

在我可以预料,如果-失败,所以不==以下操作:在阵列

In [18]: a = np.zeros((2,7,5)) 

In [19]: b = np.zeros((2,7)) 

In [20]: a == b 
Out[20]: False 

In [21]: a - b 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-21-a5f966a4b1f4> in <module>() 
----> 1 a - b 

ValueError: operands could not be broadcast together with shapes (2,7,5) (2,7) 

回答

1

a-b失败,因为自动广播发生在左侧,而不是右侧。

np.zeros((2,7,5))-np.zeros((2,7))[:,:,None] 

工作

np.zeros((2,7,5))==np.zeros((2,7))[:,:,None] 

和平等的测试通过元素的作品元素。

但是由于Kasra注意到,在a==b中,逐个元素比较将失败。显然这两个数组并不相等。返回False与其他Python使用==.__eq__方法)一致。我不知道numpy开发者是否考虑过退回ValueError的替代方案。

考虑一下Python中返回时比较字符串和列表:

'two'=='three' 
[1,2,3]==[1] 
'string'==['l','i','s','t'] 

我想不出哪里__eq__返回一个错误,而不是False的情况。但是你也许可以用这种方式编写自己的类。

__eq__ Python文档说:

A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments. By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

numpy如下这一点 - 返回布尔数组,如果可能的话,False否则。

bool(np.zeros((2,7,5))==np.zeros((2,7))[:,:,None]) 

产生错误消息:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这是一个常见的问题SO的根。

+0

我想,如果我想在广播不可能的时候抛出ValueError,我应该'a -b == 0' – andrew 2015-04-06 14:09:13

+0

当测试生成整数数组的其他方法时,我会使用'=='。但如果他们是花车,allclose就更好。 '== aScalar'也是一种常见的面具。 – hpaulj 2015-04-06 17:03:37

1

算术运算符适用的elementwise。创建一个新数组并填充结果,如果数组不具有相同的形状,则python将引发一个ValueError以通知您有关该问题,因为它的算术错误。

==蟒蛇返回bool值及其可能要2个阵列放在一起比较,并获得bool值(即使他们没有一个相同的形状),所以首先它检查阵列的shapes;如果这些不相同,则返回False

+1

“但是对于== == python必须返回一个'bool'对象” - 什么?你为什么这么说? – user2357112 2015-04-06 05:16:21

+0

这是这种类型的运算符的Python约定。看我的报价。 – hpaulj 2015-04-06 06:45:37

+0

@ user2357112抱歉,它只是一个写错误!感谢提醒! – Kasramvd 2015-04-06 07:21:09

相关问题