ValueError: operands could not be broadcast together with shapes (200,49000) (10,49000) (200,49000)

ValueError: operands could not be broadcast together with shapes (200,49000) (10,49000) (200,49000)

这个

a=np.zeros((20,4900))

b=np.zeros((1,4900))

a+=b

工作得很好。然而,这:

a=np.zeros((200,49000))

b=np.zeros((10,49000))

a+=b

显示此错误:

ValueError: operands could not be broadcast together with shapes (200,49000) (10,49000) (200,49000)

这可能是什么原因?

编辑:

Numpy 仅当且仅当矩阵 A 或 B 的高度为 1 行时,才允许您添加两个 不等维 的矩阵。这称为广播。基本线性代数表示您正在尝试执行无效的矩阵运算,因为两个矩阵必须具有相同的维度(对于 addition/subtraction),因此 Numpy 尝试通过广播来对此进行补偿。

如果在你的第二个例子中你的 b 矩阵是这样定义的:

b=np.zeros((1,49000))

不会有错误。但如果你尝试这样做:

b=np.zeros((2,49000))

它会抛出同样的错误。 Numpy docs 中的案例 2 适用于您的情况:

General Broadcasting Rules

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when

1.they are equal, or
2.one of them is 1

If these conditions are not met, a ValueError: frames are not aligned exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays.