Alejandro
Alejandro

Reputation: 949

How can I combine two gradient tapes in TensorFlow 2.0

How can I combine the two following gradient tape, into one:

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)

Here's what I prefer but does not work the way I have written it:

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

Upvotes: 3

Views: 1510

Answers (2)

Joseph Konan
Joseph Konan

Reputation: 706

To avoid the need for persistent tape, you could do this:

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)

Upvotes: 3

javidcf
javidcf

Reputation: 59731

You should be able to do this:

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)

Upvotes: 5

Related Questions