Tensorflow 的求梯度函數:
[db, dW, dx] = tf.gradient(C, [b, w, x])
在調試時用處較大。
實例:
import tensorflow as tf import numpy as np w1 = tf.Variable(2.0) w2 = tf.Variable(3.0) a = tf.multiply(w1,w2) g = tf.get_default_graph() with g.gradient_override_map({"Sign":"Identity"}): clip = tf.sign(a) gradients = tf.gradients(clip, xs=[w1, w2]) with tf.Session() as sess: tf.global_variables_initializer().run() print(sess.run(gradients))
>>[3.0,2.0]
此外,更加深度的應用見:
https://zhuanlan.zhihu.com/p/23060519
詳細的解釋了tensorflow中梯度的累計以及異步實現