Mak*_*dis 5 python numpy theano
我试图在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)
Run Code Online (Sandbox Code Playgroud)
|-------|每次迭代的输入在哪里.
我试图找出最有效的方法,也许使用某种形式的引用或操纵步幅,但我还没有设法让一些东西工作,即使是纯粹的numpy.
我找到的一个可能的解决方案可以在这里找到,但我无法弄清楚如何使用步幅,我没有看到与theano一起使用它的方法.
小智 3
您可以构建一个包含每个时间步切片的起始索引的向量,并调用 Scan 将该向量作为序列,将原始向量作为非序列。然后,在 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)
Run Code Online (Sandbox Code Playgroud)
使用您的参数运行该函数会产生输出:
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.]]
Run Code Online (Sandbox Code Playgroud)