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.