参数 persistent是设置持久Tape内容。正常的情况下,此值为False。当调用tape.gradient之后就会释放Tape中的内容。也就是说,如果要对变量x求两个函数的导数,是报错的。
但是如果设置此值为True,就可以连续的计算导数。比如下面的例子。不过此种形式下,需要显式的删除Tape。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x=tf.linspace(0.0,3.0,150)
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
y=x*x
z=tf.math.log(x)
grads = tape.gradient(y,x)
grads_z=tape.gradient(z,x)
del tape
plt.plot(x,y,color='r')
plt.plot(x,z,color='b')
plt.plot(x,grads,color='g')
plt.plot(x,grads_z,color='y')
plt.show()