![](/img/trans.png)
[英]How to compute all second derivatives (only the diagonal of the Hessian matrix) in Tensorflow?
[英]TensorFlow: Compute Hessian matrix (and higher order derivatives)
好吧,您可以毫不費力地計算 Hessian 矩陣!
假設您有兩個變量:
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)
所以在代數方面,這個函數是
現在我們定義一個計算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.]]
提醒一句:Hessian 矩陣(或更一般地說,張量)的計算和存儲成本很高。 您實際上可能會重新考慮是否真的需要完整的 Hessian 或一些 hessian 屬性。 其中許多,包括跡、范數和頂部特征值,無需顯式Hessian矩陣即可獲得,只需使用 Hessian 向量乘積預言機即可。 反過來,hessian-vector 產品可以有效地實現(也在領先的 autodiff 框架中,例如 Tensorflow 和 PyTorch)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.