TensorFlow:计算Hessian矩阵(和高阶导数)

2024-05-15 21:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够计算出损失函数的高阶导数。至少我希望能够计算出Hessian矩阵。目前,我正在计算对Hessian的数值近似,但这是更昂贵的,更重要的是,据我所知,如果矩阵病态(条件数非常大),则是不准确的。

no通过符号循环来实现这一点,请参见here,但是Tensorflow似乎还不支持符号控制流,请参见here。在TF github页面上也出现了类似的问题,请参见here,但似乎有一段时间没有人跟进这个问题。

有没有人知道最近的发展或计算张量流中高阶导数(象征性的)的方法?


Tags: 函数nogithubheretftensorflow符号矩阵
1条回答
网友
1楼 · 发布于 2024-05-15 21:31:35

好吧,你可以不费吹灰之力就计算出海森矩阵!

假设有两个变量:

x = tf.Variable(np.random.random_sample(), dtype=tf.float32)
y = tf.Variable(np.random.random_sample(), dtype=tf.float32)

以及使用这两个变量定义的函数:

f = tf.pow(x, cons(2)) + cons(2) * x * y + cons(3) * tf.pow(y, cons(2)) + cons(4) * x + cons(5) * y + cons(6)

其中:

def cons(x):
    return tf.constant(x, dtype=tf.float32)

所以用代数术语来说,这个函数是

enter image description here

现在,我们定义了一种计算hessian的方法:

def compute_hessian(fn, vars):
    mat = []
    for v1 in vars:
        temp = []
        for v2 in vars:
            # computing derivative twice, first w.r.t v2 and then w.r.t v1
            temp.append(tf.gradients(tf.gradients(f, v2)[0], v1)[0])
        temp = [cons(0) if t == None else t for t in temp] # tensorflow returns None when there is no gradient, so we replace None with 0
        temp = tf.pack(temp)
        mat.append(temp)
    mat = tf.pack(mat)
    return mat

并称之为:

# arg1: our defined function, arg2: list of tf variables associated with the function
hessian = compute_hessian(f, [x, y])

现在我们获取一个tensorflow会话,初始化变量,然后运行hessian

sess = tf.Session()
sess.run(tf.initialize_all_variables())
print sess.run(hessian)

注意:由于我们使用的函数本质上是二次函数(并且我们是两次微分),因此无论变量如何,返回的hessian值都是常量。

输出为:

[[ 2.  2.]
[ 2.  6.]]

相关问题 更多 >