import tensorflow as tf w = tf.constant(1.) x = tf.constant(2.) y = x * w
with tf.GradientTape() as tape: tape.watch([w]) y2 = x * w grad1 = tape.gradient(y, [w]) grad1
with tf.GradientTape() as tape: tape.watch([w]) y2 = x * w grad2 = tape.gradient(y2, [w]) grad2
try: grad2 = tape.gradient(y2, [w]) except Exception as e: print(e) with tf.GradientTape(persistent=True) as tape: tape.watch([w]) y2 = x * w
grad2 = tape.gradient(y2, [w]) grad2
with tf.GradientTape() as t1: with tf.GradientTape() as t2: y = x * w + b dy_dw, dy_db = t2.gradient(y, [w, b]) d2y_dw2 = t1.gradient(dy_dw, w)