From this post https://stackoverflow.com/a/40085052/3293881, 我们可以用strided_app
基本上将滑动视图放入数组中,它还允许我们指定跳跃大小/步长。然后,我们只需使用np.std
沿着第二个轴的最终输出,就像这样 -
np.std(strided_app(x, framesize, hopsize), axis=1)
运行样品进行验证 -
In [162]: x = np.random.randint(0,9,(11))
In [163]: framesize = 5
In [164]: hopsize = 3
In [165]: np.array([np.std(x[i:i+framesize]) \
for i in range(0, len(x)-framesize+1, hopsize)])
Out[165]: array([ 1.62480768, 2.05912603, 1.78885438])
In [166]: np.std(strided_app(x, framesize, hopsize), axis=1)
Out[166]: array([ 1.62480768, 2.05912603, 1.78885438])
作为输入数组的视图,这些跨步操作必须非常高效。让我们来看看吧!
运行时测试
循环方法 -
def loopy_app(x, framesize, hopsize):
return [np.std(x[i:i+framesize]) \
for i in range(0, len(x)-framesize+1, hopsize)]
时间安排 -
In [185]: x = np.random.randint(0,9,(1001))
In [186]: framesize = 5
In [187]: hopsize = 3
In [188]: %timeit loopy_app(x, framesize, hopsize)
10 loops, best of 3: 17.8 ms per loop
In [189]: %timeit np.std(strided_app(x, framesize, hopsize), axis=1)
10000 loops, best of 3: 111 µs per loop
因此,要回答效率问题strides
,时间安排应该有助于证明这一点!