My question is what role with statement is playing of? See the code below,the first code block is working correctly and give the correct result.But the second code block give a RuntimeError.
# Importing the library
import tensorflow as tf
x = tf.Variable(4.0)
# Using GradientTape
with tf.GradientTape() as g:
y = x * x * x
# Computing gradient
res = g.gradient(y, x)
# Printing result
print("res: ",res)
# Importing the library
import tensorflow as tf
x = tf.Variable(4.0)
# Using GradientTape
g = tf.GradientTape()
y = x * x * x
# Computing gradient
res = g.gradient(y, x)
# Printing result
print("res: ",res)
I wish the second code block can calculate gradient correctly.