34 / 90

第 34 天:MLP 結構與前向傳播

從歷史上的感知機走向可微神經元,在 projects/autograd 標量引擎上組裝一個 2-2-1 多層感知機,手工計算每一個前向數值,並收集將在第 35 天手工推導的全部參數梯度。

模型原理與訓練微調 480 分鐘(8 小時專注學習)
01 120 分鐘

從感知機到可微 MLP:層、權重與激活函數

Agent 輔助工程檢查

前置要求

第 33 天自動微分掌握檢查,以及已驗證的 Value `backward()` 語義。

學習目標

區分歷史感知機(階躍激活)與可微神經元 $z = \sum_i w_i x_i + b$、$a = \sigma(z)$;解釋為何必須堆疊帶非線性激活的層才能表達 XOR 等函數;並陳述本日使用的參考 2-2-1 網路的精確結構。

操作指引

先閱讀下面的概念分解,再先預測後計算。

感知機計算 $z = \sum_i w_i x_i + b$,當 $z > 0$ 時輸出 $1$,否則輸出 $0$。其階躍激活使輸入-輸出映射分段恆定:梯度幾乎處處為 $0$,在拐點處無定義,因此基於梯度的訓練無法改進它。可微神經元把階躍換成 $\tanh$ 等光滑激活。

多層感知機 (MLP) 將全連接層堆疊起來:第 $l$ 層的每個神經元都接收第 $l-1$ 層的全部激活。單個線性單元只能畫出一條直線決策邊界,無法表示 XOR;兩層以上加非線性激活則可以。

本日參考網路 N1:輸入 $x=(2.0, -1.0)$;隱藏神經元 $h_1$:權重 $(0.5, -0.25)$,偏置 $0.1$,激活 $\tanh$;隱藏神經元 $h_2$:權重 $(-0.5, 1.0)$,偏置 $-0.2$,激活 $\tanh$;輸出神經元 $o$:權重 $(1.0, -2.0)$,偏置 $0.3$,線性(無激活);損失 $L = (o - y)^2$,目標 $y = 1.0$。

自主實作與記錄

1. 在任何計算之前,先預測 $z_1$ 與 $z_2$ 的符號,並判斷是否有隱藏神經元接近飽和。
2. 數出 N1 的可訓練參數總數,並拆分為權重與偏置。
3. 用一句話說明為何階躍激活的感知機無法用梯度下降訓練。
4. 預測 $o$ 會高於還是低於目標 $y = 1.0$。

獨立掌握標準

學習者能寫出 $z = \sum w_i x_i + b$ 與 $a = \sigma(z)$ 的公式,正確數出 N1 的九個參數,並用自己的話說明基於梯度的學習為何要求可微性。

權威來源資源與權利證明

linking CC BY-NC 3.0 noncommercial

Neural Networks and Deep Learning: How the backpropagation algorithm works

作者 / 機構: Michael Nielsen | 原始出處連結 ↗

對應章節 / 時間戳: Sections: Perceptrons, Sigmoid neurons, The architecture of neural networks

驗證版本與日期: Online book (Verified: 2026-10-30)

入選理由:

Clear four-equation derivation of backpropagation with scalar and matrix notation.

來源前置條件:

Matrix multiplication and the multivariable chain rule from Days 19-24.

安全回退方案(離線彈性):

All four backprop equations and derivations are self-contained within the lesson text.

對比候選資源與選型分析 (2)
Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.

Modular computational graph view; used as secondary source on Days 35-36.

linking MIT

micrograd: A tiny scalar-valued autograd engine

作者 / 機構: Andrej Karpathy | 原始出處連結 ↗

對應章節 / 時間戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

驗證版本與日期: Git commit master (Verified: 2026-10-30)

入選理由:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

來源前置條件:

Python object-oriented programming and operator overloading from Day 31.

安全回退方案(離線彈性):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

