Home > Backend Development > Python Tutorial > How to Efficiently Extract Subarrays with Strides in NumPy?

How to Efficiently Extract Subarrays with Strides in NumPy?

Barbara Streisand
Release: 2024-12-03 18:05:16
Original
318 people have browsed it

How to Efficiently Extract Subarrays with Strides in NumPy?

Subarray Extraction with Strides in Numpy Arrays

Consider a Python Numpy array a:

a = numpy.array([1,2,3,4,5,6,7,8,9,10,11])
Copy after login

We aim to extract subarrays of length 5 with a stride of 3. This results in a matrix with the following content:

numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])
Copy after login

Cleaner Implementation

While a for-loop approach is viable, Numpy provides more efficient methods:

Approach 1: Broadcasting

This approach takes advantage of broadcasting:

def broadcasting_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    return a[S*np.arange(nrows)[:,None] + np.arange(L)]
Copy after login

Approach 2: Strides Optimization

This method utilizes Numpy's efficient strides:

def strided_app(a, L, S ):  # Window len = L, Stride len/stepsize = S
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
Copy after login

Usage Example:

a = numpy.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

broadcasting_app(a, L = 5, S = 3)
# [[ 1  2  3  4  5]
#  [ 4  5  6  7  8]
#  [ 7  8  9 10 11]]

strided_app(a, L = 5, S = 3)
# [[ 1  2  3  4  5]
#  [ 4  5  6  7  8]
#  [ 7  8  9 10 11]]
Copy after login

These approaches offer more efficient and optimized solutions for extracting subarrays with strides in Numpy arrays.

The above is the detailed content of How to Efficiently Extract Subarrays with Strides in NumPy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template