38 / 90

Day 38: N-gram 言語モデル ― カウント、条件付き確率、スムージング

決定論的な学習分割(train split)上でカウントベースのバイグラム(2-gram)ベースラインを適合:カウント表を構築し、条件付き確率に正規化し、未見の事象を平滑化し、ホールドアウトされたテキストを尤度とパープレキシティでスコアリングします(全数値を手計算で検証可能)。すべての作業は 480 分の台帳に計上されます。

モデルと訓練 480 分の有効学習(8 時間集中学習)
01 120 分

バイグラムのカウント:トークンストリームから集計表へ

Agent 支援エンジニアリング確認

前提条件

第 37 日を完了していること。行き詰まった場合は第 35 日の回復リンクで確率と Python を復習してください。

学習目標

トークンストリームをバイグラムカウント表 C(w_{i-1}, w_i) に変換し、文脈合計とペアカウントを分離し、すべての数値を手計算トレースと照合検証する(Unicode 文字や空入力の境界処理を含む)。

手順

バイグラムとは連続する 2 つのトークンのペアです。必須の作業:トークンストリーム 'the cat sat the cat ran the dog sat'(text_tools の動作と同様に、3 行の学習データを結合した 9 トークンのストリーム)上で長さ 2 のウィンドウをスライドさせ、Counter(zip(words, words[1:])) で隣接ペアを集計します。任意の作業:val 分割で繰り返し、データのスパース性を比較します。空文字列 '' が入力された場合は空のカウントとなり、Unicode 文字列 'é猫é' でも同様の規則でカウントされます。

演習と予測記録

コードを実行する前に、8 つの隣接ペアと完全なカウント表を手書きしてください。次に 'banana' の文字レベルバイグラムも同様に計算し、両方の表を記録してください。

独立習得基準

手書きの集計表が 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 | オリジナル出所URL ↗

該当セクション・範囲: 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 | オリジナル出所URL ↗

該当セクション・範囲: 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 であることを検証し、2 因子の尤度積を正確に計算できること。

公式ソースリソースと権利証跡

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 | オリジナル出所URL ↗

該当セクション・範囲: 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 | オリジナル出所URL ↗

該当セクション・範囲: 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 が尤度をゼロ破壊する理由を説明し、語彙サイズ V の加算スムージング P(next|context) = (C+1)/(context_total + V) を適用し、平滑化されたスコアをトークンごとの NLL とパープレキシティに変換する。

手順

ストリームの語彙サイズは V=5({the, cat, sat, ran, dog})です。必須の作業:Add-one スムージングで 'the' と 'cat' の行を再計算し、'the' に続くホールドアウトされた続き 'cat ran' を評価します。尤度 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 | オリジナル出所URL ↗

該当セクション・範囲: 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 | オリジナル出所URL ↗

該当セクション・範囲: 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 支援なし)

前提条件

前のすべての活動を完了していること。行き詰まった場合は一覧の回復リンクを使用してください。

学習目標

支援なしでバイグラムカウントを実装し、条件付き確率と平滑化確率を手計算し、ゼロ尤度エラーを診断し、ホールドアウト評価の規則を明述する(空文字や Unicode 境界を含む)。

手順

この確認中は解答や AI を参照しないでください。必須の作業:(1) 'banana' 文字のバイグラム集計を Python で実装する;(2) P(n|a) と P(a|n) を手計算する;(3) 未見ペアに対する加算平滑化確率を計算する;(4) テスト分割を非接触で保持する理由を説明する。任意の作業:トリグラム(3-gram)に拡張する。

演習と予測記録

何も見ずに解答してください:(a) 'banana' の文字バイグラムとカウント一覧。(b) P(n|a) と P(a|n) はいくつか?(c) V={a,b,n}(V=3)のとき、加算平滑化された P(b|a) は?(d) 未平滑モデルが 'cat dog' にスコア 0 を付けた原因となるカウントは何か、加算平滑化は代わりに何を割り当てるか?

独立習得基準

実装が Counter と完全に同一のカウントを出力し、すべての確率が正確な分数として導出され、ゼロ尤度と過学習(リーク)を防ぐための平滑化および train のみ適合規則が明確に記述されていること。

公式ソースリソースと権利証跡

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 | オリジナル出所URL ↗

該当セクション・範囲: 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 | オリジナル出所URL ↗

該当セクション・範囲: 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.