繁体   English   中英

在theano中定义函数的正确方法?

[英]The right way to define a function in theano?

背景:

通常,我将使用诸如'x = fmatrix()'之类的输入定义一个theano函数,但是,在修改keras(基于theano的深度学习库)以使其与CTC成本兼容时,我注意到了一个非常奇怪的问题:如果有一个输入成本函数的声明为

x = tensor.zeros(shape=[M,N], dtype='float32')

代替

x = fmatrix()

培训过程将更快地收敛。

一个简化的问题:

上面的整个代码很大。 因此,我尝试简化如下问题:假设一个用于计算Levenshtein编辑距离的函数为

import theano
from theano import tensor
from theano.ifelse import ifelse
def editdist(s, t):
    def update(x, previous_row, target):
        current_row = previous_row + 1
        current_row = tensor.set_subtensor(current_row[1:], tensor.minimum(current_row[1:], tensor.add(previous_row[:-1], tensor.neq(target,x))))
        current_row = tensor.set_subtensor(current_row[1:], tensor.minimum(current_row[1:], current_row[0:-1] + 1))
        return current_row
    source, target = ifelse(tensor.lt(s.shape[0], t.shape[0]), (t, s), (s, t))
    previous_row = tensor.arange(target.size + 1, dtype=theano.config.floatX)
    result, updates = theano.scan(fn = update, sequences=source, outputs_info=previous_row, non_sequences=target, name='editdist')
    return result[-1,-1]

然后我定义两个函数f1和f2:

x1 = tensor.fvector()
x2 = tensor.fvector()
r1 = editdist(x1,x2)
f1 = theano.function([x1,x2], r1)
x3 = tensor.zeros(3, dtype='float32')
x4 = tensor.zeros(3, dtype='float32')
r2 = editdist(x3,x4)
f2 = theano.function([x3,x4], r2)

使用f1和f2计算时,结果不同:

>>f1([1,2,3],[1,3,3])
   array(1.0)

>>f2([1,2,3],[1,3,3])
   array(3.0)

f1给出正确的结果,但f2没有给出正确的结果。

所以我的问题是:定义theano函数的正确方法是什么? 而且,f2到底出了什么问题?

更新:

我正在使用版本0.8.0.dev0的theano。 我只是尝试theano 0.7.0,f1和f2都给出正确的结果。 也许这是theano的错误?

更新_1st 1-27-2016:

根据@lamblin对此问题的解释( https://github.com/Theano/Theano/issues/3925#issuecomment-175088918 ),这实际上是theano的错误,并且已在最新版本中修复(1- 26-2016)版本。 为了方便起见,此处引用了lamblin的解释:

第一种方法是最自然的方法,但理论上两者应该是等效的。 x3和x4被创建为“分配”操作的输出,其输入将为常数3,而不是诸如x1和x2之类的自由输入,但这无关紧要,因为您将[x3,x4]作为输入传递给theano.function,应在此处剪切计算图。

我的猜测是扫描过早优化,认为x3或x4始终保证为常数0,并做了一些简化,这些简化被证明在为它们提供值时是不正确的。 那将是扫描中的实际错误。”

Update_2nd 1-27-2016:

不幸的是,该错误尚未完全修复。 在背景部分中,我提到如果将cost函数的一个输入声明为tensor.zeros(),那么收敛过程会更快,我发现了原因:当将输入声明为tensor.zeros()时,cost函数给出了错误的结果,尽管这神秘地帮助了收敛。 我在这里( https://github.com/daweileng/TheanoDebug )管理了一个简化的问题重现演示,运行ctc_bench.py​​,您可以看到结果。

theano.tensor.zeros(...)不能采用除0外的任何其他值。

除非您向图当然添加节点,然后使用theano.tensor.set_subtensor修改零张量的theano.tensor.set_subtensor

输入张量theano.tensor.fmatrix可以采用您输入的任何值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM