批量卷积 2d 在 numpy 中没有 scipy?



我有一批存储在数组x中的bm x n图像,以及一个大小为p x q的卷积过滤器f,我想将其应用于批处理中的每个图像(然后使用总和池化并存储在数组y中(,即all(np.allclose(y[i][j][k], (x[i, j:j+p, k:k+q] * f).sum()) for i in range(b) for j in range(m-p+1) for k in range(n-q+1))是真的。

改编这个答案,我可以写以下内容:

b, m, n, p, q = 6, 5, 4, 3, 2
x = np.arange(b*m*n).reshape((b, m, n))
f = np.arange(p*q).reshape((p, q))
y = []
for i in range(b):
shape = f.shape + tuple(np.subtract(x[i].shape, f.shape) + 1)
strides = x[i].strides * 2
M = np.lib.stride_tricks.as_strided(x[i], shape=shape, strides=strides)
y.append(np.einsum('ij,ijkl->kl', f, M))
assert all(np.allclose(y[i][j][k], (x[i, j:j+p, k:k+q] * f).sum()) for i in range(b) for j in range(m-p+1) for k in range(n-q+1))

但我认为有一种方法可以只用一个einsum来做到这一点,这对我很有用,因为b通常在 100 到 1000 之间。

如何调整我的方法以仅使用一种einsum?另外,出于我的目的,除了numpy之外,我无法引入scipy或任何其他依赖项。

只需要让shape成为 5d 并让stridesshape相匹配。

shape = f.shape + (x.shape[0],) + tuple(np.subtract(x.shape[1:], f.shape) + 1)
strides = (x.strides * 2)[1:]
M = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
y = np.einsum('pq,pqbmn->bmn', f, M)

现在,如果M变得非常大,b可能会变得非常大,但它适用于您的玩具问题。

最新更新