title: Using numpy `as_strided` function to create patches, tiles, rolling or sliding windows of arbitrary dimension
body: <p>Spent a while this morning looking for a generalized question to point duplicates to for questions about <a href="https://stackoverflow.com/questions/7542135/sliding-window-using-as-strided-function-in-numpy"><code>as_strided</code></a> and/or <a href="https://stackoverflow.com/questions/45950124/creating-image-tiles-mn-of-original-image-using-python-and-numpy">how to make generalized window functions</a>.  There seem to be a lot of <a href="https://stackoverflow.com/questions/45685772/will-results-of-numpy-as-strided-depend-on-input-dtype/45812234#45812234">questions</a> on how to (safely) create patches, sliding windows, rolling windows, tiles, or views onto an array for machine learning, convolution, image processing and/or numerical integration. </p>
  
  <p>I'm looking for a generalized function that can accept a <code>window</code>, <code>step</code> and <code>axis</code> parameter and return an <code>as_strided</code> view for over arbitrary dimensions.  I will give my answer below, but I'm interested if anyone can make a more efficient method, as I'm not sure using <code>np.squeeze()</code> is the best method, I'm not sure my <code>assert</code> statements make the function safe enough to write to the resulting view, and I'm not sure how to handle the edge case of <code>axis</code> not being in ascending order.</p>
  
  <p><strong>DUE DILIGENCE</strong></p>
  
  <p>The most generalized function I can find is <a href="https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/image.py#L241" rel="noreferrer"><code>sklearn.feature_extraction.image.extract_patches</code></a> written by @eickenberg (as well as the apparently equivalent <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#view-as-windows" rel="noreferrer"><code>skimage.util.view_as_windows</code></a>), but those are not well documented on the net, and can't do windows over fewer axes than there are in the original array (for example, <a href="https://stackoverflow.com/questions/45748469/transform-2d-array-to-a-3d-array-with-overlapping-strides/45748530#45748530">this question</a> asks for a window of a certain size over just one axis).  Also often questions want a <code>numpy</code> only answer. </p>
  
  <p>@Divakar created a generalized <code>numpy</code> function for 1-d inputs <a href="https://stackoverflow.com/questions/40084931/taking-subarrays-from-numpy-array-with-given-stride-stepsize">here</a>, but higher-dimension inputs require a bit more care.  I've made a bare bones <a href="https://stackoverflow.com/questions/45540000/batch-convolution-2d-in-numpy-without-scipy/45541172#45541172">2D window over 3d input method</a>, but it's not very extensible.</p>