我想使用GradientTape在急切执行模式下观察梯度。是否可以创建一个 GradientTape
一次,然后记录所有内容,就好像它具有全局上下文一样?
这是我想做的一个例子:
import numpy as np
import tensorflow as tf
x = tf.Variable(np.ones((2,)))
y=2*x
z=2*y
tf.gradients(z, x) # RuntimeError, not supported in eager execution
现在,这个问题可以轻松解决:
with tf.GradientTape() as g:
y = 2*x
z = 2*y
g.gradient(y, x) # this works
但问题是我经常没有紧接着彼此的 y 和 z 的定义。例如,如果代码在 Jupyter Notebook 中执行并且它们位于不同的单元格中怎么办?
我可以定义一个 GradientTape 来监视全局的所有内容吗?
最佳答案
我找到了这个解决方法:
import numpy as np
import tensorflow as tf
# persistent is not necessary for g to work globally
# it only means that gradients can be computed more than once,
# which is important for the interactive jupyter notebook use-case
g = tf.GradientTape(persistent=True)
# this is the workaround
g.__enter__()
# you can execute this anywhere, also splitted into separate cells
x = tf.Variable(np.ones((2,)))
y = 2*x
z = 2*y
g.gradient(z, x)
关于python - 在全局上下文中使用一个 GradientTape,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58612362/