迭代 numpy 数组时的性能问题
Performance issues when iterating numpy array
我有一个 3D 图像数组,例如
[
[
[225, 0, 0],
[225, 225, 0],
...
],
[
[225, 0, 0],
[225, 225, 0],
...
],
...
]
此数组的大小为 500x500x3,即 750.000 个元素。
这些是迭代数组的简单嵌套循环
for row in arr:
for col in row:
for elem in col:
elem = (2 * elem / MAX_COLOR_VAL) - 1
但是迭代需要很多时间(> 5 分钟)。
我是 numpy 的新手所以我可能以错误的方式迭代数组?我如何优化这些循环?
Numpy 数组并非设计用于对元素进行迭代。它甚至可能 比遍历 Python 列表慢 ,因为这将导致元素的大量包装和展开。
Numpy 数组旨在批量 进行处理。因此,例如计算两个 1000×1000 矩阵的元素和。
如果您想将所有元素与 2
相乘,将这些元素除以 MAX_COLOR_VAL
并从中减去一个,您可以简单地构造一个新数组:
arr = (2 * arr.astype(float) / MAX_COLOR_VAL) - 1
这会将此操作应用于 所有 个元素。
Note: note that if you iterate over a numpy array, you do not iterate over the indices, you iterate over the rows itself. So the row
in for row in arr
will return a 2d array, not the index of a 2d array.
我有一个 3D 图像数组,例如
[
[
[225, 0, 0],
[225, 225, 0],
...
],
[
[225, 0, 0],
[225, 225, 0],
...
],
...
]
此数组的大小为 500x500x3,即 750.000 个元素。 这些是迭代数组的简单嵌套循环
for row in arr:
for col in row:
for elem in col:
elem = (2 * elem / MAX_COLOR_VAL) - 1
但是迭代需要很多时间(> 5 分钟)。
我是 numpy 的新手所以我可能以错误的方式迭代数组?我如何优化这些循环?
Numpy 数组并非设计用于对元素进行迭代。它甚至可能 比遍历 Python 列表慢 ,因为这将导致元素的大量包装和展开。
Numpy 数组旨在批量 进行处理。因此,例如计算两个 1000×1000 矩阵的元素和。
如果您想将所有元素与 2
相乘,将这些元素除以 MAX_COLOR_VAL
并从中减去一个,您可以简单地构造一个新数组:
arr = (2 * arr.astype(float) / MAX_COLOR_VAL) - 1
这会将此操作应用于 所有 个元素。
Note: note that if you iterate over a numpy array, you do not iterate over the indices, you iterate over the rows itself. So the
row
infor row in arr
will return a 2d array, not the index of a 2d array.