concept GradientTape in category deep learning

appears as: The GradientTape, GradientTape
Deep Learning with Python, Second Edition

This is an excerpt from Manning's book Deep Learning with Python, Second Edition.

The API through which you can leverage TensorFlow’s powerful automatic differentiation capabilities is the GradientTape. It’s a Python scope that will “record” the tensor operations that run inside it, in the form of a computation graph (sometimes called a “tape”). This graph can then be used to retrieve the gradient of any output with respect to any variable or set of variables (instances of the tf.Variable class). A tf.Variable is a specific kind of tensor mean to hold mutable state — for instance, the weights of a neural network are always tf.Variable instances.

import tensorflow as tf
x = tf.Variable(0.)                                #1
with tf.GradientTape() as tape:                    #2
  y = 2 * x + 3                                    #3
grad_of_y_wrt_x = tape.gradient(y, x)              #4

The GradientTape works with tensor operations:

  • Backpropagation, a way to compute the gradient of mathematical expressions (handled in TensorFlow via the GradientTape object)
  • 3.5.3  A second look at the GradientTape API

    So far, TensorFlow seems to look a lot like NumPy. But here’s something NumPy can’t do: retrieve the gradient of any differentiable expression with respect to any of its inputs. Just open a GradientTape scope, apply some computation to one or several input tensors, and retrieve the gradient of the result with respect to the inputs.

    Listing 3.10. Using the GradientTape
    input_var = tf.Variable(initial_value=3.)
    with tf.GradientTape() as tape:
       result = tf.square(input_var)
    gradient = tape.gradient(result, input_var)