我正在尝试使用 numpy 除法对数组执行除法,我有两个数组,我将其称为如下:
log_norm_images = np.divide(diff_images, b_0)
我收到错误:
operands could not be broadcast together with shapes (96,96,55,64) (96,96,55).
这些分别是 ndarray 的形状。
现在,在我的 python shell 中,我执行以下测试:
x = np.random.rand((100, 100, 100))
y = np.random.rand((100, 100))
和
np.divide(x, y)
运行没有任何错误。我不确定为什么这有效,而不是我的情况。
最佳答案
您正在尝试将 4 维数组与 3 维数组一起广播。根据 NumPy 的广播行为,只有当每个相应维度的维度相等或其中一个维度为 1 时,此操作才会成功。这就是它不匹配的原因:
Your 4-D array: 96 x 96 x 55 x 64
Your 3-D array: 96 x 96 x 55
^ ^
Mismatching dimensions
如果您将 3-D 数组(我认为不再是 3-D)填充/ reshape 为明确具有形状 (96, 96, 55, 1),则您的操作可能会起作用。那么它看起来像:
Your 4-D array: 96 x 96 x 55 x 64
Your 3-D array: 96 x 96 x 55 x 1
^
This is acceptable for the broadcast behavior
此 SciPy/NumPy 文档链接对此进行了更详细的介绍:
http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
关于python - numpy 除法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27842229/