"""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()
本例需在 Windows、Python 3.12.14。sympy 1.14.0;torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。sympy 1.14.0;torch 2.10.0+cpu。
入口文件:projects/ai-math-chain-rule-example-lab/local-derivative-products.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
local-derivative-products.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。sympy 1.14.0;torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a40.zip