人工智能之数学基础 微积分:第二章 多变量微积分

<p> </p><p/><h1>人工智能之数学基础 微积分</h1><p/><p>第二章 多变量微积分</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-244b50c9edcad0e8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p>


<h1>前言</h1><p>多变量微积分研究<strong>多元函数</strong>()的变化规律,是机器学习、优化、物理建模和经济学的核心数学工具。本文系统讲解<strong>偏导数、方向导数、梯度、Jacobian 矩阵、Hessian 矩阵</strong>等关键概念,并提供完整的 <strong>Python(NumPy / SymPy / Matplotlib)代码实现与可视化</strong>。</p>
<h1>一、多元函数与偏导数</h1><p><strong>1. 多元函数</strong></p><ul><li><p>• 标量场:,如 </p></li><li><p>• 向量场:,如 </p></li></ul><p><strong>2. 偏导数(Partial Derivative)</strong></p><p>固定其他变量,对某一变量求导。</p><p/><blockquote><p>✅ 几何意义:函数在坐标轴方向的切线斜率。</p></blockquote><p><strong>示例:</strong></p><p>设 ,则:</p><p/>
<h1>二、方向导数与梯度(Gradient)</h1><p><strong>1. 方向导数(Directional Derivative)</strong></p><p>函数 在点  沿单位向量  的变化率:</p><p/><p>若 可微,则:</p><p/><p><strong>2. 梯度(Gradient)</strong></p><p>梯度是<strong>所有偏导数组成的向量</strong>,指向函数增长最快的方向:</p><p/><blockquote><p>🔑 关键性质:</p><ul><li><p>• 梯度方向 = 最大上升方向</p></li><li><p>• 负梯度方向 = 最速下降方向(梯度下降法基础)</p></li><li><p>• 梯度与等高线垂直</p></li></ul></blockquote>
<h1>三、Jacobian 矩阵(一阶导数推广)</h1><p><strong>定义</strong></p><p>对于向量值函数 ,其 <strong>Jacobian 矩阵</strong> 是一阶偏导数组成的  矩阵:</p><p/><blockquote><p>✅ 特例:</p><ul><li><p>• 若 (标量函数),Jacobian = 梯度的转置(行向量)</p></li><li><p>• 若 (单变量向量函数),Jacobian = 导数向量</p></li></ul></blockquote><p><strong>应用</strong></p><ul><li><p>• 非线性方程组求解(牛顿法)</p></li><li><p>• 坐标变换(如极坐标 → 直角坐标)</p></li><li><p>• 神经网络反向传播(链式法则的矩阵形式)</p></li></ul>
<h1>四、Hessian 矩阵(二阶导数推广)</h1><p><strong>定义</strong></p><p>对于标量函数 ,其 <strong>Hessian 矩阵</strong> 是二阶偏导数组成的 对称矩阵(若连续):</p><p/><blockquote><p>✅ 性质:</p><ul><li><p>• 对称(Clairaut 定理)</p></li><li><p>• 正定 ⇒ 局部极小值;负定 ⇒ 局部极大值</p></li><li><p>• 用于牛顿优化法、曲率分析</p></li></ul></blockquote>
<h1>五、Python 代码实现</h1><p><strong>1. 导入库</strong></p><pre>import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport sympy as spfrom sympy import symbols, diff, Matrix, sin, cos, exp# 符号变量x, y, z = symbols('x y z')sp.init_printing(use_unicode=True)</pre>
<p><strong>2. 偏导数与梯度(SymPy 符号计算)</strong></p><pre># 定义标量函数 f(x, y) = x^2  y + sin(xy)f = x y + sp.sin(x  y)# 偏导数df_dx = diff(f, x)df_dy = diff(f, y)# 梯度grad_f = Matrix([df_dx, df_dy])print("f(x, y) =", f)print("∂f/∂x =", df_dx)print("∂f/∂y =", df_dy)print("∇f =", grad_f)</pre><p>输出:</p><pre>f(x, y) = x2y + sin(xy)∂f/∂x = 2xy + ycos(xy)∂f/∂y = x2 + xcos(xy)∇f = Matrix([[2xy + ycos(xy)],[     x2 + xcos(xy)]])</pre>
<p><strong>3. Jacobian 矩阵</strong></p><pre># 向量函数 F(x, y) = [x^2 + y, exp(x)  sin(y)]F1 = x2 + yF2 = sp.exp(x)  sp.sin(y)F = Matrix([F1, F2])# Jacobian 矩阵J = F.jacobian([x, y])print("F(x, y) =", F)print("Jacobian J =")sp.pprint(J)</pre><p>输出:</p><pre>F(x, y) = Matrix([[      x2 + y],[exp(x)sin(y)]])Jacobian J =⎡ 2x        1    ⎤⎢                 ⎥⎣exp(x)sin(y)  exp(x)cos(y)⎦</pre>
<p><strong>4. Hessian 矩阵</strong></p><pre># 使用之前的 f(x, y)H = hessian(f, [x, y])  # SymPy 内置函数# 或手动计算H_manual = Matrix([    [diff(f, x, x), diff(f, x, y)],    [diff(f, y, x), diff(f, y, y)]])print("Hessian 矩阵 H =")sp.pprint(H)</pre>
<p><strong>5. 数值梯度(有限差分)</strong></p><p>当函数无解析表达式时,用数值方法近似。</p><pre>def numerical_gradient(f, x, h=1e-6):    """    计算标量函数 f: R^n -> R 在点 x 处的数值梯度    """    grad = np.zeros_like(x)    for i in range(len(x)):        x_plus = x.copy()        x_minus = x.copy()        x_plus[i] += h        x_minus[i] -= h        grad[i] = (f(x_plus) - f(x_minus)) / (2  h)    return grad# 测试函数def f_num(x):    return x[0] x[1] + np.sin(x[0]  x[1])x0 = np.array([1.0, 2.0])grad_num = numerical_gradient(f_num, x0)# 解析梯度(代入 x=1, y=2)grad_true = np.array([    212 + 2np.cos(12),    12 + 1np.cos(12)])print(f"数值梯度: {grad_num}")print(f"解析梯度: {grad_true}")print(f"误差: {np.linalg.norm(grad_num - grad_true):.2e}")</pre>
<p><strong>6. 可视化:梯度场与等高线</strong></p><pre># 函数 f(x, y) = x2&nbsp;+&nbsp;y2def f_plot(x, y):    return x
2 + y2def grad_f_plot(x, y):    return np.array([2x, 2y])# 网格x_vals = np.linspace(-2, 2, 20)y_vals = np.linspace(-2, 2, 20)X, Y = np.meshgrid(x_vals, y_vals)U = 2  X  # ∂f/∂xV = 2  Y  # ∂f/∂yplt.figure(figsize=(8, 6))# 等高线CS = plt.contour(X, Y, f_plot(X, Y), levels=10, cmap='viridis')plt.clabel(CS, inline=1, fontsize=10)# 梯度向量场(归一化以便显示)N = np.sqrt(U2 + V2)U_norm, V_norm = U/N, V/Nplt.quiver(X, Y, U_norm, V_norm, scale=30, color='red', alpha=0.7)plt.title('梯度场与等高线(f = x² + y²)')plt.xlabel('x'); plt.ylabel('y')plt.axis('equal')plt.grid(True)plt.show()</pre><blockquote><p>📊 红色箭头为梯度方向,垂直于等高线,指向函数增长方向。</p></blockquote>
<p><strong>7. Hessian 与极值判别</strong></p><pre># 函数 f(x, y) = x3&nbsp;-&nbsp;3x&nbsp;+&nbsp;y2f_test = x
3 - 3x + y2# 求驻点:∇f = 0grad = [diff(f_test, var) for var in (x, y)]critical_points = sp.solve(grad, (x, y))print("驻点:", critical_points)  # [(-1, 0), (1, 0)]# 计算 HessianH = hessian(f_test, [x, y])for pt in critical_points:    H_at_pt = H.subs({x: pt[0], y: pt[1]})    eigenvals = H_at_pt.eigenvals()    print(f"
在点 {pt}:")    print("Hessian =")    sp.pprint(H_at_pt)    print("特征值:", list(eigenvals.keys()))        # 判别    if all(ev > 0 for ev in eigenvals):        print("→ 局部极小值")    elif all(ev < 0 for ev in eigenvals):        print("→ 局部极大值")    else:        print("→ 鞍点")</pre><p>输出:</p><pre>驻点: [(-1, 0), (1, 0)]在点 (-1, 0):Hessian =⎡-6  0⎤⎢     ⎥⎣0   2⎦特征值: [-6, 2]→ 鞍点在点 (1, 0):Hessian =⎡6  0⎤⎢    ⎥⎣0  2⎦特征值: [6, 2]→ 局部极小值</pre>
<p><strong>8. Jacobian 应用:坐标变换</strong></p><p>极坐标 → 直角坐标:</p><p/><pre>r, theta = symbols('r theta')x_polar = r 
 sp.cos(theta)y_polar = r 
 sp.sin(theta)# Jacobian 矩阵J_polar = Matrix([x_polar, y_polar]).jacobian([r, theta])det_J = J_polar.det().simplify()print("Jacobian 矩阵 (极坐标 → 直角坐标):")sp.pprint(J_polar)print("行列式 |J| =", det_J)  # = r,用于面积元变换 dx dy = r dr dθ</pre>
