从具有给定步幅/步长的 numpy 数组中获取子数组 [英] Taking subarrays from numpy array with given stride/stepsize

查看:36
本文介绍了从具有给定步幅/步长的 numpy 数组中获取子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Python Numpy 数组 a.

Lets say I have a Python Numpy array a.

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

我想从这个长度为 5、步幅为 3 的数组中创建一个子序列矩阵.因此,结果矩阵将如下所示:

I want to create a matrix of sub sequences from this array of length 5 with stride 3. The results matrix hence will look as follows:

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

实现这一点的一种可能方法是使用 for 循环.

One possible way of implementing this would be using a for-loop.

result_matrix = np.zeros((3, 5))
for i in range(0, len(a), 3):
  result_matrix[i] = a[i:i+5]

在 Numpy 中是否有更简洁的方法来实现这一点?

Is there a cleaner way to implement this in Numpy?

推荐答案

方法 #1 : 使用 广播 -

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)]

方法 2 : 使用更高效的 NumPy strides -

Approach #2 : Using more efficient NumPy 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))

样品运行 -

In [143]: a
Out[143]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [144]: broadcasting_app(a, L = 5, S = 3)
Out[144]: 
array([[ 1,  2,  3,  4,  5],
       [ 4,  5,  6,  7,  8],
       [ 7,  8,  9, 10, 11]])

In [145]: strided_app(a, L = 5, S = 3)
Out[145]: 
array([[ 1,  2,  3,  4,  5],
       [ 4,  5,  6,  7,  8],
       [ 7,  8,  9, 10, 11]])

这篇关于从具有给定步幅/步长的 numpy 数组中获取子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