c00*_*ter 34 python numpy window
有没有办法在Numpy中有效地实现1D阵列的滚动窗口?
例如,我有这个纯Python代码片段来计算1D列表的滚动标准偏差,其中observations是1D值列表,并且n是标准差的窗口长度:
stdev = []
for i, data in enumerate(observations[n-1:]):
strip = observations[i:i+n]
mean = sum(strip) / n
stdev.append(sqrt(250*sum([(s-mean)**2 for s in strip])/(n-1)))
Run Code Online (Sandbox Code Playgroud)
有没有办法在Numpy中完全执行此操作,即没有任何Python循环?标准偏差是微不足道的numpy.std,但滚动窗口部分完全残留我.
我发现这篇关于Numpy滚动窗口的博文,但它似乎不适用于1D阵列.
so1*_*311 53
只需使用博客代码,但将您的功能应用于结果.
即
numpy.std(rolling_window(observations, n), 1)
Run Code Online (Sandbox Code Playgroud)
你在哪里(来自博客):
def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
Run Code Online (Sandbox Code Playgroud)
Lel*_*rth 13
我尝试在具有形状的 2D 数组上使用上面列出的so12311的答案[samples, features],以获得具有[samples, timesteps, features]用于卷积或 lstm 神经网络的形状的输出数组,但它工作得不太正确。在深入研究 strides 的工作原理后,我意识到它是沿着最后一个轴移动窗口,所以我做了一些调整,以便窗口沿着第一个轴移动:
def rolling_window(a, window_size):
shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
strides = (a.strides[0],) + a.strides
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
Run Code Online (Sandbox Code Playgroud)
注意:如果您仅使用一维输入数组,则输出没有区别。在我的搜索中,这是第一个接近我想要做的结果,所以我添加它是为了帮助任何其他人寻找类似的答案。
只有一行代码...
import pandas as pd
pd.Series(observations).rolling(n).std()
Run Code Online (Sandbox Code Playgroud)
从 开始Numpy 1.20,您可以直接获得一个滚动窗口sliding_window_view:
from numpy.lib.stride_tricks import sliding_window_view
sliding_window_view(np.array([1, 2, 3, 4, 5, 6]), window_shape = 3)
# array([[1, 2, 3],
# [2, 3, 4],
# [3, 4, 5],
# [4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)
基于后面的答案,这里我添加了滚动一维 numpy 数组的代码,选择窗口大小和窗口步数频率。
a = np.arange(50)
def rolling_window(array, window_size,freq):
shape = (array.shape[0] - window_size + 1, window_size)
strides = (array.strides[0],) + array.strides
rolled = np.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)
return rolled[np.arange(0,shape[0],freq)]
rolling_window(a,10,5)
Run Code Online (Sandbox Code Playgroud)
输出:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[35, 36, 37, 38, 39, 40, 41, 42, 43, 44],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23404 次 |
| 最近记录: |