<h1>六、在机器学习中的应用</h1><p><strong>1. 梯度下降</strong></p><p>参数更新:</p><p><strong>2. 牛顿法(利用 Hessian)</strong></p><p/><p><strong>3. 反向传播</strong></p><p>神经网络中,损失对权重的梯度通过 Jacobian 链式法则传递。</p>
<h1>七、总结</h1><p/><p/><blockquote><p>💡 <strong>关键洞见</strong>:</p><ul><li><p>• 梯度是一阶局部信息,Hessian 是二阶;</p></li><li><p>• Jacobian 是多元链式法则的自然载体;</p></li><li><p>• 所有这些矩阵都是<strong>局部线性/二次近似</strong>的系数。</p></li></ul></blockquote><h1>后续</h1><p>python过渡项目部分代码已经上传至gitee,后续会逐步更新。</p><h1>资料关注</h1><p>公众号:咚咚王
gitee:https://gitee.com/wy18585051844/ai_learning</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-f08df24c01a0050b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p>《Python编程:从入门到实践》
《利用Python进行数据分析》
《算法导论中文第三版》
《概率论与数理统计(第四版) (盛骤) 》
《程序员的数学》
《线性代数应该这样学第3版》
《微积分和数学分析引论》
《(西瓜书)周志华-机器学习》
《TensorFlow机器学习实战指南》
《Sklearn与TensorFlow机器学习实用指南》
《模式识别(第四版)》
《深度学习 deep learning》伊恩·古德费洛著 花书
《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》
《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen)》
《自然语言处理综论 第2版》
《Natural-Language-Processing-with-PyTorch》
《计算机视觉-算法与应用(中文版)》
《Learning OpenCV 4》
《AIGC:智能创作时代》杜雨+&+张孜铭
《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》
《从零构建大语言模型(中文版)》
《实战AI大模型》
《AI 3.0》</p><p> </p><p/><p/>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容