2016-11-02 93 views
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

回答

0

只是不通过W作为输入参数:

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

它只是将使用W当前值。 如果您想要计算其他值为W的其他值(与当前值不同),则更具挑战性,但它看起来不是您想要的。

+0

对,谢谢。对于另一个人的gradf,可以'Wsave = W.get_value(); W.set_value(anotherW); g = gradf(...); W.set_value(Wsave)'?似乎令人费解。 – denis