《动手学深度学习 Pytorch版》 2.4 微积分
2.4.1 导数和微分
导数是啥无需多讲,可以代码实现求 在 处的导数的趋近值
%matplotlib inline
import numpy as np
from matplotlib_inline import backend_inline
from d2l import torch as d2l
def f(x): # 定义f(X)
return 3 * x ** 2 - 4 * x
def numerical_lim(f, x, h): # 求导函数
return (f(x + h) - f(x)) / h
h = 0.1
for i in range(5):
print(f'h={h:.5f}, numerical limit={numerical_lim(f, 1, h):.5f}')
h *= 0.1
h=0.10000, numerical limit=2.30000
h=0.01000, numerical limit=2.03000
h=0.00100, numerical limit=2.00300
h=0.00010, numerical limit=2.00030
h=0.00001, numerical limit=2.00003
使用matplotlib对导数的这种解释进行可视化。
ps:#@save是d2l包的标记,用来把函数、类或者语句保存在d2l包中,以后无需定义即可调用。
def use_svg_display(): #@save
"""使用svg格式在Jupyter中显示绘图"""
backend_inline.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5, 2.5)): #@save
"""设置matplotlib的图表大小"""
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize # 这里可以直接使用d2l.plt是因为导入语句 from matplotlib import pyplot as plt已标记为保存到d2l包中
#@save
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
"""设置matplotlib的轴"""
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
axes.set_xlim(xlim)
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
#@save
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):
"""绘制数据点"""
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
# 如果X有一个轴,输出True
def has_one_axis(X):
return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list)
and not hasattr(X[0], "__len__"))
if has_one_axis(X):
X = [X]
if Y is None:
X, Y = [[]] * len(X), X
elif has_one_axis(Y):
Y = [Y]
if len(X) != len(Y):
X = X * len(Y)
axes.cla()
for x, y, fmt in zip(X, Y, fmts):
if len(x):
axes.plot(x, y, fmt)
else:
axes.plot(y, fmt)
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
2.4.2 偏导数
无需多言
2.4.3 梯度
梯度(gradient)向量也就是一个包含n个偏导数的向量:
2.4.4 链式法则
无需多言
练习
(1)绘制函数 和其在 处切线的图像。
def g(x): # 定义g(X)
return x ** 3 - 1 / x
x = np.arange(0, 3, 0.1)
plot(x, [g(x), 4 * x - 4], 'x', 'g(x)', legend=['g(x)', 'Tangent line (x=1)'])
C:\Users\AncilunKiang\AppData\Local\Temp\ipykernel_8840\2032550329.py:2: RuntimeWarning: divide by zero encountered in true_divide
return x ** 3 - 1 / x
(2)求函数 的梯度值
求两个偏导,写成向量形式即可。
对 求偏导得:
对 求偏导得:
最后得函数 相对于 的梯度是:
(3)函数 的梯度是什么?
第二范数的表达式时:
求偏导是:
最后得函数 相对于 的梯度是:
(4)尝试写出函数 的链式法则,其中 ,,。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了