我正在尝试在theano中实现一个扫描循环,给定张量将使用"移动切片"输入。它不必实际上是一个移动切片,它可以是一个预处理张量到另一个张量,代表移动切片。
本质:
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
|-------| (first iteration)
|-------| (second iteration)
|-------| (third iteration)
...
...
...
|-------| (last iteration)
其中|-------|
是每次迭代的输入。
我试图找出最有效的方法,也许使用某种形式的引用或操纵步幅,但我还是设法让一些东西工作,即使是纯粹的numpy。
我找到的一个可能的解决方案可以找到here,但我无法弄清楚如何使用步幅,而且我也没有找到与theano一起使用的方法。
答案 0 :(得分:3)
您可以在每个时间步长构建一个包含切片起始索引的向量,并使用该向量作为序列调用Scan,将原始向量作为非序列调用。然后,在“扫描”内部,您可以在每次迭代时获得所需的切片。
我添加了一个示例,其中我还将切片的大小设置为符号输入,以防您想要将其从Theano函数的一次调用更改为下一次:
import theano
import theano.tensor as T
# Input variables
x = T.vector("x")
slice_size = T.iscalar("slice_size")
def step(idx, vect, length):
# From the idx of the start of the slice, the vector and the length of
# the slice, obtain the desired slice.
my_slice = vect[idx:idx + length]
# Do something with the slice here. I don't know what you want to do
# to I'll just return the slice itself.
output = my_slice
return output
# Make a vector containing the start idx of every slice
slice_start_indices = T.arange(x.shape[0] - slice_size + 1)
out, updates = theano.scan(fn=step,
sequences=[slice_start_indices],
non_sequences=[x, slice_size])
fct = theano.function([x, slice_size], out)
使用您的参数运行函数会产生输出:
print fct(range(17), 5)
[[ 0. 1. 2. 3. 4.]
[ 1. 2. 3. 4. 5.]
[ 2. 3. 4. 5. 6.]
[ 3. 4. 5. 6. 7.]
[ 4. 5. 6. 7. 8.]
[ 5. 6. 7. 8. 9.]
[ 6. 7. 8. 9. 10.]
[ 7. 8. 9. 10. 11.]
[ 8. 9. 10. 11. 12.]
[ 9. 10. 11. 12. 13.]
[ 10. 11. 12. 13. 14.]
[ 11. 12. 13. 14. 15.]
[ 12. 13. 14. 15. 16.]]
答案 1 :(得分:1)
您可以使用this rolling_window recipe:
import numpy as np
def rolling_window_lastaxis(arr, winshape):
"""
Directly taken from Erik Rigtorp's post to numpy-discussion.
http://www.mail-archive.com/numpy-discussion@scipy.org/msg29450.html
(Erik Rigtorp, 2010-12-31)
See also:
http://mentat.za.net/numpy/numpy_advanced_slides/ (Stéfan van der Walt, 2008-08)
https://stackoverflow.com/a/21059308/190597 (Warren Weckesser, 2011-01-11)
https://stackoverflow.com/a/4924433/190597 (Joe Kington, 2011-02-07)
https://stackoverflow.com/a/4947453/190597 (Joe Kington, 2011-02-09)
"""
if winshape < 1:
raise ValueError("winshape must be at least 1.")
if winshape > arr.shape[-1]:
print(winshape, arr.shape)
raise ValueError("winshape is too long.")
shape = arr.shape[:-1] + (arr.shape[-1] - winshape + 1, winshape)
strides = arr.strides + (arr.strides[-1], )
return np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)
x = np.arange(17)
print(rolling_window_lastaxis(x, 5))
打印
[[ 0 1 2 3 4]
[ 1 2 3 4 5]
[ 2 3 4 5 6]
[ 3 4 5 6 7]
[ 4 5 6 7 8]
[ 5 6 7 8 9]
[ 6 7 8 9 10]
[ 7 8 9 10 11]
[ 8 9 10 11 12]
[ 9 10 11 12 13]
[10 11 12 13 14]
[11 12 13 14 15]
[12 13 14 15 16]]
请注意,甚至有更好的扩展,例如可以翻转多维窗口的Joe Kington's rolling_window,以及Sebastian Berg's implementation,此外,它还可以逐步跳转。