如何在 TensorFlow 2.0 中组合两个渐变带

How can I combine two gradient tapes in TensorFlow 2.0

如何将以下两个渐变带合并为一个:

x = tf.Variable(x, dtype=tf.float32)
with tf.GradientTape() as t:
    m, v = DGP.predict(x)
    dm_dx = t.gradient(m, x)
with tf.GradientTape() as t:
    m, v = DGP.predict(x)
    dv_dx = t.gradient(v, x)

这是我喜欢的,但与我写的不一样:

with tf.GradientTape() as t:
    m, v = DGP.predict(x)
    dm_dx, dv_dx = t.gradient([m,v], x)

你应该可以做到这一点:

x = tf.Variable(x, dtype=tf.float32)
with tf.GradientTape(persistent=True) as t:
    m, v = DGP.predict(x)
    dm_dx = t.gradient(m, x)
    dv_dx = t.gradient(v, x)

为避免需要永久性磁带,您可以这样做:

x = tf.Variable(x, dtype=tf.float32)
with tf.GradientTape() as t1, tf.GradientTape() as t2:
    m, v = DGP.predict(x)
    dm_dx = t1.gradient(m, x)
    dv_dx = t2.gradient(v, x)