python - 在 theano 张量上重叠迭代

标签 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)

其中 |--------| 是每次迭代的输入。

我正在尝试找出最有效的方法来做到这一点,也许使用某种形式的引用或操纵步幅,但即使对于纯 numpy,我也没有设法让某些东西起作用。

可以找到我找到的一个可能的解决方案 here ,但我无法弄清楚如何使用步幅,而且我看不到将其与 theano 一起使用的方法。

最佳答案

您可以在每个时间步构建一个包含切片起始索引的向量,然后将该向量作为序列调用 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)

使用您的参数运行该函数会产生输出:

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

关于python - 在 theano 张量上重叠迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733166/

相关文章:

python - SCons - 为 CUDA、CORBA 等集成自定义构建器

Python 等同于 Java 的 JNLP Web Start?

python - Lambda 函数和 0

python - 如何使用 scipy 的 affine_transform 对彩色图像进行任意仿射变换?

python - 将 rec.array 转换为数据帧

python - Pytorch 相当于 Numpy 的 logical_and 和 kin?

python - 如何在python中提取与fft值相关的频率

ubuntu - 如何在 Ubuntu 16.04 上使用 Theano 和 GPU?

python - Numpy 中的 dimshuffle 等效函数

python - 如何防止被零除或替换 Theano 中的无限值?