0
如何獲取theano共享變量的梯度值?那就是,
怎麼製作theano.function(outputs=TT.grad(shared vars))
?如何監控theano共享變量的梯度
採取在 Marek Rei's theano tutorial極小訓練示例:
import theano
import theano.tensor as TT
import numpy as np
floatx = theano.config.floatX
#...............................................................................
x = TT.fvector('x')
target = TT.fscalar('target')
W = theano.shared(np.asarray([0.2, 0.7]), 'W') # state
y = (x * W).sum()
cost = TT.sqr(target - y)
gradients = TT.grad(cost, [W])
W_updated = W - (0.1 * gradients[0])
updates = [(W, W_updated)]
f = theano.function([x, target], y, updates=updates)
x0 = np.array([1.0, 1.0]).astype(floatx)
target0 = 20.0
for i in xrange(10):
output = f(x0, target0)
Wval = W.get_value().astype(floatx)
grad = gradf(x0, Wval, target0)[0] # <--- how to define gradf ?
print "f %-8.3g W %s grad %s" % (
output, Wval, grad)
>>>
f 0.9 W [4.02 4.52] grad [-22.9 -22.9]
f 8.54 W [6.31 6.81] grad [-13.8 -13.8]
...
一個不能直接
gradf = theano.function([x, W, target], TT.grad(...))
因爲theano.function
說
輸入:可變或在實例中的列表。 函數參數,這些不允許是共享變量。
一個可以使整個圖形符號的副本
gradients = TT.grad(cost, [W])
具有輸入變量,而不是共享;必須是更好的方式, 也許與givens=
?
相關:
[Theano]How to evaluate gradient based on shared variables
對,謝謝。對於另一個人的gradf,可以'Wsave = W.get_value(); W.set_value(anotherW); g = gradf(...); W.set_value(Wsave)'?似乎令人費解。 – denis