Tensorflow2.0 自动微分基础

自动微分(低阶方法)

首先拿线性方程来举例说明基本步骤

  1. 在 with GradientTape 内部 自定义的损失函数
  2. 调用gradient方法对指定变量求导
一阶导数
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)
利用导数==0 求函数极值

对于一元多次函数来讲,极值点为导数等于的点,那可以利用牛顿法求函数的极值。具体原理推导见 梯度下降与 一阶泰勒展开

# 求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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值