How to use numpy as_strided (from np.stride_tricks) correctly?

后端 未结 3 1846
青春惊慌失措
青春惊慌失措 2021-01-20 10:32

I\'m trying to reshape a numpy array using numpy.strided_tricks. This is the guide I\'m following: https://stackoverflow.com/a/2487551/4909087

My use c

3条回答
  •  不要未来只要你来
    2021-01-20 11:18

    I was trying to do a similar operation and run into the same problem.

    In your case, as stated in this comment, the problems were:

    1. You were not taking into account the size of your element when stored in memory (int32 = 4, which can be checked using a.dtype.itemsize).
    2. You didn't specify appropriately the number of strides you had to skip, which in your case were also 4, as you were skipping only one element.

    I made myself a function based on this answer, in which I compute the segmentation of a given array, using a window of n-elements and specifying the number of elements to overlap (given by window - number_of_elements_to_skip).

    I share it here in case someone else needs it, since it took me a while to figure out how stride_tricks work:

    def window_signal(signal, window, overlap):
        """ 
        Windowing function for data segmentation.
    
        Parameters:
        ------------
        signal: ndarray
                The signal to segment.
        window: int
                Window length, in samples.
        overlap: int
                 Number of samples to overlap
    
        Returns: 
        --------
        nd-array 
                A copy of the signal array with shape (rows, window),
                where row = (N-window)//(window-overlap) + 1
        """
        N = signal.reshape(-1).shape[0] 
        if (window == overlap):
            rows = N//window
            overlap = 0
        else:
            rows = (N-window)//(window-overlap) + 1
            miss = (N-window)%(window-overlap)
            if(miss != 0):
                print('Windowing led to the loss of ', miss, ' samples.')
        item_size = signal.dtype.itemsize 
        strides = (window - overlap) * item_size
        return np.lib.stride_tricks.as_strided(signal, shape=(rows, window),
                                               strides=(strides, item_size))
    

    The solution for this case is, according to your code: as_strided(a, (len(a) - 2, 3), (4, 4))

    Alternatively, using the function window_signal:

    window_signal(a, 3, 2)

    Both return as output the following array:

    array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])
    

提交回复
热议问题