gpt4 book ai didi

theano - 在 Theano 中从 scan 调用函数

转载 作者:行者123 更新时间:2023-12-04 20:01:31 26 4
gpt4 key购买 nike

我需要通过扫描多次执行 theano 函数,以便总结成本函数并将其用于梯度计算。我熟悉执行此操作的深度学习教程,但我的数据切片和其他一些复杂情况意味着我需要做一些不同的事情。
下面是我正在尝试做的一个非常简化的版本..

tn = testnet()
cost = tn.single_cost( )
x = theano.shared(numpy.asarray([7.1,2.2,3.4], dtype='float32'))
index = T.lscalar('index')
test_fn = theano.function(inputs=[index], outputs=cost,
givens={tn.x:x[index:index+1]} )

def step(curr):
return T.constant( test_fn( curr ) )
outs,_ = theano.scan(step, T.arange(2))

out_fn = theano.function(inputs=[], outputs=outs)
print out_fn()

在扫描函数中,对 test_fn(curr) 的调用给出了错误...
期望一个类似数组的对象,但发现了一个变量:也许您正试图在(可能是共享的)变量而不是数字数组上调用函数?')

即使我传入一个值数组而不是将 T.arrange(2) 放在适当的位置,我仍然会遇到相同的错误。有什么理由不能从扫描中调用函数吗?

一般来说,我想知道是否有一种方法可以使用一系列索引调用这样的函数,以便输出可以输入 T.grad() 计算(未显示)。

最佳答案

不要做两个不同的theano.functions .

一个 theano.function获取符号关系,对其进行优化并对其进行编译。你在这里做的是问theano.scan (因此 out_fn )将编译函数视为符号关系。我不确定你是否可以在技术上让它发挥作用,但这与 Theano 的想法背道而驰。

因为我不知道你的成本函数在这里做了什么,所以我不能给出一个确切的例子,但这里有一个快速的例子,它确实有效并且应该与我认为你想要做的足够相似。

x = theano.shared(np.asarray([7.1,2.2,3.4], dtype = np.float32))

v = T.vector("v")
def fv(v):
res,_ = theano.scan(lambda x: x ** 2, v)
return T.sum(res)

def f(i):
return fv(x[i:i+2])

outs,_ = theano.scan(
f,
T.arange(2)
)

fn = theano.function(
[],
outs,
)

fn()

关于theano - 在 Theano 中从 scan 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29380867/

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