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.