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>
相关推荐
百锦再13 分钟前
大数据技术的主要方向及其应用详解
大数据·linux·网络·python·django·pygame
盛夏绽放18 分钟前
Python字符串常用方法详解
开发语言·python·c#
白熊18840 分钟前
【计算机视觉】OpenCV实战项目:基于OpenCV的车牌识别系统深度解析
人工智能·opencv·计算机视觉
noravinsc1 小时前
django中用 InforSuite RDS 替代memcache
后端·python·django
IT古董1 小时前
【漫话机器学习系列】261.工具变量(Instrumental Variables)
人工智能·机器学习
小王格子1 小时前
AI 编程革命:腾讯云 CodeBuddy 如何重塑开发效率?
人工智能·云计算·腾讯云·codebuddy·craft
MonkeyKing_sunyuhua2 小时前
VSCode + Cline AI辅助编程完全指南
ide·人工智能·vscode
Leinwin2 小时前
Microsoft Azure 服务4月更新告示
人工智能·azure
胡耀超2 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全