38 / 90

第 38 天:N-gram 语言模型 — 计数、条件概率与平滑

在确定性训练划分上拟合基于计数的二元(bigram)基线:构建计数表、归一化为条件概率、对未见事件进行平滑,并在留出文本上用似然度与困惑度进行评估 — 每个数值均可手算验证。所有工作都计入 480 分钟台账。

模型与训练 480 分钟有效学习(8 小时专注学习)
01 120 分钟

统计二元词元对:从词元流到计数表

Agent 辅助工程检查

前置要求

完成第 37 天。如受阻,使用第 35 天的回退链接复习概率与 Python。

学习目标

将词元序列转换为二元计数表 C(w_{i-1}, w_i),区分上下文总频次与配对频次,并将每个计数值与手动追踪对照验证(支持 Unicode 字符与空输入边界处理)。

操作指引

二元语法(bigram)指相邻的两个连续词元。必做工作:在词元流 'the cat sat the cat ran the dog sat'(模拟由三行训练数据合并成的 9 词元流,遵循 text_tools 的规范)上滑动长度为 2 的窗口,使用 Counter(zip(words, words[1:])) 统计所有相邻配对。选做工作:在验证集 val 划分上重复此过程并比较数据稀疏度。注意:当输入为空文本 '' 时配对计数为空集,Unicode 字符串如 'é猫é' 亦能完全按相同逻辑滑动计数。

自主演练与记录

在运行任何代码之前,手工写出 8 个相邻词元对以及完整计数表。然后用同样方法计算 'banana' 的字符级 bigram 并记录两张表。

独立掌握标准

你的手写计数表与 Counter(zip(words, words[1:])) 的输出完全一致,并能清晰阐述为什么上下文行总和(而非全语料 unigram 词频)是下一步转移概率归一化的正确分母。

权威源资源与权利证明

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 范围: makemore.py part 1 bigrams: counting consecutive character pairs into a frequency table

验证版本与日期: Verified 2026-10-30

入选理由:

Standard minimal implementation of a count-based bigram language model on the same names.txt corpus family.

来源前置条件:

Basic Python and Day 37 token ids

安全回退方案(离线弹性):

The lesson builds the full count table locally in pure Python with verified counts.

