pythonshapescupystride

How to use cupy.lib.stride_tricks.as_strided(x, shape=None, strides=None)


I was using:

np.lib.stride_tricks.sliding_window_view

with a 1D-array and two parameters (the array and the length of the subset n) to slice it into slices of n elements (n < 1D-array.shape, of course)

I think I can go faster with cupy and I started with:

cupy.lib.stride_tricks.as_strided(x, shape=None, strides=None)

Documentation is here.

Unfortunately, I cannot manage to run such a simple code:

import cupy as cp
x  = [4,2,1,1,1,2,3,4]
y = cp.lib.stride_tricks.as_strided(x, shape=None, strides=2)
print(y)  # expecting a 2D-array of size 7, 2

I get:

runfile('C:/Users/didie/.spyder-py3/untitled2.py', wdir='C:/Users/didie/.spyder-py3')
Traceback (most recent call last):

  File ~\miniconda3\envs\spyder-cf\lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File c:\users\didie\.spyder-py3\untitled2.py:28
    y = cp.lib.stride_tricks.as_strided(x, shape=None, strides=2)

  File ~\miniconda3\envs\spyder-cf\lib\site-packages\cupy\lib\stride_tricks.py:35 in as_strided
    shape = x.shape if shape is None else tuple(shape)

AttributeError: 'list' object has no attribute 'shape'

It may not be hard to solve...

EDIT: new code

x  = cp.array([4,2,1,1,1,2,3,4])
y = cp.lib.stride_tricks.as_strided(x, None, strides=2)
print(y)  # expecting a 2D-array of size 7, 2

leading to:

runfile('C:/Users/didie/.spyder-py3/untitled2.py', wdir='C:/Users/didie/.spyder-py3')
Traceback (most recent call last):

  File ~\miniconda3\envs\spyder-cf\lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File c:\users\didie\.spyder-py3\untitled2.py:27
    y = cp.lib.stride_tricks.as_strided(x, None, strides=2)

  File ~\miniconda3\envs\spyder-cf\lib\site-packages\cupy\lib\stride_tricks.py:36 in as_strided
    strides = x.strides if strides is None else tuple(strides)

TypeError: 'int' object is not iterable

Solution

  • Here is the solution I found, in case somebody is looking for it (l being the window):

    y = cp.lib.stride_tricks.as_strided(x, shape=(x.shape[0] - l + 1, l), strides=x.strides + (x.strides[-1],))
    

    Based on: https://rigtorp.se/2011/01/01/rolling-statistics-numpy.html