如何监控theano共享变量的梯度

How to monitor gradients of theano shared variables

如何获取theano共享变量的梯度值?也就是说,
如何制作 theano.function( outputs=TT.grad( shared vars )) ?

以最小训练示例为例 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

inputs : list of either Variable or In instances. Function parameters, these are not allowed to be shared variables.

一个人可以复制整个符号图

gradients = TT.grad(cost, [W])

带输入变量,不共享;一定是更好的方法, 也许 givens= ?

相关:

只是不要将 W 作为输入参数传递:

gradf = theano.function( [x, target], TT.grad(...) )

它将只使用 W 的当前值。 如果你想让它计算不同于当前值的 W 的其他值的梯度,这将更具挑战性,但它似乎不是你想要的。