gpt4 book ai didi

python - numpy stride_tricks.as_strided 与滚动窗口的列表理解

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:00 24 4
gpt4 key购买 nike

在处理滚动窗口时,我用列表推导式的方式编写函数

[np.std(x[i:i+framesize]) for i in range(0, len(x)-framesize, hopsize)])]

最近我发现numpy.lib.stride_tricks.as_strided并发现它被广泛用于滚动窗口(例如 this post ),即使它是一个“隐藏”功能。

this issue关于为什么 stride_tricks.as_strided 没有记录,有人提到

Intentionally! It's dangerous! It was just low-level plumbing to help implement broadcast_arrays().

stride_tricks.as_strided有什么优势吗?在列表理解或 for 循环上?我看了看 the source code of stride_tricks 但收获甚微。

最佳答案

来自 this post ,我们可以使用 strided_app 基本上将滑动 View 获取到数组中,它还允许我们指定 hopsize/stepsize。然后,我们简单地在第二个轴上使用 np.std 作为最终输出,就像这样 -

np.std(strided_app(x, framesize, hopsize), axis=1)

用于验证的 sample 运行 -

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

作为输入数组的 View ,这些跨步操作必须非常高效。让我们找出答案!

运行时测试

循环方法-

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

因此,要回答关于步幅效率的问题,时间应该有助于证明这一点!

关于python - numpy stride_tricks.as_strided 与滚动窗口的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38186869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com