Search code examples
pythonnumpystride

Inverse function of numpy as_strided


I have a 4-tensor x. The 6-tensor y is computed as follows:

x = np.random.randn(64, 28, 28, 1)
strided_shape = 64, 26, 26, 3, 3, 1
y = numpy.lib.stride_tricks.as_strided(x, strided_shape, strides=(x.strides[0], x.strides[1], x.strides[2], x.strides[1], x.strides[2], x.strides[3]))

strided_shape in general can be any shape as long as the first and last dimensions match those of x (this is just a concrete example).

My question is, using y (and the x.shape and x.strides tuples), is it possible to recover the original tensor x, using as_strided again, reshape, sum, etc.? Note: I am not actually planning on applying said process to y itself; rather I want to perform the procedure on a tensor with the same shape as y.


Solution

  • Well y is simply a view into x, with different shape and strides. As such, recovering x from y is simply changing back the shape and strides. So, given those (assuming those are saved before the x to y conversion), it would be simply -

    x = np.lib.stride_tricks.as_strided(y, x.shape, x.strides)