Some morning passed this morning, looking for a generalized question to point out duplicates of questions about as_strided and / or how to make generalized window functions . There seem to be many questions about how to (safely) create patches, sliding windows, rolling windows, tiles or array views for machine learning, convolution, image processing and / or numerical integration.
I am looking for a generic function that can take window , step and axis parameters and return an as_strided for arbitrary dimensions. I will give my answer below, but I am wondering if anyone can make a more efficient method, since I am not sure that using np.squeeze() is the best method, I am not sure that my assert make the function safe enough to write the resulting view, and I'm not sure how to handle the boundary case of the axis not in ascending order.
DUE DILIGENCE
The most generalized function I can find is sklearn.feature_extraction.image.extract_patches written by @eickenberg (and also apparently equivalent to skimage.util.view_as_windows ), but they are not well documented on the network and cannot make windows with less the number of axes than in the original array (for example, this question asks for a window of a certain size along only one axis). Also often questions require a numpy answer.
@Divakar created a generic numpy function for 1-d inputs here , but higher level inputs require a bit more caution. I made a bare-bone 2D window on top of the three-dimensional input method , but it is not very extensible.
source share