代码片段如下:
t = tensor.arange(1, K)
results, updates = theano.scan(fn=updatefunc, sequences=t, ...)
扫描过程将沿着 t 迭代。然而,当 K<=1 时,t 将是一个空范围,然后 theano.scan() 将崩溃。有什么办法可以解决这个问题吗?
请您参考如下方法:
您可以使用 theano.ifelse.ifelse 仅当序列中包含某些元素时才计算扫描。例如:
import theano
import theano.tensor as tt
import theano.ifelse
def step(x_t, s_tm1):
return s_tm1 + x_t
def compile():
K = tt.lscalar()
t = tt.arange(1, K)
zero = tt.constant(0, dtype='int64')
outputs, _ = theano.scan(step, sequences=[t], outputs_info=[zero])
output = theano.ifelse.ifelse(tt.gt(K, 1), outputs[-1], zero)
return theano.function([K], outputs=[output])
def main():
f = compile()
print f(3)
print f(2)
print f(1)
print f(0)
print f(-1)
main()
打印
[array(3L, dtype=int64)]
[array(1L, dtype=int64)]
[array(0L, dtype=int64)]
[array(0L, dtype=int64)]
[array(0L, dtype=int64)]
