Home / TensorFlow / Automatic differentiation with GradientTape
Example: Vector and graph
Given \(y = \sin x\), graph \(y\) and \(\dv*{y}{x}\) at \(x \in [-\pi, \pi]\).
import math
import tensorflow as tf
import matplotlib.pyplot as plt
# Differentiate.
x = tf.linspace(-math.pi, math.pi, 100)
with tf.GradientTape() as tape:
tape.watch(x)
y = tf.sin(x)
dy_dx = tape.gradient(y, x)
# Plot.
plt.style.use('dark_background')
plt.rc('legend', facecolor='#111')
fig, ax = plt.subplots()
ax.set_xlabel(r'\(x\)')
ax.set_xticks([-math.pi, 0, +math.pi])
ax.set_xticklabels([r'\(-\pi\)', '0', r'\(\pi\)'])
ax.set_ylabel(r'\(y\)')
ax.set_yticks([-1, 0, +1])
ax.plot(x, y, label=r'\(y = \sin(x)\)')
ax.plot(x, dy_dx, label=r'\(y = \dv*{x} \sin(x) = \cos(x)\)')
ax.grid()
ax.legend()
fig