好吧,你可以毫不费力地计算粗体矩阵!
假设您有两个变量:
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)
所以在代数术语中,这个函数是
现在我们定义一个计算粗麻布的方法:
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)
注意:由于我们使用的函数本质上是二次的(并且我们进行了两次微分),所以返回的粗体将具有恒定值,而与变量无关.
输出是:
[[ 2. 2.]
[ 2. 6.]]
如果觉得《python求高阶导数_python – TensorFlow:计算Hessian矩阵(和更高阶导数)》对你有帮助,请点赞、收藏,并留下你的观点哦!