导数入门
从平均变化率到切线,再用有限差分和训练更新解释斜率。
学完这一章,你能够
- 从平均变化率到切线,再用有限差分和训练更新解释斜率。
从割线到切线
在区间内部取 h≠0,割线斜率为 [f(x+h)−f(x)]/h。若 h 从两侧趋零时差商收敛到同一个有限值,这个值就是 f′(x),也给出切线的斜率。只定义在端点一侧时,按相应的单侧导数讨论。
对 f(x)=x²,取 x=2,差商化简为 4+h。h=0.25 时斜率是 4.25,h=−0.25 时是 3.75。两种方向都向 4 靠拢。

斜率符号和驻点
导数为正时切线向右上方,为负时切线向右下方。要由斜率判断整个区间的单调性,需要考察区间内各点。只知道某一点的导数,可用来选择该点邻近的下降方向。
导数为零意味着水平切线。x² 在零有极小值,−x² 在零有极大值,x³ 在零没有极值。可微的无约束内点局部最优应满足梯度为零。梯度范数很小可以用作停止条件,它也可能出现在鞍点、局部极大点或平坦区。
假设汽车在 0 到 2 小时行驶了 120 公里,全程平均速度是 60 公里每小时。若位移模型为 s(t)=30t² 公里,并且汽车一直向前,则两小时末的瞬时速度是 s′(2)=120 公里每小时。发生反向时,瞬时速率是有符号速度的绝对值。
有限差分和模型训练
居中差分取 [f(x+h)−f(x−h)]/(2h),本例要求 h>0。对二次函数,它在精确算术中恰好等于导数,各点 −2、−1、0、1、2 的结果分别为 −4、−2、0、2、4。对一般光滑函数,这是近似。步长过小会受浮点舍入影响。对 |x|,两侧差商分别为 −1 和 1,居中差分虽返回 0,零点仍不可导。
梯度下降按 x新=x旧−ηf′(x旧) 更新。η>0 时,正导数让参数往左走,负导数让它往右走。对 x² 用 η=0.25,从 −2 更新到 −1,从 2 更新到 1,两种情况下损失都从 4 降到 1。步长过大时需要检查更新后的损失。
ReLU 在负半轴导数为 0,在正半轴为 1。零点不可导,PyTorch 在零点反向传播时选择 0。Sigmoid 的导数是 σ(x)(1−σ(x)),在 x=0 取最大值 0.25,远离零时更小。多个这样的因子相乘可使信号衰减,实际深层梯度还取决于权重、输入与网络结构。
用二次函数验证居中差分
"""Inspect secants, centered differences, and stationary points."""
import argparse
from fractions import Fraction as F
import json
import math
import platform
def centered(function, point, step):
if step <= 0:
raise ValueError("step must be positive")
return (function(point+step)-function(point-step))/(2*step)
def main():
options = argparse.ArgumentParser()
options.add_argument("--torch", action="store_true")
args = options.parse_args()
cases = []
versions = {}
def check(name, inputs, operation, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, input=inputs, operation=operation, expected=expected, actual=actual, passed=True))
square = lambda x: x*x
points = list(range(-2,3))
h = F(1,100_000)
slopes = [centered(square,F(x),h) for x in points]
check("quadratic_centered_five_points", [points,str(h)], "use exact centered differences", [-4,-2,0,2,4], [int(x) for x in slopes])
check("tangent_signs", points, "classify five exact slopes", ["fall","fall","flat","rise","rise"],
["fall" if x < 0 else "rise" if x > 0 else "flat" for x in slopes])
check("quadratic_one_sided_secants", [-0.5,-0.1,0.1,0.5], "subtract f(2), divide by signed h",
["7/2","39/10","41/10","9/2"],
[str((square(2+h)-square(2))/h) for h in (F(-1,2),F(-1,10),F(1,10),F(1,2))])
check("centered_can_hide_corner", ["abs",0,"1/100000"], "compare left, right, and centered quotient",
[-1,1,0],[int((abs(-h)-abs(0))/(-h)), int((abs(h)-abs(0))/h), int(centered(abs,F(0),h))])
cubic = lambda x: x*x*x
check("smooth_centered_error_decreases", ["1/2","1/4"], "compute centered differences for x³ at zero",
["1/4","1/16"],[str(centered(cubic,F(0),d)) for d in (F(1,2),F(1,4))])
check("float_steps_can_round_away", [2.0,2**-60], "use binary64 centered difference",
0.0, centered(square,2.0,2**-60))
check("stationary_examples", ["x²","−x²","x³"], "compare values at −1, 0, 1",
[[1,0,1],[-1,0,-1],[-1,0,1]], [[f(x) for x in (-1,0,1)] for f in (square,lambda x:-square(x),cubic)])
distance = lambda t: 30*t*t
check("mean_vs_instantaneous_speed", [0,2], "average distance rate and derivative at the end",
[60,120], [int((distance(2)-distance(0))/2),int(centered(distance,F(2),h))])
check("gradient_update_choices", [-2,2,"eta=1/4"], "update x by subtracting eta times 2x",
[-1,1], [int(x-F(1,4)*2*x) for x in (-2,2)])
if args.torch:
import torch
versions["torch"] = torch.__version__
def gradient(operation, value):
x = torch.tensor(value, dtype=torch.float64, requires_grad=True)
operation(x).backward()
return float(x.grad)
check("relu_autograd_rule", [-1,0,1], "CPU backward pass for ReLU",
[0,0,1], [gradient(torch.relu,x) for x in (-1,0,1)])
sigmoid_at_zero = gradient(torch.sigmoid,0)
check("sigmoid_peak_and_saturation", [-8,0,8], "evaluate CPU backward slopes",
[True,True,True], [gradient(torch.sigmoid,-8)<sigmoid_at_zero,
math.isclose(sigmoid_at_zero,.25,abs_tol=1e-15),
gradient(torch.sigmoid,8)<sigmoid_at_zero])
def repeated_sigmoid(x):
for _ in range(4):
x = torch.sigmoid(x) - .5
return x
check("four_sigmoid_layers_unit_weight", [0,4], "differentiate four centered sigmoid layers",
.25**4, gradient(repeated_sigmoid,0))
print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=cases)))
if __name__ == "__main__":
main()
- 在 −2、−1、0、1、2 得到斜率 −4、−2、0、2、4。
所需环境:Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。
当前源码 SHA256:9ef5c0906d0acd43c696999dacffd5532598f2ba0bf62fca64af08f5de07aa61
复跑实验
解压后调整切点和横向增量,或用 Python 查看两侧差商。
所需环境:Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。
ZIP SHA256:d9427781aa334cb85f537afca86a5fe2377fb51125c0c56fa8496e6bc9d4b8e0
常见错误与边界
- h 太小可能因浮点舍入而失效。
- 驻点还需要进一步判断。
练习与解答
居中差分为零时,一定存在导数吗?
展开参考解答
|x| 在零的居中差分为零,但左右导数不同。