How do I get the gradient of the loss at a TensorFlow variable ?

How do I get the gradient of the loss at a TensorFlow variable ?

Asked on December 26, 2018 in Tensorflow.
Add Comment


  • 1 Answer(s)

          To compute the symbolic gradient of one tensor with respect to many other tensors include variable use tf.gradients()

    Example:

    data = tf.placeholder(tf.float32)
    var = tf.Variable(...)              # Must be a tf.float32 or tf.float64 variable.
    loss = some_function_of(var, data)  # some_function_of() returns a `Tensor`.
     
    var_grad = tf.gradients(loss, [var])[0]
    

    And to evaluate the gradient in some specific data use this symbolic gradient:

    sess = tf.Session()
     
    var_grad_val = sess.run(var_grad, feed_dict={data: ...})
    
    Answered on December 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.