首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算Tensorflow中的所有二阶导数(只有Hessian矩阵的对角线)?

如何计算Tensorflow中的所有二阶导数(只有Hessian矩阵的对角线)?
EN

Stack Overflow用户
提问于 2016-07-05 10:23:35
回答 3查看 6K关注 0票数 13

我有一个损失值/函数,我想计算关于张量f ( n)的所有二阶导数。我成功地使用了tf.gradients两次,但是当第二次应用它时,它会在第一个输入中对派生项进行求和(请参阅我的代码中的second_derivatives )。

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

代码语言:javascript
复制
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,f0,0)会努力检索关于f_0的二阶导数,但似乎tensorflow不允许从张量的一个片段中导出。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-06-28 14:15:32

现在想想tf.hessians,

代码语言:javascript
复制
tf.hessians(loss, f)

docs/python/tf/hessians

票数 1
EN

Stack Overflow用户

发布于 2016-07-05 13:49:10

tf.gradients([f1,f2,f3],...)也计算f=f1+f2+f3的梯度,对于x[0]的区分也是有问题的,因为x[0]引用的是一个新的Slice节点,它不是您丢失的祖先,因此与它相关的导数将是None。您可以使用packx[0], x[1], ...粘合到xx中,从而使您的损失依赖于xx而不是x。另一种方法是为单个组件使用单独的变量,在这种情况下,计算Hessian会类似于这样。

代码语言:javascript
复制
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()

你终究会明白的

代码语言:javascript
复制
[[ 2.  0.]
 [ 0.  2.]]
票数 8
EN

Stack Overflow用户

发布于 2020-07-03 11:34:38

以下函数在Tensorflow 2.0中计算第二导数( Hessian矩阵的对角线):

代码语言:javascript
复制
%tensorflow_version 2.x  # Tells Colab to load TF 2.x
import tensorflow as tf

def calc_hessian_diag(f, x):
    """
    Calculates the diagonal entries of the Hessian of the function f
    (which maps rank-1 tensors to scalars) at coordinates x (rank-1
    tensors).
    
    Let k be the number of points in x, and n be the dimensionality of
    each point. For each point k, the function returns

      (d^2f/dx_1^2, d^2f/dx_2^2, ..., d^2f/dx_n^2) .

    Inputs:
      f (function): Takes a shape-(k,n) tensor and outputs a
          shape-(k,) tensor.
      x (tf.Tensor): The points at which to evaluate the Laplacian
          of f. Shape = (k,n).
    
    Outputs:
      A tensor containing the diagonal entries of the Hessian of f at
      points x. Shape = (k,n).
    """
    # Use the unstacking and re-stacking trick, which comes
    # from https://github.com/xuzhiqin1990/laplacian/
    with tf.GradientTape(persistent=True) as g1:
        # Turn x into a list of n tensors of shape (k,)
        x_unstacked = tf.unstack(x, axis=1)
        g1.watch(x_unstacked)

        with tf.GradientTape() as g2:
            # Re-stack x before passing it into f
            x_stacked = tf.stack(x_unstacked, axis=1) # shape = (k,n)
            g2.watch(x_stacked)
            f_x = f(x_stacked) # shape = (k,)
        
        # Calculate gradient of f with respect to x
        df_dx = g2.gradient(f_x, x_stacked) # shape = (k,n)
        # Turn df/dx into a list of n tensors of shape (k,)
        df_dx_unstacked = tf.unstack(df_dx, axis=1)

    # Calculate 2nd derivatives
    d2f_dx2 = []
    for df_dxi,xi in zip(df_dx_unstacked, x_unstacked):
        # Take 2nd derivative of each dimension separately:
        #   d/dx_i (df/dx_i)
        d2f_dx2.append(g1.gradient(df_dxi, xi))
    
    # Stack 2nd derivates
    d2f_dx2_stacked = tf.stack(d2f_dx2, axis=1) # shape = (k,n)
    
    return d2f_dx2_stacked

下面是一个使用f(x) = ln(r)函数的例子,其中x是3D坐标,r是半径是球形坐标:

代码语言:javascript
复制
f = lambda q : tf.math.log(tf.math.reduce_sum(q**2, axis=1))
x = tf.random.uniform((5,3))

d2f_dx2 = calc_hessian_diag(f, x)
print(d2f_dx2)

遗嘱看起来是这样的:

代码语言:javascript
复制
tf.Tensor(
[[ 1.415968    1.0215727  -0.25363517]
 [-0.67299247  2.4847088   0.70901346]
 [ 1.9416015  -1.1799507   1.3937857 ]
 [ 1.4748447   0.59702784 -0.52290654]
 [ 1.1786096   0.07442689  0.2396735 ]], shape=(5, 3), dtype=float32)

我们可以通过计算拉普拉斯(即通过计算赫森矩阵的对角线)来检验实现的正确性,并与我们选择的函数2 / r^2的理论答案进行比较。

代码语言:javascript
复制
print(tf.reduce_sum(d2f_dx2, axis=1)) # Laplacian from summing above results
print(2./tf.math.reduce_sum(x**2, axis=1)) # Analytic expression for Lapalcian

我得到以下信息:

代码语言:javascript
复制
tf.Tensor([2.1839054 2.5207298 2.1554365 1.5489659 1.49271  ], shape=(5,), dtype=float32)
tf.Tensor([2.1839058 2.5207298 2.1554365 1.5489662 1.4927098], shape=(5,), dtype=float32)

他们同意在四舍五入误差范围内。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38200982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档