gpt4 book ai didi

Python - Theano scan() 函数

转载 作者:太空狗 更新时间:2023-10-29 20:20:04 26 4
gpt4 key购买 nike

我无法完全理解 theano.scan() 的行为。

这是一个例子:

import numpy as np
import theano
import theano.tensor as T


def addf(a1,a2):
return a1+a2

i = T.iscalar('i')
x0 = T.ivector('x0')
step= T.iscalar('step')

results, updates = theano.scan(fn=addf,
outputs_info=[{'initial':x0, 'taps':[-2]}],
non_sequences=step,
n_steps=i)

f=theano.function([x0,i,step],results)

print f([1,1],10,2)

上面的代码片段打印了以下序列,这是完全合理的:

[ 3  3  5  5  7  7  9  9 11 11]

但是,如果我将抽头索引从 -2 切换到 -1,即

outputs_info=[{'initial':x0, 'taps':[-1]}]

结果变成:

[[ 3  3]
[ 5 5]
[ 7 7]
[ 9 9]
[11 11]
[13 13]
[15 15]
[17 17]
[19 19]
[21 21]]

而不是我认为合理的(只取向量的最后一个值并加 2):

[ 3  5  7  9 11 13 15 17 19 21]

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

当你使用taps=[-1]时,scan假设输出info中的信息是原样使用的。这意味着 addf 函数将使用向量和 non_sequence 作为输入来调用。如果将 x0 转换为标量,它将按预期工作:

import numpy as np
import theano
import theano.tensor as T


def addf(a1,a2):
print a1.type
print a2.type
return a1+a2

i = T.iscalar('i')
x0 = T.iscalar('x0')
step= T.iscalar('step')

results, updates = theano.scan(fn=addf,
outputs_info=[{'initial':x0, 'taps':[-1]}],
non_sequences=step,
n_steps=i)

f=theano.function([x0,i,step],results)

print f(1,10,2)

这给出了这个输出:

TensorType(int32, scalar)
TensorType(int32, scalar)
[ 3 5 7 9 11 13 15 17 19 21]

在你的例子中,当它执行 addf(vector,scalar) 时,它广播元素值。

换句话说,如果 taps 是 [-1],x0 将“按原样”传递给内部函数。如果 taps 包含任何其他内容,则传递给内部函数的内容将比 x0 小一维,因为 x0 必须提供许多初始步长值(-2 和 -1)。

关于Python - Theano scan() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26718812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com