Here is my example from Tensorflow 2.0:
import tensorflow as tf
w = tf.Variable([[1.0]])
with tf.GradientTape() as tape_1:
loss_1 = w * w
with tf.GradientTape() as tape_2:
loss_2 = w * w * w
grad_1 = tape_1.gradient(loss_1, w)
grad_2 = tape_2.gradient(loss_2, w)
print(grad_1)
print(grad_2)
it returns:
tf.Tensor([[2.]], shape=(1, 1), dtype=float32)
tf.Tensor([[3.]], shape=(1, 1), dtype=float32)
The above are correct coefficients, but grad_2
should also indicate that we have 3w^2. How can I retrieve w^2
part?