TensorFlow之微分求导

目录

前言

在TensorFlow中,微分是个非常重要的概念。它们分别用于自动求导(计算梯度)和高效地处理数据。下面我将分别介绍这两个主题。

微分(Automatic Differentiation)

TensorFlow提供了强大的自动求导功能,这对于训练机器学习模型尤其重要,因为需要通过反向传播算法来更新模型参数。自动求导允许 TensorFlow 自动计算损失函数相对于模型参数的梯度,从而简化了模型训练过程中的优化步骤。

使用 tf.GradientTape

tf.GradientTape是TensorFlow 2.x 中实现自动求导的核心工具。它会记录在其上下文内的所有操作,并可以在需要时计算这些操作相对于输入张量的梯度。

示例

手动微分实现

python 复制代码
from tensorflow import keras
import numpy as np
import pandas
import matplotlib.pyplot as plt


# 3 * x^2 + 2 * x - 1
# 手动微分
def f(x):
    return 3. * x ** 2 + 2. * x - 1.

# 近似求导
def approximate_derivative(f, x, eps=1e-3):
    return (f(x + eps) - f(x - eps)) / (2. * eps)

print(approximate_derivative(f, 1.))

结果如下:

powershell 复制代码
7.999999999999119

两个未知数, 求偏导

python 复制代码
from tensorflow import keras
import numpy as np
import pandas
import matplotlib.pyplot as plt


# 两个未知数, 求偏导
def g(x1, x2):
    return (x1 + 5) * (x2 ** 2)

# 近似求导
def approximate_derivative(f, x, eps=1e-3):
    return (f(x + eps) - f(x - eps)) / (2. * eps)

# 分别求g对x1,和x2的偏导.
def approximate_gradient(g, x1, x2, eps=1e-3):
    dg_x1 = approximate_derivative(lambda x: g(x, x2), x1, eps)
    dg_x2 = approximate_derivative(lambda x: g(x1, x), x2, eps)
    return dg_x1, dg_x2



print(approximate_gradient(g, 2, 3))

结果如下:

powershell 复制代码
(8.999999999993236, 41.999999999994486)

tf.GradientTape常量求导

python 复制代码
from tensorflow import keras
import numpy as np
import pandas
import matplotlib.pyplot as plt
import tensorflow as tf 


x1 = tf.Variable(2.0)
x2 = tf.Variable(3.0)

def g(x1, x2):
    return (x1 + 5) * (x2 ** 2)

with tf.GradientTape() as tape:
    z = g(x1, x2)
    
dz_x1x2 = tape.gradient(z, [x1, x2])
print(dz_x1x2)

结果如下:

powershell 复制代码
[<tf.Tensor: shape=(), dtype=float32, numpy=9.0>, <tf.Tensor: shape=(), dtype=float32, numpy=42.0>]

tf.GradientTape二阶导数

python 复制代码
from tensorflow import keras
import numpy as np
import pandas
import matplotlib.pyplot as plt
import tensorflow as tf 


x1 = tf.Variable(2.0)
x2 = tf.Variable(3.0)

def g(x1, x2):
    return (x1 + 5) * (x2 ** 2)



# 二阶导数
# 嵌套tf.GradientTape
x1 = tf.Variable(2.0)
x2 = tf.Variable(3.0)

with tf.GradientTape(persistent=True) as outer_tape:
    with tf.GradientTape(persistent=True) as inner_tape:
        z = g(x1, x2)
    # 一阶导    
    inner_grads = inner_tape.gradient(z, [x1, x2])
# 对一阶导的结果再求导
outer_grads = [outer_tape.gradient(inner_grad, [x1, x2]) for inner_grad in inner_grads]
print(outer_grads)
del inner_tape
del outer_tape

结果如下:

powershell 复制代码
[[None, <tf.Tensor: shape=(), dtype=float32, numpy=6.0>], [<tf.Tensor: shape=(), dtype=float32, numpy=6.0>, <tf.Tensor: shape=(), dtype=float32, numpy=14.0>]]

tf.GradientTape实现梯度下降

python 复制代码
from tensorflow import keras
import numpy as np
import pandas
import matplotlib.pyplot as plt
import tensorflow as tf 


def f(x):
    return 3. * x ** 2 + 2. * x - 1.

# 使用tf.GradientTape实现梯度下降
learing_rate = 0.1
x = tf.Variable(0.0)

for _ in range(100):
    with tf.GradientTape() as tape:
        z = f(x)
    dz_dx = tape.gradient(z, x)
    x.assign_sub(learing_rate * dz_dx) # x -= learning_rate * dz_dx
print(x)

结果如下:

powershell 复制代码
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=-0.3333333>

结合optimizer实现梯度下降

python 复制代码
from tensorflow import keras
import numpy as np
import pandas
import matplotlib.pyplot as plt
import tensorflow as tf 


def f(x):
    return 3. * x ** 2 + 2. * x - 1.

from tensorflow import keras

# 结合optimizer去实现梯度下降
learing_rate = 0.1
x = tf.Variable(0.0)
optimizer = keras.optimizers.SGD(lr=learing_rate)

for _ in range(100):
    with tf.GradientTape() as tape:
        z = f(x)
    dz_dx = tape.gradient(z, x)
#     x.assign_sub(learing_rate * dz_dx) # x -= learning_rate * dz_dx
    optimizer.apply_gradients([(dz_dx, x)])
print(x)

结果如下

powershell 复制代码
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=-0.3333333>
相关推荐
非门由也几秒前
《sklearn机器学习——管道和复合估算器》可视化复合估计器
人工智能·机器学习·sklearn
中等生19 分钟前
Pandas 与 NumPy:数据分析中的黄金搭档
后端·python
用户83562907805131 分钟前
Python查找替换PDF文字:告别手动,拥抱自动化
后端·python
星哥说事39 分钟前
Python自学12 — 函数和模块
开发语言·python
GIS工具-gistools20211 小时前
ArcGIS Excalibur 的新功能
人工智能·arcgis
THMAIL2 小时前
深度学习从入门到精通 - 迁移学习实战:用预训练模型解决小样本难题
人工智能·python·深度学习·算法·机器学习·迁移学习
音视频牛哥2 小时前
AI+ 行动意见解读:音视频直播SDK如何加速行业智能化
人工智能·音视频·人工智能+·ai+ 行动意见·rtsp/rtmp 播放器·低空经济视频链路·工业巡检视频传输
roman_日积跬步-终至千里2 小时前
【软件架构设计(19)】软件架构评估二:软件架构分析方法分类、质量属性场景、软件评估方法发展历程
人工智能·分类·数据挖掘
和小胖11222 小时前
第一讲 Vscode+Python+anaconda 安装
python
和小胖11222 小时前
第二讲 Vscode+Python+anaconda 高阶环境配置
ide·vscode·python