对比候选资源与选型分析 (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

作者 / 机构: Daniel Jurafsky, James H. Martin | 原始出处链接 ↗

对应章节 / 范围: Sections 3.1-3.2: n-gram counts, Markov assumption, and maximum-likelihood estimation

验证版本与日期: Draft of 2026-08-19 (Verified: 2026-10-30)

入选理由:

Standard reference text defining n-gram models, count normalization, and the chain-rule decomposition used in this lesson.

来源前置条件:

Basic probability

安全回退方案(离线弹性):

All definitions and worked count tables are included in the lesson itself.

对比候选资源与选型分析 (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

02 120 分钟

最大似然条件概率估计

独立掌握检查(无 AI 辅助)

前置要求

完成上一活动;如受阻,使用列出的回退链接。

学习目标

将计数表行归一化为最大似然转移概率 P(w_i|w_{i-1}) = C(w_{i-1}, w_i) / C(w_{i-1}),验证每个上下文行的概率和为 1,并通过条件概率连乘为简短语句打分。

操作指引

必做工作:对每个上下文词元,将其所有引出的配对计数除以该上下文的总频次。手工计算 P(·|the)、P(·|cat) 和 P(·|dog) 各行,并验证每行之和严格为 1。选做工作:在 'banana' 字符表上进行相同的概率归一化计算。

自主演练与记录

计算 P(cat|the)、P(dog|the)、P(sat|cat)、P(ran|cat)、P(sat|dog)。然后计算在 'the' 之后接续 'cat ran' 的条件概率连乘得分,并预测是否有任何上下文行的和不为 1。

独立掌握标准

无辅助情况下写出全部 5 个条件概率的精确分数形式,验证各上下文行概率和为 1,并正确计算双因子似然度乘积。

权威源资源与权利证明

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

作者 / 机构: Daniel Jurafsky, James H. Martin | 原始出处链接 ↗

对应章节 / 范围: Section 3.2: relative-frequency normalization P(w_n|w_{n-1}) = C(w_{n-1} w_n) / C(w_{n-1})

验证版本与日期: Draft of 2026-08-19 (Verified: 2026-10-30)

入选理由:

Normative definition of maximum-likelihood n-gram estimation used for the hand-computed probabilities in this activity.

来源前置条件:

Basic probability

安全回退方案(离线弹性):

The lesson includes the complete worked normalization with verified fractions and decimals.

对比候选资源与选型分析 (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 范围: makemore.py part 1: row-normalizing the count matrix into P[i] = N[i] / N[i].sum()

验证版本与日期: Verified 2026-10-30

入选理由:

Shows the same normalization implemented over a real character-level count matrix on names.txt.

来源前置条件:

Basic Python

安全回退方案(离线弹性):

The local worked example normalizes a fully printed 3-context table by hand.

对比候选资源与选型分析 (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.

03 120 分钟

Add-k 平滑、似然度与困惑度

Agent 辅助工程检查

前置要求

完成上一活动;如受阻,使用列出的回退链接。

学习目标

解释为什么零概率会使似然度崩塌为 0,应用加一平滑 P(next|context) = (C+1)/(context_total + V)(词汇表大小为 V),并将平滑后的句子得分转化为每个词元的负对数似然 (NLL) 和困惑度 (Perplexity)。

操作指引

该词元流的词汇表大小为 V=5({the, cat, sat, ran, dog})。必做工作:使用加一平滑重新计算 'the' 和 'cat' 的条件分布,并为留出接续文本 'cat ran'(跟在 'the' 后)打分:似然度 L 为平滑条件概率乘积,单词元 NLL = -ln(L)/N(N=2),困惑度 = exp(单词元 NLL)。选做工作:使用 add-0.5 平滑重复计算并对比数值差异。

自主演练与记录

计算上下文 'the' 和 'cat' 的平滑行、接续句的平滑似然度、单词元 NLL 与困惑度。先预测:平滑后的似然度会高于还是低于未平滑的 1/3,为什么?

独立掌握标准

能准确给出完整的平滑行、3/28 的似然度、≈1.117 nats 的单词元 NLL、≈3.055 的困惑度,并清楚解释为什么模型评估只能在留出的测试集(held-out text)上进行。

权威源资源与权利证明

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

作者 / 机构: Daniel Jurafsky, James H. Martin | 原始出处链接 ↗

对应章节 / 范围: Sections 3.3-3.4: Laplace (add-one) smoothing, evaluation, and perplexity

验证版本与日期: Draft of 2026-08-19 (Verified: 2026-10-30)

入选理由:

Standard treatment of smoothing zero counts and of perplexity as the inverse likelihood per token.

来源前置条件:

Basic probability and logarithms

安全回退方案(离线弹性):

The lesson contains the complete smoothed probability table and perplexity computation.

对比候选资源与选型分析 (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

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.

来源前置条件:

Python systems programming

安全回退方案(离线弹性):

The lesson evaluates the smoothed model on a declared held-out sentence with verified numbers.

对比候选资源与选型分析 (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 分钟

独立掌握检查:实现并验证二元语言模型基线

独立掌握检查(无 AI 辅助)

前置要求

完成前面所有活动;如受阻,使用列出的回退链接。

学习目标

在无辅助情况下实现 bigram 计数、手算条件概率与平滑概率、诊断零似然失败原因,并陈述留出评估防泄露规则(支持空串与 Unicode 边界检查)。

操作指引

本检查期间不要查看答案或使用 AI。必做工作:(1) 在 Python 中实现 'banana' 字符的 bigram 计数;(2) 手算 P(n|a) 和 P(a|n);(3) 为未见字符对计算加一平滑概率;(4) 解释为什么测试集必须封存。选做工作:将计数扩展到三元(trigram)。

自主演练与记录

闭卷作答:(a) 列出 'banana' 的字符 bigram 及其计数值。(b) P(n|a)=? 与 P(a|n)=? (c) 设字符表 V={a,b,n}(V=3),加一平滑后的 P(b|a) 是多少?(d) 若未平滑模型对 'cat dog' 打分为 0,是哪个具体计数值导致的?加一平滑赋予其什么概率?

独立掌握标准

代码实现的计数值与 Counter 完全一致,所有概率给出精确分数,并指出平滑机制与仅在训练集拟合的防泄露规则是解决零概率与虚假高表现的两大基石。

权威源资源与权利证明

linking Free author-published draft chapter Draft text is not reproduced; linking only

Speech and Language Processing, 3rd ed. draft, Chapter 3: N-gram Language Models

作者 / 机构: Daniel Jurafsky, James H. Martin | 原始出处链接 ↗

对应章节 / 范围: Sections 3.1-3.4 combined: counts, MLE, smoothing, and evaluation

验证版本与日期: Draft of 2026-08-19 (Verified: 2026-10-30)

入选理由:

Single primary source covering every formula assessed in the independent check.

来源前置条件:

Basic probability

安全回退方案(离线弹性):

All assessed quantities were derived locally and verified by execution.

对比候选资源与选型分析 (2)
Chen & Goodman: An Empirical Study of Smoothing Techniques for Language Modeling ↗ compared_alternative [CC BY-NC-SA 3.0 (ACL Anthology, pre-2016 material)]

Detailed smoothing survey but far beyond the add-one scope of a first n-gram day; optional further reading.

MIT OCW 6.863J Natural Language Processing ↗ compared_alternative [CC BY-NC-SA 4.0]

Solid academic lecture treatment but less current and less integrated with executable count tables than the SLP3 draft.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 范围: makemore.py part 1: negative log-likelihood averaging nll/N as the loss of the count model

验证版本与日期: Verified 2026-10-30

入选理由:

Connects the hand-derived likelihood to the averaged negative log-likelihood used as a training loss.

来源前置条件:

Basic Python

安全回退方案(离线弹性):

The mastery check reproduces the nll/N computation on a fully specified toy corpus.

对比候选资源与选型分析 (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.