I'm new to Tensorflow, so this may be a dummy question. I'm trying to figure out what tf.GradientTape() is doing, and I couldn't quite understand how it's recording the operations. Here's the code I tried:
mean = tf.keras.metrics.Mean()
xs = tf.constant([2.0, 3.0, 4.0])
for x in xs:
with tf.GradientTape() as g:
y = x * x
print(y, mean(y))
Abd here's the output:
tf.Tensor(4.0, shape=(), dtype=float32) tf.Tensor(4.0, shape=(), dtype=float32)
tf.Tensor(9.0, shape=(), dtype=float32) tf.Tensor(6.5, shape=(), dtype=float32)
tf.Tensor(16.0, shape=(), dtype=float32) tf.Tensor(9.666667, shape=(), dtype=float32)
It looks like the mean operation gets accumulated across loops, where in loop 1, it computes 4/1 = 4; in loop 2, it computes (4+9)/2=6.5, and in loop 3, it computes (4+9+16)/3 = 9.666667. But what puzzles me is that the square operation (x * x) isn't accumulated, because when y is printed out at each loop, it's just y, and yet when I take the mean of y, it becomes the mean of y + all previous y's.
I can sort of imagine this to be useful when computing loss, as we can easily take the mean of accumulated loss over samples/batches. But i have trouble visualize how tf.GradientTape is "selectively" recording operations behind the scene.