计算图构建与标量前向求值
Agent 辅助工程检查
前置要求
第 30 天数学基础、Python 面向对象基础,以及理解变量作为对象引用的内存模型。
学习目标
理解如何将标量算术表达式映射为由 `Value` 节点组成的有向无环图 (DAG),并跟踪前向求值流程。
操作指引
在自动微分中,计算图将每个数学运算表示为内部节点,操作数表示为输入边。运行图结构查看命令:
python3 projects/autograd/cli.py graph --preset neuron --format ascii
观察 $x_1 w_1 + x_2 w_2 + b$ 如何流入激活函数 $o = \tanh(n)$,并核对各前向计算节点数据。
自主演练与记录
对于表达式 $f(x, y) = (x \cdot y + 2)^2$,在 $x = 1.5, y = -2.0$ 处:
1. 拆解步骤构建中间节点:令 $u = x \cdot y$, $v = u + 2$, $f = v^2$。
2. 计算 $u, v, f$ 的数值。
3. 在下方演练区写出你预测的前向节点数值,先不运行代码。
依次计算中间结果:$u = 1.5 \times (-2.0) = -3.0$;接着 $v = -3.0 + 2 = -1.0$;最终 $f = (-1.0)^2 = 1.0$。
参考解答:
- $u = 1.5 \times (-2.0) = -3.0$
- $v = -3.0 + 2 = -1.0$
- $f = (-1.0)^2 = 1.0$
该计算图包含 2 个叶子节点 ($x, y$)、1 个常数节点 ($2$) 与 3 个运算符节点 ($*, +, **2$)。
学习者能够准确将标量算术拆解为带有父节点依赖 (`_prev`) 与标量数值 (`data`) 的 DAG 计算节点。
权威源资源与权利证明
micrograd: A tiny scalar-valued autograd engine
对应章节 / 时间戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'
验证版本与日期: commit a9a9f94 (Verified: 2026-10-30)
Clear, minimal scalar DAG implementation demonstrating fundamental autograd data structures.
Basic Python and calculus fundamentals
Local engine implementation in projects/autograd/engine.py and offline documentation.
对比候选资源与选型分析 (2)
Production scale, but too large and complex for tracing by hand in introductory lessons.
Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.