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

标签 python numpy array-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 中找不到任何内容关于空数组。

最佳答案

广播规则也适用于添加,

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) => (1,0),(1,1) => (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)

关于python - 为什么 numpy 的广播有时允许比较不同长度的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38331703/

相关文章:

python - FailedPreconditionError : Attempting to use uninitialized in Tensorflow

python - 从可能不完整的候选列表构建 2D 网格

python - 根据另一列的多个条件填充一列

python - 具有广播功能的 numpy 数组构造

python - 列表外积的numpy方式

python 生成器 int() 的无效文字

python - 谷歌应用引擎 : How to write large files to Google Cloud Storage

python - sys.argv 无输出

python - 矩阵中每行的特定案例计数

python - 用于近似像素颜色变化的嵌套 For 循环的 Numpy 等效项