O'Reilly logo

Getting Started with TensorFlow by Giancarlo Zaccone

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Computing gradients

TensorFlow has functions to solve other more complex tasks. For example, we will use a mathematical operator that calculates the derivative of y with respect to its expression x parameter. For this purpose, we use the tf.gradients() function.

Let us consider the math function y = 2x². We want to compute the gradient di y with respect to x=1. The following is the code to compute this gradient:

  1. First, import the TensorFlow library:
        import TensorFlow as tf
    
  2. The x variable is the independent variable of the function:
        x = tf.placeholder(tf.float32)
    
  3. Let's build the function:
        y =  2*x*x
    
  4. Finally, we call the  tf.gradients() function with y and x as arguments:
        var_grad = tf.gradients(y, x)
    
  5. To evaluate the gradient, we must build a session: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required