計算圖建構與純量前向求值
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.