擅长:python、mysql、java
<p>在这篇文章中,是一种使用<code>strided-indexing scheme</code>的方法,它基本上是在输入数组中创建一个视图,因此创建视图非常有效,并且作为一个视图不会占用更多的内存空间。
此外,这也适用于具有通用维数的nArray</p>
<p>以下是实施方案-</p>
<pre><code>def strided_axis0(a, L):
# Store the shape and strides info
shp = a.shape
s = a.strides
# Compute length of output array along the first axis
nd0 = shp[0]-L+1
# Setup shape and strides for use with np.lib.stride_tricks.as_strided
# and get (n+1) dim output array
shp_in = (nd0,L)+shp[1:]
strd_in = (s[0],) + s
return np.lib.stride_tricks.as_strided(a, shape=shp_in, strides=strd_in)
</code></pre>
<p><code>4D</code>数组案例的运行示例-</p>
<pre><code>In [44]: a = np.random.randint(11,99,(10,4,2,3)) # Array
In [45]: L = 5 # Window length along the first axis
In [46]: out = strided_axis0(a, L)
In [47]: np.allclose(a[0:L], out[0]) # Verify outputs
Out[47]: True
In [48]: np.allclose(a[1:L+1], out[1])
Out[48]: True
In [49]: np.allclose(a[2:L+2], out[2])
Out[49]: True
</code></pre>