偏导数
用坐标切片、二阶偏导和冻结参数实验解释多变量求导。
学完这一章,你能够
- 用坐标切片、二阶偏导和冻结参数实验解释多变量求导。
一次改变一个自变量
多变量函数的偏导数来自固定其他坐标的一元切片。估算面积对模型房价的局部影响时,可先固定地段和楼层。在味道模型里也可只改盐量、保留其它配料。这样的偏导表示模型在指定条件下的局部变化率。
∂ 表示偏导。对 f=x²+xy+y²,固定 y 后用 [f(x+h,y)−f(x,y)]/h 的极限定义 ∂f/∂x=2x+y。固定 x 时得到 ∂f/∂y=x+2y。在 (2,1),x 和 y 两个坐标方向的斜率分别是 5 和 4。两者同时增加会得到另一条切片。
沿相同或不同坐标再求一次
对 x 的一阶偏导再对 x 求导,得到坐标方向上的二阶变化率。本例是 2。混合偏导涉及不同坐标。按分母从右到左解释,∂²f/(∂x∂y) 是先对 y 再对 x。SymPy 的 diff(f, y, x) 按参数顺序执行,两种顺序在 f 的二阶偏导邻域连续时相等,本例均为 1。
符号练习分别计算两个坐标方向的一阶结果、纯二阶以及两种混合顺序。再用非对称表达式 xy² 展示中间过程:先对 x 得 y²,先对 y 得 2xy,两条路径最后都到达 2y。
训练时怎样得到参数梯度
把同一点的偏导按参数顺序组成梯度。反向自动微分可用一次反传得到标量损失对一组参数的梯度。对 L=(wx+b−y)²,令 r=wx+b−y,则 ∂L/∂w=2rx,∂L/∂b=2r。在 (w,b,x,y)=(2,1,3,4),梯度为 (18,6)。
对节点 x+y 求 x 的偏导得到 1,乘法节点 xy 对 x 的偏导为 y。反传沿每条路径相乘。同一变量出现在多条路径时将贡献相加,例如 (x²+x)² 在 x=2 的导数为 60。
在 PyTorch 中可令冻结参数的 requires_grad=False,并把它排除在优化器更新范围外。实验冻结 w 后,w.grad 保持 None,偏置仍获取梯度,输入若需要梯度也会收到反传。冻结能省去部分梯度工作;节省的显存和计算量依赖实际图与模型。
验证偏导、混合顺序与冻结参数
"""Check coordinate slices, mixed derivatives, and frozen parameters."""
import argparse
from fractions import Fraction
import json
import platform
import sympy as sp
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--torch", action="store_true")
args = parser.parse_args()
cases = []
versions = {"sympy": sp.__version__}
def check(name, inputs, expected, actual, operation):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name,input=inputs,expected=expected,actual=actual,operation=operation,passed=True))
x, y = sp.symbols("x y", real=True)
f = x*x + x*y + y*y
check("quadratic_partials", str(f), ["2*x + y","x + 2*y"], [str(sp.diff(f,p)) for p in (x,y)],
"derive the two coordinate partials")
check("pure_and_mixed_orders", str(f), [2,2,1,1],
[int(sp.diff(f,*variables)) for variables in ((x,x),(y,y),(x,y),(y,x))],
"differentiate twice in each ordered pair")
nonsymmetric = x*y*y
check("ordered_steps_are_visible", str(nonsymmetric), ["y**2","2*x*y","2*y","2*y"],
[str(sp.diff(nonsymmetric,*variables)) for variables in ((x,),(y,),(x,y),(y,x))],
"observe the intermediate result for each differentiation order")
h = Fraction(1,100)
def value(a,b):
return a*a+a*b+b*b
first = (value(2+h,1)-value(2,1))/h
second = (value(2,1+h)-value(2,1))/h
both = (value(2+h,1+h)-value(2,1))/h
check("coordinate_slice_quotients", {"point":[2,1],"h":str(h)}, ["501/100","401/100","903/100"],
list(map(str,(first,second,both))), "change x alone, y alone, then both")
w, b, sample, target = sp.symbols("w b sample target", real=True)
loss = (w*sample+b-target)**2
at = {w:2,b:1,sample:3,target:4}
check("linear_square_gradient", {"w":2,"b":1,"sample":3,"target":4}, [18,6],
[int(sp.diff(loss,p).subs(at)) for p in (w,b)], "differentiate loss by weight and bias independently")
check("addition_and_product_local", ["x+y","x*y"], ["1","y"],
[str(sp.diff(node,x)) for node in (x+y,x*y)], "compute the local derivative for a graph node")
shared = (x*x+x)**2
check("shared_node_gradients_add", {"x":2,"graph":"(x*x + x)**2"}, 60, int(sp.diff(shared,x).subs(x,2)),
"add contributions from direct and squared paths")
if args.torch:
import torch
versions["torch"] = torch.__version__
frozen = torch.nn.Parameter(torch.tensor(2.,dtype=torch.float64),requires_grad=False)
bias = torch.nn.Parameter(torch.tensor(1.,dtype=torch.float64))
input_value = torch.tensor(3.,dtype=torch.float64,requires_grad=True)
optimizer = torch.optim.SGD([bias],lr=.125)
loss = (frozen*input_value+bias-4)**2
loss.backward()
check("freeze_keeps_input_gradient", {"w":2,"b":1,"x":3,"target":4}, [None,6,12],
[frozen.grad,float(bias.grad),float(input_value.grad)],
"backpropagate with the weight frozen but the input requiring gradient")
optimizer.step()
check("freeze_optimizer_step", {"learning_rate":.125}, [2,.25],
[float(frozen.detach()),float(bias.detach())], "step only the included trainable bias")
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__ == "__main__":
main()
- f=x²+xy+y² 的一阶偏导为 2x+y 与 x+2y,两种混合偏导均为 1。
所需环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。
当前源码 SHA256:0cbdd8d23f3f8c95255a3ec285f83dc3522f9290f06cece21ef3de17256c191b
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。
ZIP SHA256:8e8c053c9dac0a1488d3cb147f89686f5a3899fbf07e04641bcd81ba7b6e242c
常见错误与边界
- 坐标切片要固定其余变量。
- 交换混合偏导的次序需要适当的光滑条件。
练习与解答
在 (2,1) 只增大 y,哪个表达式给出初始斜率?
展开参考解答
使用 ∂f/∂y=x+2y,此处取值为 4。