教程 / AI / 智能开发 / AI 数学基础
手动实现链式法则
逐层计算局部导数,并用数值差分、SymPy 和 PyTorch 复查。
本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。
学完这一章,你能够
- 逐层计算局部导数,并用数值差分、SymPy 和 PyTorch 复查。
先求每个中间量,再按依赖传递导数
一个测量值先校正、再转成周期量、最后取平方时,输出对原值的敏感度可以拆成各段的局部变化率。本例设 u=x²+1、v=3sin(u)、y=v²,所以 dy/dx=(2v)·(3cos(u))·(2x)。每项使用对应的当前输入。支路共享同一变量时,先算各条路径的乘积,再把路径贡献相加。
区分两层和三层的目标量
取 x=1.5,u=3.25,v≈−0.324585。两层目标 v 对 x 的导数约 −8.947167。三层目标 y 对 x 的导数还要乘 2v≈−0.649171,结果变为正的约 5.808240。旧例将外层导数误用了 2u,符号与大小都不符合这组输入。
SymPy 从代数表达式求出符号导数。PyTorch 则按实际前向操作构建计算图,再计算反向梯度。中心差分直接比较相邻输入的输出,可以对这两种结果作数值核对。示例检查了两层、三层、分支求和和重复反向时的梯度累积。
链式法则的三种用途
| 场景 | 操作与实测范围 |
|---|---|
| 反向传播 | 沿依赖路径累乘,当同一变量流向多个支路时合并各项贡献。 |
| 自动求导 | 对标量结果反传,读取叶子张量梯度并与手算对照。 |
| 数值检查 | 原文的两法是手算和符号微分。本站补做中心差分,展示第三种独立检查。 |
比较两层和三层复合函数的导数
python · 阅读源码
"""Check local derivatives against symbolic, numerical and automatic differentiation."""
import argparse
import json
from math import cos, sin, prod, isclose
import platform
import sympy
CASES = []
def record(name, operation, inputs, expected, actual):
assert actual == expected, (name, expected, actual)
CASES.append(dict(name=name, operation=operation, inputs=inputs,
expected=expected, actual=actual, passed=True))
def inner(x):
return x * x + 1
def middle(x):
return 3 * sin(inner(x))
def outer(x):
return middle(x) ** 2
def locals_at(x):
return 2 * x, 3 * cos(inner(x)), 2 * middle(x)
def main():
cli = argparse.ArgumentParser()
cli.add_argument("--torch", action="store_true")
args = cli.parse_args()
versions = {"sympy": sympy.__version__}
x0 = 1.5
local = locals_at(x0)
v_grad, y_grad = prod(local[:2]), prod(local)
record("scalar_chain_local_products", "calculate intermediate values and multiply two and three factors",
{"x": x0}, [[3.25, -.324585], [-8.947167, 5.80824]],
[[inner(x0), round(middle(x0), 6)], [round(v_grad, 6), round(y_grad, 6)]])
x = sympy.symbols("x")
v_expr = 3 * sympy.sin(x**2 + 1)
y_expr = v_expr**2
symbolic = [float(sympy.diff(expr, x).subs(x, sympy.Rational(3, 2))) for expr in (v_expr, y_expr)]
record("symbolic_derivatives_at_example", "symbolically differentiate v and y as functions of x",
{"x": "3/2"}, [True, True],
[isclose(observed, expected) for observed, expected in zip(symbolic, (v_grad, y_grad))])
h = 1e-5
numeric = [(func(x0 + h) - func(x0 - h)) / (2 * h) for func in (middle, outer)]
record("numerical_gradient_recheck", "compare symmetric difference quotients",
{"x": x0, "h": h}, [True, True],
[isclose(observed, expected, abs_tol=1e-7) for observed, expected in zip(numeric, (v_grad, y_grad))])
record("sum_branch_contributions", "differentiate a loss containing y plus twice v",
{"loss": "y + 2v"}, True,
isclose(float(sympy.diff(y_expr + 2 * v_expr, x).subs(x, x0)), y_grad + 2 * v_grad))
record("zero_path_factor", "place x at zero where the first local slope vanishes",
{"x": 0}, [0., True],
[prod(locals_at(0)), float(sympy.diff(y_expr, x).subs(x, 0)) == 0.])
mistaken = 2 * inner(x0) * v_grad
record("different_outer_input", "compare applying the square derivative to u versus to v",
{"u": inner(x0), "v": middle(x0)}, [True, True],
[mistaken < 0, y_grad > 0])
if args.torch:
import torch
versions["torch"] = torch.__version__
point = torch.tensor(x0, dtype=torch.float64, requires_grad=True)
def graph():
return (3 * torch.sin(point.square() + 1)).square()
graph().backward()
record("autograd_three_layer", "backpropagate through all three scalar operations",
{"dtype": "float64", "x": x0}, True, isclose(point.grad.item(), y_grad))
graph().backward()
twice = point.grad.item()
point.grad = None
graph().backward()
record("autograd_accumulation", "build two graphs for one leaf, then clear its gradient",
{"backward_calls": 3}, [True, True],
[isclose(twice, 2 * y_grad), isclose(point.grad.item(), y_grad)])
print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=CASES)))
if __name__ == "__main__":
main()
预期结果 · 待实际运行核验
- 两层导数约为 −8.947167,三层约为 5.808240。对照还包含路径求和与梯度累积。
比较两层和三层复合函数的导数
所需环境:Windows、Python 3.12.14。sympy 1.14.0;torch 2.10.0+cpu。
当前源码 SHA256:8b8dc77eb8adfc236c487eefa34c0c2cdf895cfe979d133236605bdb64dcbec9
复跑实验
解压后按 README 运行自编程序。
下载手动实现链式法则实验
所需环境:Windows、Python 3.12.14。sympy 1.14.0;torch 2.10.0+cpu。
ZIP SHA256:63dcc515ae86a5f13bd2a6333e4103a4d3e0a592eeda75c244c5a1a4bfc0ee93
常见错误与边界
- 外层导数必须代入其实际输入,v² 的导数为 2v。
- 使用深度学习框架时留意叶子梯度何时累积、何时清空。
练习与解答
输入改成 x=0 时,三层导数为何为 0?
展开参考解答
g′(0)=0,整条单路径的导数乘积为 0。