好了,您可以轻松地计算出粗麻布矩阵!
假设您有两个变量:
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.]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句