如何在Theano中分配/更新张量共享变量的子集?

gag*_*zhn 25 python numpy theano

编译函数时theano,可以通过指定更新共享变量(比如X)updates=[(X, new_value)].现在我试图只更新共享变量的子集:

from theano import tensor as T
from theano import function
import numpy

X = T.shared(numpy.array([0,1,2,3,4]))
Y = T.vector()
f = function([Y], updates=[(X[2:4], Y)] # error occur:
                                        # 'update target must 
                                        # be a SharedVariable'
Run Code Online (Sandbox Code Playgroud)

代码将引发错误"更新目标必须是SharedVariable",我猜这意味着更新目标不能是非共享变量.那么有没有办法编译一个函数只是udpate共享变量的子集?

dpf*_*ied 32

使用set_subtensorinc_subtensor:

from theano import tensor as T
from theano import function, shared
import numpy

X = shared(numpy.array([0,1,2,3,4]))
Y = T.vector()
X_update = (X, T.set_subtensor(X[2:4], Y))
f = function([Y], updates=[X_update])
f([100,10])
print X.get_value() # [0 1 100 10 4]
Run Code Online (Sandbox Code Playgroud)

现在有一个关于Theano FAQ的页面:http://deeplearning.net/software/theano/tutorial/faq_tutorial.html

  • [这里](http://deeplearning.net/software/theano/tutorial/faq_tutorial.html)它说`inc_subtensor`比`set_subtensor`更受欢迎 (2认同)

Fra*_*ter 0

这段代码应该可以解决您的问题:

from theano import tensor as T
from theano import function, shared
import numpy

X = shared(numpy.array([0,1,2,3,4], dtype='int'))
Y = T.lvector()
X_update = (X, X[2:4]+Y)
f = function(inputs=[Y], updates=[X_update])
f([100,10])
print X.get_value()
# output: [102 13]
Run Code Online (Sandbox Code Playgroud)

这里是官方教程中关于共享变量的介绍

如果您还有其他问题,请询问!