我有一批存储在数组x
中的b
m 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 并让strides
与shape
相匹配。
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
可能会变得非常大,但它适用于您的玩具问题。