简体   繁体   English

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

[英]How can I assign/update subset of tensor shared variable in Theano?

When compiling a function in theano , a shared variable(say X) can be updated by specifying updates=[(X, new_value)] . theano编译函数时,可以通过指定updates=[(X, new_value)]来更新共享变量(比如X)。 Now I am trying to update only subset of a shared variable: 现在我试图只更新共享变量的子集:

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'

The codes will raise a error "update target must be a SharedVariable", I guess that means update targets can't be non-shared variables. 代码将引发错误“更新目标必须是SharedVariable”,我猜这意味着更新目标不能是非共享变量。 So is there any way to compile a function to just udpate subset of shared variables? 那么有没有办法编译一个函数只是udpate共享变量的子集?

Use set_subtensor or inc_subtensor : 使用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]

There's now a page about this in the Theano FAQ: http://deeplearning.net/software/theano/tutorial/faq_tutorial.html 现在有一个关于Theano FAQ的页面: http//deeplearning.net/software/theano/tutorial/faq_tutorial.html

This code should solve your problem: 此代码应该可以解决您的问题:

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]

And here is the introduction about shared variables in the official tutorial . 以下是官方教程中关于共享变量介绍

Please ask, if you have further questions! 如果您还有其他问题,请询问!

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

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