这是我在 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)
它返回:
tf.Tensor([[2.]], shape=(1, 1), dtype=float32)
tf.Tensor([[3.]], shape=(1, 1), dtype=float32)
以上是正确的系数,但grad_2
也应该表明我们有 3w^2。我怎样才能找回w^2
零件?