how to use GradientTape to calculate gradient without using with statement?

30 views Asked by At

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)

enter image description here

I wish the second code block can calculate gradient correctly.

0

There are 0 answers