为什么numpy的广播有时会允许比较不同长度的数组?

时间:2016-07-12 14:27:10

标签: python numpy numpy-broadcasting

我试图了解numpy的广播如何影响np.allclose的输出。

>>> np.allclose([], [1.])
True

我不明白为什么会有效,但事实并非如此:

>>> np.allclose([], [1., 2.])
ValueError: operands could not be broadcast together with shapes (0,) (2,)

这里的规则是什么?我无法在numpy docs中找到有关空数组的任何内容。

2 个答案:

答案 0 :(得分:1)

广播不会以任何其他方式影响np.allclose,而不会影响任何其他功能。

与@cel的评论一样,[1.]的维度为1,因此可以广播到任何其他维度,包括0.另一方面,[1., 2.]的维度为2,因此不能广播。

现在为什么allclose([],[1.]) == True?这实际上是有道理的:它意味着[]中的所有元素都接近1.。相反的意思是[]中至少有一个元素不接近1.,显然是False,因为[]中根本没有元素。< / p>

考虑它的另一种方法是问问自己如何实际编码allclose()

def allclose(array, target=1.):
    for x in array:
        if not isclose(x, target):
            return False
    return True

使用True调用时,这将返回[]

答案 1 :(得分:1)

广播规则也适用于添加,

In [7]: np.array([])+np.array([1.])
Out[7]: array([], dtype=float64)

In [8]: np.array([])+np.array([1.,2.])
....

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

让我们看一下形状。

In [9]: np.array([]).shape,np.array([1.]).shape,np.array([1,2]).shape
Out[9]: ((0,), (1,), (2,))

(0,)和(1,) - 可以调整(1,)以匹配另一个数组的形状。可以调整1维度以匹配其他数组,例如从1增加到3.但是这里(显然)从1调整为0.我通常不使用0的数组维度,但这看起来像是对更高维度的适当概括。

尝试(0,)和(1,1)。结果是(1,0):

In [10]: np.array([])+np.array([[1.]])
Out[10]: array([], shape=(1, 0), dtype=float64)

(0,),(1,1)=&gt; (1,0),(1,1)=&gt; (1,0)

形状(0,)和(2,)的第二种情况;没有任何尺寸1尺寸需要调整,因此错误。

形状(0,)和(2,1)进行广播(至(2,0)):

In [12]: np.array([])+np.array([[1.,2]]).T
Out[12]: array([], shape=(2, 0), dtype=float64)