【发布时间】:2019-01-22 18:28:16
【问题描述】:
代码:
shape = np.array([6, 6])
grid = np.array([x.ravel() for x in np.meshgrid(*[np.arange(x) for i, x in enumerate(shape)], indexing='ij')]).T
slices = [tuple(slice(box[i], box[i] + 2) for i in range(len(box))) for box in grid]
score = np.zeros((7,7,3))
column = np.random.randn(36, 12) #just for example
column
>> array([[ 0, 1, 2, 3, ... 425, 426, 427, 428, 429, 430, 431]])
column = column.reshape((16, 3, 3, 3))
for i, window in enumerate(slices):
score[window] += column[i]
score
>> array([[[0.000e+00, 1.000e+00, 2.000e+00],
[3.000e+01, 3.200e+01, 3.400e+01],
[9.000e+01, 9.300e+01, 9.600e+01], ...
[8.280e+02, 8.300e+02, 8.320e+02],
[4.290e+02, 4.300e+02, 4.310e+02]]])
它可以工作,但最后两行需要很长时间,因为它们将处于循环状态。问题是“网格”变量包含一个窗口数组。我现在不知道如何加快这个过程。
【问题讨论】:
-
添加示例数据?
-
请查看minimal reproducible example 并包含所需的输出示例。
-
最后两行似乎很容易矢量化...纯 python for 循环对于迭代和求和真的很慢..矢量化操作正好解决了这个问题
-
你的意思是我可以用 np.vectorize() 向量化它们吗?
-
经过一些调整以使代码正常工作,我在两个部分上尝试了 `%%timeit。设置平均为 5 毫秒,for 循环为 6 毫秒。没有太大的区别。超过 600 次的迭代需要时间。
标签: numpy sliding-window numpy-slicing