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:
First, import the TensorFlow library:
import TensorFlow as tf
The
x
variable is the independent variable of the function:x = tf.placeholder(tf.float32)
Let's build the function:
y = 2*x*x
Finally, we call the
tf.gradients()
function withy
andx
as arguments:var_grad = tf.gradients(y, x)
To evaluate the gradient, we must build a session:
with tf.Session() as session:
The gradient will be evaluated on the variable
x=1
:var_grad_val = session.run(var_grad,feed_dict={x:1})
The
var_grad_val
value is the feed result, to be printed:print(var_grad_val...