好吧,你可以不费吹灰之力就计算出海森矩阵!
假设有两个变量: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.]]
如果觉得《python求高阶导数_TensorFlow:计算Hessian矩阵(和高阶导数)》对你有帮助,请点赞、收藏,并留下你的观点哦!