首先拿线性方程来举例说明基本步骤
import numpy as np
# f(x) = a*x**2 + b*x + c的导数
# 因为是 auto watched ,所以不需要watch, 常量需要watched
x = tf.Variable(0.0,name = "x",dtype = tf.float32)
a = tf.constant(1.0)
b = tf.constant(-2.0)
c = tf.constant(1.0)
## 这个地方是定义有及 对谁 求导【定义】
with tf.GradientTape() as tape:
y = a*tf.pow(x,2) + b*x + c
### 这个地方是 求导数 【求导】
dy_dx = tape.gradient(y,x)
print(dy_dx)
tf.print(dy_dx)
二阶导数与一阶导数方法无异,差异就在于内部求一阶,再去求二阶。
x = tf.Variable(2.,name = "x",dtype = tf.float32)
a = tf.constant(1.0)
b = tf.constant(-2.0)
c = tf.constant(1.0)
with tf.GradientTape() as tape2:
with tf.GradientTape() as tape1:
y = a*tf.pow(x,2) + b*x + c
dy_dx = tape1.gradient(y,x)
## 再对 dy_dx这个函数求导就是 y的二阶导数
dy2_dx2 = tape2.gradient(dy_dx,x)
tf.print(dy_dx)
tf.print(dy2_dx2)
print (dy2_dx2)
对于一元多次函数来讲,极值点为导数等于的点,那可以利用牛顿法求函数的极值。具体原理推导见 梯度下降与 一阶泰勒展开
# 求f(x) = a*x**2 + b*x + c的最小值
# 使用optimizer.apply_gradients
x = tf.Variable(0.0,name = "x",dtype = tf.float32)
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
a = tf.constant(1.0)
b = tf.constant(-2.0)
c = tf.constant(1.0)
for _ in range(1000):
with tf.GradientTape() as tape:
y = a*tf.pow(x,2) + b*x + c
## 每一轮,都会计算出当前x下的 dy_dx,
dy_dx = tape.gradient(y,x)
## 这一步就是求 x 的 下一个x。参数更新
optimizer.apply_gradients(grads_and_vars=[(dy_dx,x)])
tf.print("y =",y,"; x =",x)
参考教材 eat_tensorflow2_in_30_days