2016-07-05 98 views
8

我有一个损失值/函数,我想计算关于张量的所有二阶导数f(的大小为n)。我设法使用tf.gradients两次,但第二次应用它时,它将第一个输入中的衍生物相加(请参阅我的代码中的second_derivatives)。如何在Tensorflow中计算所有二阶导数(只有Hessian矩阵的对角线)?

此外,我设法检索Hessian矩阵,但我只想计算其对角线以避免额外计算。

import tensorflow as tf 
import numpy as np 

f = tf.Variable(np.array([[1., 2., 0]]).T) 
loss = tf.reduce_prod(f ** 2 - 3 * f + 1) 

first_derivatives = tf.gradients(loss, f)[0] 

second_derivatives = tf.gradients(first_derivatives, f)[0] 

hessian = [tf.gradients(first_derivatives[i,0], f)[0][:,0] for i in range(3)] 

model = tf.initialize_all_variables() 
with tf.Session() as sess: 
    sess.run(model) 
    print "\nloss\n", sess.run(loss) 
    print "\nloss'\n", sess.run(first_derivatives) 
    print "\nloss''\n", sess.run(second_derivatives) 
    hessian_value = np.array(map(list, sess.run(hessian))) 
    print "\nHessian\n", hessian_value 

我的想法是,tf.gradients(first_derivatives,F [0,0])[0]将努力对于检索实例的二阶导数F_0但似乎tensorflow不允许从一张张量中派生出来。

回答

6

tf.gradients([f1,f2,f3],...)计算的f=f1+f2+f3 另外,对于分化为x[0]是有问题的,因为梯度x[0]指的是不你的损失的祖先,相对于这样的衍生物,以这将是NoneSlice节点。您可以通过使用packx[0], x[1], ...粘合到xx中并避免损失取决于xx而不是x。另一种方法是对单个组件使用单独的变量,在这种情况下,计算Hessian将看起来像这样。

def replace_none_with_zero(l): 
    return [0 if i==None else i for i in l] 

tf.reset_default_graph() 

x = tf.Variable(1.) 
y = tf.Variable(1.) 
loss = tf.square(x) + tf.square(y) 
grads = tf.gradients([loss], [x, y]) 
hess0 = replace_none_with_zero(tf.gradients([grads[0]], [x, y])) 
hess1 = replace_none_with_zero(tf.gradients([grads[1]], [x, y])) 
hessian = tf.pack([tf.pack(hess0), tf.pack(hess1)]) 
sess = tf.InteractiveSession() 
sess.run(tf.initialize_all_variables()) 
print hessian.eval() 

你会看到

[[ 2. 0.] 
[ 0. 2.]] 
+0

坦克的回答,遗憾的是它并没有真正帮助,因为我会喜欢只检索Hessian的对角线。我试着用x [0],x [1] ......来包装,但它仍然给我一个错误。 –

+1

'hess0 = tf.gradients([grads [0]],[x]); hess1 = tf.gradients([grads [1]],[y])'只会计算对角线条目 –

+0

谢谢,我终于设法使用你上次回复的和tf.pack()做到了! –