python - numpy 除法的问题

标签 python arrays numpy

我正在尝试使用 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/

相关文章:

python - 以图形形式表示维基百科

python - 在没有pygame的情况下加载 Sprite (在乌龟中)

python - 优雅的结构化文本文件解析

c++ - Bad_alloc 声明数组时,似乎内存不够

python - numba 中的整数数组

python - django 的 URL Conf 支持将参数映射到字符串吗?

c - 为什么这个整数会自己递减?

javascript - 重复字母表

python - 优化 Kadane 的 numpy 算法

multithreading - 在默认的conda numpy中禁用/配置多线程