簡體   English   中英

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

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

theano編譯函數時,可以通過指定updates=[(X, new_value)]來更新共享變量(比如X)。 現在我試圖只更新共享變量的子集:

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'

代碼將引發錯誤“更新目標必須是SharedVariable”,我猜這意味着更新目標不能是非共享變量。 那么有沒有辦法編譯一個函數只是udpate共享變量的子集?

使用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]

現在有一個關於Theano FAQ的頁面: http//deeplearning.net/software/theano/tutorial/faq_tutorial.html

此代碼應該可以解決您的問題:

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]

以下是官方教程中關於共享變量介紹

如果您還有其他問題,請詢問!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM