Python as_strided method, how does it work?

49 Views Asked by At

I am trying to do some anomaly detection in one of my assignments and I am trying to create sliding windows, but I want to make them so that one window does not overlap with the other. For example array = [1, 2, 3, 4, 5, 6] I want to get to this result result = [[1, 2, 3], [4, 5, 6]] Apparently you can use either as_strided or sliding_window_view methods, but the second one did not work so well, but if anyone knows a solution to this it is highly appreciated

2

There are 2 best solutions below

0
hpaulj On

Your 1d array:

In [234]: x=np.arange(1,7)

A simple reshape:

In [235]: x.reshape(-1,3)
Out[235]: 
array([[1, 2, 3],
       [4, 5, 6]])

sliding windows creates (3,) windows, with full overlap

In [236]: np.lib.stride_tricks.sliding_window_view(x,3)
Out[236]: 
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])

from that we can easily slice out the no-overlap elements:

In [237]: np.lib.stride_tricks.sliding_window_view(x,3)[::3]
Out[237]: 
array([[1, 2, 3],
       [4, 5, 6]])

To use as_strided, we have to understand strides. sliding_windows does this thinking for us:

In [238]: x.strides
Out[238]: (4,)

In [239]: np.lib.stride_tricks.as_strided(x,shape=(2,3),strides=(12,4))
Out[239]: 
array([[1, 2, 3],
       [4, 5, 6]])

That 12 is (3*4)

The equivalent of sliding_windows:

In [240]: np.lib.stride_tricks.as_strided(x,shape=(4,3),strides=(4,4))
Out[240]: 
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])

sliding_windows is easier to use, since we don't need to know about strides, and it makes sure that the result is the correct size.

0
Manoj Bhosle On
import numpy as np

# Your initial array
array = np.array([1, 2, 3, 4, 5, 6])

# Reshape the array into a 2D array where each sub-array is a window
# This only works if the length of the array is divisible by the window size
result = array.reshape(-1, 2)

print(result)