一元函数
import tensorflow as tf
x = tf.Variable(3.)
with tf.GradientTape(persistent=True) as tape:
y = tf.square(x)
z = tf.pow(x,3)
dy_dx = tape.gradient(y,x)
dz_dx = tape.gradient(z,x)
print(y)
print(dy_dx)
print(z)
print(dz_dx)
del tape #使用完之后手动释放
多元函数
import tensorflow as tf
x = tf.Variable(3.)
y = tf.Variable(4.)
with tf.GradientTape(persistent=True) as tape:
f = tf.square(x)+2*tf.square(y)+1
dy_dx,df_dy = tape.gradient(f,[x,y])
print(f)
print(dy_dx)
print(df_dy)
del tape #使用完之后手动释放
二阶导数
import tensorflow as tf
x = tf.Variable(3.)
y = tf.Variable(4.)
with tf.GradientTape(persistent=True) as tape2:
with tf.GradientTape(persistent=True) as tape1:
f = tf.square(x)+2*tf.square(y)+1