對比候選資源與選型分析 (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

02 120 分鐘

手工計算 2-2-1 網路的完整前向傳播

獨立掌握檢查

前置要求

活動 34-01 的網路定義與 tanh 求值。

學習目標

手工計算網路 N1 的每一個中間值——$z_1, a_1, z_2, a_2, o, L$——把結果記錄到前向傳播台帳中,然後用標量自動微分引擎逐項核對。

操作指引

先在紙上或用普通計算器完成前向傳播,再碰引擎。逐節點填寫台帳:節點名、局部輸入、計算值。

然後用引擎核對:

python3 - <<'EOF'
import sys; sys.path.insert(0, '.')
from projects.autograd.engine import Value
x1, x2 = Value(2.0), Value(-1.0)
a1 = (x1*Value(0.5) + x2*Value(-0.25) + Value(0.1)).tanh()
a2 = (x1*Value(-0.5) + x2*Value(1.0) + Value(-0.2)).tanh()
o = a1*Value(1.0) + a2*Value(-2.0) + Value(0.3)
loss = (o - 1.0)**2
print(a1.data, a2.data, o.data, loss.data)
EOF

把列印值與台帳逐行比對。任何不一致都意味著對應行算錯了——找出第一處分歧。

自主實作與記錄

為 N1 產生一張完整的前向台帳:$z_1$、$a_1 = \tanh(z_1)$、$z_2$、$a_2 = \tanh(z_2)$、$o$ 與 $L = (o - 1.0)^2$。手算結果至少保留 4 位小數,並標出每個引擎輸出是確認還是推翻了你的值。

獨立掌握標準

台帳每一項與引擎值誤差均在 $10^{-3}$ 以內;輸出神經元未誤套 tanh;若曾出現分歧,學習者能指出第一處出錯的行。

權威來源資源與權利證明

linking 3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions No video, audio, transcript or frame redistribution permitted

What is backpropagation really doing? (Chapter 3, Deep Learning)

作者 / 機構: Grant Sanderson (3Blue1Brown) | 原始出處連結 ↗

對應章節 / 時間戳: The Intuition for Backpropagation

驗證版本與日期: Online video and article (Verified: 2026-10-30)

入選理由:

Visual and geometric intuition for how nudging weights impacts the final cost function.

來源前置條件:

Basic derivative intuition from Days 16-18.

安全回退方案(離線彈性):

The lesson derives the network gradient equations step by step without requiring video playback.

對比候選資源與選型分析 (2)
StatQuest Neural Networks Part 3 ↗ compared_alternative [Proprietary]

Step-by-step arithmetic without calculus notation; 3Blue1Brown provides the calculus-visual link needed.

Khan Academy Multivariable Chain Rule ↗ compared_alternative [CC BY-NC-SA 3.0]

Pure math focus; 3Blue1Brown contextualizes the chain rule specifically for neural network graphs.

linking MIT

micrograd: A tiny scalar-valued autograd engine

作者 / 機構: Andrej Karpathy | 原始出處連結 ↗

對應章節 / 時間戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

驗證版本與日期: Git commit master (Verified: 2026-10-30)

入選理由:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

來源前置條件:

Python object-oriented programming and operator overloading from Day 31.

安全回退方案(離線彈性):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

對比候選資源與選型分析 (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

03 120 分鐘

在標量自動微分引擎上組裝 Neuron、Layer 與 MLP 類別

Agent 輔助工程檢查

前置要求

活動 34-02 已核對的前向台帳。

學習目標

仿照 micrograd `nn.py` 的模式,在 projects/autograd 的 `Value` 之上實作 Module/Neuron/Layer/MLP 類別:神經元持有權重與偏置,層持有若干神經元,MLP 持有若干層,且 `parameters()` 能返回每一個可訓練 `Value`。

操作指引

在草稿目錄(不要放進 lessons/ 或 projects/autograd/)寫一個模組,例如 mlp_scratch.py,骨架如下:

from projects.autograd.engine import Value

class Module:
def parameters(self):
return []

class Neuron(Module):
def __init__(self, weights, bias):
assert len(weights) > 0
self.w = [Value(w) for w in weights]
self.b = Value(bias)
def __call__(self, x):
assert len(x) == len(self.w), 'input/weight length mismatch'
z = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return z.tanh()
def parameters(self):
return self.w + [self.b]

再擴展出 Layer(對同一輸入並行求值的一組神經元)與 MLP(按順序串聯的一組層)。構造 N1 時給輸出神經元一個跳過 tanh 的旗標,實作線性輸出。對第 34 天樣本求損失,呼叫 loss.backward(),列印全部九個參數梯度。

單神經元參考軌跡可用以下指令對照:

python3 projects/autograd/cli.py forward-backward --preset neuron --json

自主實作與記錄

1. 實作這三個類別,並讓 N1 的 parameters() 恰好收集九個參數。
2. 求出 loss.data,確認等於你手算的 $4.5179$。
3. 呼叫 loss.backward() 後記錄全部九個 .grad 值——第 35 天你將手工重新推導它們。
4. 說明讓所有參數都能經 parameters() 存取的一個好處。

獨立掌握標準

學習者的類別能複現前向數值、產生九個與引擎誤差在 $10^{-3}$ 以內的參數梯度,並在加權和之前有顯式的長度檢查。

權威來源資源與權利證明

linking MIT

micrograd: A tiny scalar-valued autograd engine

作者 / 機構: Andrej Karpathy | 原始出處連結 ↗

對應章節 / 時間戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

驗證版本與日期: Git commit master (Verified: 2026-10-30)

入選理由:

Minimal, readable implementation of scalar autograd and MLP layers directly matched to our project.

來源前置條件:

Python object-oriented programming and operator overloading from Day 31.

安全回退方案(離線彈性):

The local projects/autograd engine is runnable offline and matches micrograd semantics.

對比候選資源與選型分析 (2)
PyTorch autograd C++ engine ↗ compared_alternative [Modified BSD]

Production scale, but too large and complex for tracing by hand in introductory lessons.

Autograd (HIPS) ↗ compared_alternative [MIT]

Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者 / 機構: Stanford University CS336 Staff | 原始出處連結 ↗

對應章節 / 時間戳: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

驗證版本與日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

入選理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

來源前置條件:

Fluent Python, PyTorch, and linear algebra

安全回退方案(離線彈性):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

對比候選資源與選型分析 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

04 120 分鐘

獨立掌握檢查:MLP 結構與前向計算能力

獨立掌握檢查

前置要求

活動 34-01 至 34-03。

學習目標

在無輔助條件下展示對感知機與 MLP 結構差異、參數統計與完整數值前向傳播的掌握,並通過下方客觀測驗驗證。

操作指引

不查閱前面的活動、不使用 AI 工具:寫出通用神經元的前向公式;在權重與偏置不變的情況下,手工計算 N1 對新輸入 $x = (1.0, 1.0)$ 的輸出;然後完成客觀測驗。提交前請把草稿過程記入下方草稿區。

自主實作與記錄

獨立任務:
1. 對 $x = (1.0, 1.0)$:手工計算 $z_1, a_1, z_2, a_2, o$ 與 $L$。
2. 解釋為什麼換成新輸入不需要改動任何參數。
3. 以獨立模式完成 3 題客觀測驗並取得 100%。

客觀知識測驗:MLP 結構與前向傳播

請回答以下題目檢驗掌握情況。提交前請誠實聲明你的輔助條件。

聲明輔助條件

說明:無 AI 輔助屬於誠實聲明條件,非平台監控或強制檢測手段。

1.

為什麼帶階躍激活的經典感知機無法用梯度下降訓練?

2.

網路 N1 在輸入 $x = (2.0, -1.0)$ 時的輸出 $o$ 是多少?

3.

2-2-1 網路 N1 一共有多少個可訓練參數?

作答應證與歷史記錄

    獨立掌握標準

    對新輸入的無輔助前向計算與 $o \approx 0.0538$、$L \approx 0.8954$ 的誤差在 $10^{-3}$ 以內,且獨立測驗獲得 100%。

    權威來源資源與權利證明

    linking CC BY-NC 3.0 noncommercial

    Neural Networks and Deep Learning: How the backpropagation algorithm works

    作者 / 機構: Michael Nielsen | 原始出處連結 ↗

    對應章節 / 時間戳: Sections: Perceptrons, Sigmoid neurons

    驗證版本與日期: Online book (Verified: 2026-10-30)

    入選理由:

    Clear four-equation derivation of backpropagation with scalar and matrix notation.

    來源前置條件:

    Matrix multiplication and the multivariable chain rule from Days 19-24.

    安全回退方案(離線彈性):

    All four backprop equations and derivations are self-contained within the lesson text.

    對比候選資源與選型分析 (2)
    Goodfellow et al. Deep Learning (Chapter 6) ↗ compared_alternative [All Rights Reserved (free to view online)]

    Comprehensive graduate reference, but heavier tensor notation than needed for first MLP derivations.

    Modular computational graph view; used as secondary source on Days 35-36.

    linking MIT

    micrograd: A tiny scalar-valued autograd engine

    作者 / 機構: Andrej Karpathy | 原始出處連結 ↗

    對應章節 / 時間戳: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'

    驗證版本與日期: 2022 (Verified: 2026-10-30)

    入選理由:

    Deepest bottom-up mechanical clarity for backpropagation engine and computational graph visualization.

    來源前置條件:

    High-school calculus (derivatives) and basic Python syntax

    安全回退方案(離線彈性):

    Authored mathematical derivations, interactive Pyodide engine, and local tests provide complete offline study without video streaming.

    對比候選資源與選型分析 (2)
    PyTorch Autograd Internals ↗ compared_alternative [Modified BSD]

    Normative production documentation, but micrograd's pure Python implementation provides far superior initial clarity.

    3Blue1Brown: What is Backpropagation? ↗ compared_alternative [3Blue1Brown copyright (all rights reserved); site FAQ permits only short clips under stated conditions]

    High visual quality, pairs cleanly as optional supplementary visual reference.