These are my notes from COMP90042 (NLP) at the University of Melbourne. This article covers text preprocessing, BPE, N-grams and smoothing, text classification, POS tagging, HMMs and Viterbi.
Term | Definition |
|---|---|
Word | A string of characters with meaning and/or a grammatical function (a sequence of characters with a meaning and/or function) |
Sentence | A unit of words arranged according to grammatical rules to express a complete thought, ending at a punctuation or structural boundary |
Document | A continuous unit of text, such as a news article or an email, consisting of several sentences |
Corpus | A collection of texts gathered at scale for training or evaluation (singular: corpus; plural: corpora) |
Word token | A word instance at each occurrence in a text; "to be or not to be" has 6 tokens |
Word type | A distinct word after deduplication; "to be or not to be" has 4 types |
Lexicon | The set of all word types in a language or domain, together with their lexical entries |
Remember: number of tokens ≥ number of types; corpus size is often described by
\vert V\vert(vocabulary size) and the total number of tokens.
Language is compositional. Humans understand documents by breaking them into components; for computers to understand language, they need to perform a similar decomposition.
Preprocessing gradually converts raw strings into representations suited to the task. Here is a schematic pipeline for traditional text processing:
"<p> Hi there. I'm TARS. </p>"
→ Remove formatting "Hi there. I'm TARS."
→ Segment sentences ["Hi there.", "I'm TARS."]
→ Tokenise [["Hi","there","."], ["I","'m","TARS","."]]
→ Normalise [["hi","there","."], ["i","be","tars","."]]
→ Remove stopwords [["hi","tars","."]] (example)Choose these steps according to the task; not every model needs all of them. Language models generally need to retain punctuation, word forms and function words. Modern pretrained models should also use the same tokenizer used during training.
Figure 1-1 The five-step text preprocessing pipeline, showing the same sentence after each step.
Step | English term | Goal |
|---|---|---|
1 | Remove unwanted formatting | Remove HTML/XML tags, Markdown markup, extra whitespace and escape characters |
2 | Sentence segmentation | Split a document into sentences |
3 | Word tokenisation | Split sentences into tokens, including subword approaches such as BPE |
4 | Word normalisation | Standardise case, spelling and word forms (lemmatisation / stemming) |
5 | Stopword removal | Remove frequent function words that carry little information |
Four approaches, from simple to more complex:
Chinese MaxMatch (maximum matching)
Idea: given a dictionary, greedily select the longest matching string in the dictionary as a word, working from the left or the right.
Example:
Dictionary: {去买新, 西兰花, 西兰花新}
Sentence: 去买新西兰花
Forward maximum matching (FMM, left to right, longest match first):
Position 0: try "去买新" (length 3, in dictionary) → segment as 「去买新」
Position 3: try "西兰花" (length 3, in dictionary) → segment as 「西兰花」
Result: 去买新 / 西兰花Key points and limitations:
Goals:
Methods:
Removing morphology: two types of morphological change
Type | Inflectional morphology | Derivational morphology |
|---|---|---|
Meaning | Different grammatical forms of the same word | New words formed from existing words |
Examples | Plural nouns +s; third-person singular verbs +s, tense/aspect forms +ed/+ing; comparative adjectives +er, superlatives +est | Suffixes change word class: person → personally; prefixes change meaning: write → rewrite |
Changes word class or meaning? | No | Yes |
Lemmatisation versus stemming
Aspect | Lemmatisation | Stemming |
|---|---|---|
Operation | Remove inflection to recover the lemma (dictionary form) | Remove suffixes, retaining a stem |
Approach | Lexicon-based (dictionary + part of speech) | Rule-based (usually a set of affix-stripping rules) |
Output | Meaningful, valid words | Possibly a stem that is not a valid word (studies → studi) |
Speed | Slower (dictionary and POS lookup required) | Faster |
Suitable tasks | Tasks needing valid word forms or sensitive to meaning, such as generation and tasks requiring readable output | Large-scale statistics, retrieval and classification, where consistent word forms are sufficient |
Porter Stemmer
m).k words (inspect manually to avoid removing negators such as not, no).Training (learning merge rules)
k (or vocabulary size).Encoding (tokenising new text)
Apply the rules in the learned merge order; pieces not covered by any rule remain as individual characters. Encoding is therefore deterministic and does not require recounting frequencies.
Corpus (word endings marked with _):
Corpus | Frequency |
|---|---|
o l d _ | 7 |
o l d e r _ | 3 |
f i n e s t _ | 9 |
l o w e s t _ | 4 |
Initial adjacent-pair frequencies
Pair | Count | Explanation |
|---|---|---|
(e, s) | 13 | finest_ 9 + lowest_ 4 |
(s, t) | 13 | finest_ 9 + lowest_ 4 |
(t, _) | 13 | finest_ 9 + lowest_ 4 |
(o, l) | 10 | old_ 7 + older_ 3 |
(l, d) | 10 | old_ 7 + older_ 3 |
(f, i) | 9 | finest_ 9 |
(i, n) | 9 | finest_ 9 |
(n, e) | 9 | finest_ 9 |
(d, _) | 7 | old_ 7 |
(l, o) | 4 | lowest_ 4 |
(o, w) | 4 | lowest_ 4 |
(w, e) | 4 | lowest_ 4 |
(d, e) | 3 | older_ 3 |
(e, r) | 3 | older_ 3 |
(r, _) | 3 | older_ 3 |
Merge process (ties are resolved according to the implementation, commonly by first occurrence or lexicographic order)
Round | Merge | Frequency | Resulting corpus |
|---|---|---|---|
1 | e + s → es | 13 | o l d _(7) o l d e r _(3) f i n es t _(9) l o w es t _(4) |
2 | es + t → est | 13 | f i n est _(9) l o w est _(4) |
3 | est + _ → est_ | 13 | f i n est_(9) l o w est_(4) |
4 | o + l → ol | 10 | ol d _(7) ol d e r _(3) |
5 | ol + d → old | 10 | old _(7) old e r _(3) |
6 | f + i → fi | 9 | fi n est_(9) |
7 | fi + n → fin | 9 | fin est_(9) |
8 | fin + est_ → finest_ | 9 | finest_(9) |
9 | old + _ → old_ | 7 | old_(7) |
Each row shows only the words affected by that merge; all other words remain unchanged.
Final vocabulary (partial): o, l, d, e, r, f, i, n, s, t, w, _, es, est, est_, ol, old, fi, fin, finest_, old_, …

Figure 2-1 Merge operations learned by BPE from the corpus (r · → r·, l o → lo, lo w → low, e r· → er·). This uses the original example from the paper. Source: Sennrich et al., Neural Machine Translation of Rare Words with Subword Units, ACL 2016, Figure 1.
A language model (LM) assigns a word sequence a probability P(w_1, w_2, \dots, w_m).
P(w_t \mid w_{<t}) step by step, generating one word at a time until <eos>.N-gram: a sequence of n consecutive tokens.
| Name | Example (the dog barks) |
|---|---|---|
1 | unigram | the / dog / barks |
2 | bigram | the dog / dog barks |
3 | trigram | the dog barks |
An N-gram language model assumes that the word at position t depends only on the preceding n-1 words.
(a) From joint to conditional probabilities (chain rule)
Take I like apple as an example:
P(\text{I like apple}) = P(\text{I}) \cdot P(\text{like} \mid \text{I}) \cdot P(\text{apple} \mid \text{I like})P(w_1, w_2, \dots, w_m) = \prod_{i=1}^{m} P(w_i \mid w_1, \dots, w_{i-1})P(A\mid B) = \dfrac{P(A,B)}{P(B)}.(b) Markov assumption
Depend only on the preceding n-1 words, rather than the entire history:
P(w_1, \dots, w_m) \approx \prod_{i=1}^{m} P(w_i \mid w_{i-n+1}, \dots, w_{i-1})
| Model | Formula |
|---|---|---|
1 | unigram |
|
2 | bigram |
|
3 | trigram |
|
(c) Maximum likelihood estimation (MLE)
Estimate conditional probabilities using relative frequencies:
P(w_i \mid w_{i-1}) = \frac{C(w_{i-1}, w_i)}{C(w_{i-1})}, \qquad
P(w_i) = \frac{C(w_i)}{M}Here C(\cdot) denotes a count, and M is the total number of tokens.
A hand-calculated example
Corpus (two sentences, with boundaries marked by <s> <eos>):
<s> yes no no no no yes <eos>
<s> no no no yes yes no <eos>Probability | Calculation | Result |
|---|---|---|
|
| 0.5 |
|
| 0.5 |
|
| 0.625 |
|
| 0.25 |
|
| 0.25 |
|
| 0.125 |
In the corpus, yes occurs 4 times and no occurs 8 times. The possible successors to a given word must include the end-of-sentence marker. For example, the successor probabilities for no sum to 5/8+2/8+1/8=1.
Problem | What happens | Remedy |
|---|---|---|
a) Long-distance dependencies | Considers only the preceding | Increase |
b) Very small probabilities | Multiplying dozens of values | Add log probabilities: |
c) Unseen N-grams (zero probability) | An N-gram absent from training has count 0 → the entire sentence receives probability 0 | Smoothing; see Section 4 |
Goal: assign nonzero probabilities to unseen N-grams while keeping the distribution normalised, with probabilities summing to 1 (conservation of probability mass).
Basic idea: pretend that every N-gram has occurred at least once; increment every count by +1.
P_{\text{add1}}(w_i) = \frac{C(w_i) + 1}{M + \vert V\vert }
\qquad\text{(unigram)}P_{\text{add1}}(w_i \mid w_{i-1}) = \frac{C(w_{i-1} w_i) + 1}{C(w_{i-1}) + \vert V\vert }
\qquad\text{(bigram)}Adding \vert V\vert to the denominator keeps the probabilities summing to 1 (each of the \vert V\vert candidates receives one extra count).
Problem: +1 is "too much" for low-frequency words and sparse corpora. It assigns a large amount of probability mass to unseen events, substantially reducing the probabilities of seen N-grams and introducing considerable distortion.
P_{\text{add-}k}(w_i \mid w_{i-2}, w_{i-1}) = \frac{C(w_{i-2}, w_{i-1}, w_i) + k}{C(w_{i-2}, w_{i-1}) + k\,\vert V\vert }k is a hyperparameter that must be chosen by the practitioner; 0<k<1 usually works better than k=1; the best k must be determined experimentally on a validation set.k; different values of k can produce substantially different smoothing effects;Idea: from each seen word, "borrow" a fixed count d (for example d=0.1) and give the corresponding probability mass to unseen words.
P_{\text{abs}}(w_i \mid w_{i-1}) = \frac{C(w_{i-1}, w_i) - d}{C(w_{i-1})}, \quad \text{if } C(w_{i-1},w_i) > 0Example (context = alleged; 5 seen bigrams and 2 unseen bigrams)
Word | counts | Unsmoothed probability | Add-α (α=0.1) effective count | Add-α smoothed probability | Discounting (d=0.1) effective count | Discounted probability |
|---|---|---|---|---|---|---|
impropriety | 8 | 0.4 | 7.826 | 0.391 | 7.9 | 0.395 |
offense | 5 | 0.25 | 4.928 | 0.246 | 4.9 | 0.245 |
damage | 4 | 0.2 | 3.961 | 0.198 | 3.9 | 0.195 |
deficiencies | 2 | 0.1 | 2.029 | 0.101 | 1.9 | 0.095 |
outbreak | 1 | 0.05 | 1.063 | 0.053 | 0.9 | 0.045 |
infirmity | 0 | 0 | 0.097 | 0.005 | 0.25 | 0.013 |
alleged | 0 | 0 | 0.097 | 0.005 | 0.25 | 0.013 |
Total | 20 | 1.0 | 20 | 1.0 | 20 | 1.0 |
8-0.1=7.9, 5-0.1=4.9…; the total "borrowed" effective count is 5\times0.1=0.5, corresponding to probability mass 0.5/20=0.025;0.5 is split equally between the 2 unseen words: 0.5/2 = 0.25 (effective count), which normalises to 0.25/20=0.0125\approx0.013.Idea: use discounted probabilities for seen events; for unseen events, redistribute the reserved mass according to a lower-order model.
P_{\text{katz}}(w \mid h) =
\begin{cases}
\dfrac{C^*(h,w)}{C(h)}, & \text{if } C(h,w) > 0 \\[2mm]
\alpha(h)\,P_{\text{lower}}(w), & \text{otherwise}
\end{cases}Here h=w_{i-1} is the context, and C^*(h,w) is the discounted count. Katz typically uses Good–Turing-based count discounts rather than subtracting the same constant from every seen count. The backoff weight is:
\alpha(h)=\frac{1-\sum_{w:C(h,w)>0}C^*(h,w)/C(h)}{\sum_{w:C(h,w)=0}P_{\text{lower}}(w)}The numerator is the probability mass left by the higher-order model. The denominator sums the lower-order probabilities of words unseen in the current context. Together, they keep the final distribution normalised.
A limitation of Katz backoff
P(\text{Kong}) may exceed P(\text{glasses}), so Kong could be selected incorrectly even though it almost always follows King.Idea: allocate discounted mass according to versatility—the number of distinct words a word can follow—rather than raw counts.
Formula: interpolated form
The following is the common interpolated Kneser–Ney formulation. The lower-order distribution contributes even when the higher-order count is nonzero: it is added to the discounted higher-order probability.
P_{KN}(w_i \mid w_{i-1}) =
\frac{\max(C(w_{i-1},w_i)-D,0)}{C(w_{i-1})}
+\lambda(w_{i-1})\,P_{\text{cont}}(w_i)P_{\text{cont}}(w_i)=
\frac{\vert\{u:C(u,w_i)>0\}\vert}{\vert\{(u,v):C(u,v)>0\}\vert},\qquad
\lambda(h)=\frac{D\,\vert\{v:C(h,v)>0\}\vert}{C(h)}w_i (that is, w_i's number of context types);\lambda(h): the total probability mass discounted in context h; when 0<D<1, each seen successor contributes D/C(h). Adding the higher-order and lower-order distributions still gives total probability 1.Idea: instead of selecting one order through backoff, form a weighted mixture of N-gram models of different orders, with weights tuned on held-out data.
P_{IN}(w_i \mid w_{i-1}, w_{i-2}) = \lambda_3 P_3(w_i \mid w_{i-2}, w_{i-1}) + \lambda_2 P_2(w_i \mid w_{i-1}) + \lambda_1 P_1(w_i)\sum_k \lambda_k = 1, \qquad \lambda_k \ge 0\lambda is learned on held-out data using EM or grid search, rather than chosen arbitrarily;Method | Core idea | Advantages | Limitations |
|---|---|---|---|
Add-1 | Add 1 to every count | Simplest; ensures nonzero, normalised probabilities | Adds too much to sparse data and sharply reduces seen-event probabilities |
Add-k | Add k to every count | Milder than add-one | Must tune |
Absolute Discounting | Subtract | Simple; works better than add-k | Does not distinguish the information carried by lower-order contexts |
Katz Backoff | Back off to a lower order for unseen events | Retains higher-order precision | Uses raw backoff probabilities, ignoring context diversity (the reading Kong problem) |
Kneser-Ney | Use continuation probabilities to allocate discounted mass | A strong baseline for classical N-gram models | More complex formulas; requires two sets of counts |
Interpolation | Weighted mixture of different model orders | Stable; often better than backoff | Must tune on held-out data: |
d (usually represented as a feature vector) plus a fixed set of classes C=\{c_1, c_2, \dots, c_k\} (categorical, rather than continuous or ordinal values).\hat{c} \in C.Aspect | Meaning |
|---|---|
Bias | Systematic error caused by a model's limitations or simplifying assumptions; assumptions that do not match the true data can introduce substantial bias |
Variance | The model's sensitivity to its training set. Greater sensitivity means larger changes in results when trained on a different sample, making overfitting more likely |
Underlying assumptions | Conditions the model relies on, such as feature independence, linear boundaries or meaningful distances; violations can affect performance |
Complexity | Time and space costs of training and inference, and scalability to large datasets |
Speed | Whether training and prediction latency meet production requirements |
Bias–variance trade-off: high bias often corresponds to underfitting, while high variance often corresponds to overfitting. Under squared loss, expected prediction error decomposes into squared bias, variance and irreducible noise. This framework also helps explain modelling choices in classification.
P(C\mid F) \propto P(F\mid C)\,P(C)That is, "class prior × probability of these features given the class".
P(F \mid C) = \prod_{f \in F} P(f \mid C)P(y=c \mid x) = \frac{\exp(w_c^\top x + b_c)}{\sum_{c'} \exp(w_{c'}^\top x + b_{c'})}\min_{w,b}\ \tfrac{1}{2}\Vert w\Vert ^2 \quad \text{s.t.}\quad y_i(w^\top x_i + b) \ge 1k nearest training examples in feature space and classify by their majority class.Hold-out evaluation: split data into train / dev (validation) / test sets. Select hyperparameters on dev; use test only once for the final report.
Classified As A | Classified As B | |
|---|---|---|
True A | 79 (TP) | 13 (FN) |
True B | 8 (FP) | 10 (TN) |
Accuracy
\text{Accuracy} = \frac{TP + TN}{N} = \frac{79+10}{110} = 0.809Precision: the proportion of predicted positives that are actually positive
P = \frac{TP}{TP + FP} = \frac{79}{79+8} = 0.908Recall: the proportion of actual positives that are retrieved
R = \frac{TP}{TP + FN} = \frac{79}{79+13} = 0.859F1-Score: the harmonic mean of precision and recall
F_1 = \frac{2PR}{P+R} = \frac{2 \times 0.908 \times 0.859}{0.908 + 0.859} = 0.883Why the harmonic mean rather than the arithmetic mean? The harmonic mean is pulled down by the smaller value: F1 is high only when both P and R are high. This prevents either high recall with low precision or high precision with low recall from receiving a high score.
Multiclass metrics
Metric | Method | Characteristics |
|---|---|---|
Macro-average | Calculate P/R/F1 separately for each class, then take the arithmetic mean across classes | Every class has equal weight, increasing the influence of minority classes and exposing poor long-tail performance |
Micro-average | First pool TP/FP/FN across all classes, then calculate P/R/F1 once | Every example has equal weight, so larger classes dominate; in single-label multiclass classification, micro-F1 = accuracy |
Definition: assign each word in a sentence its grammatical category, or part of speech.
Example: Janet/NNP will/MD back/VB the/DT bill/NN
Notice that back is a verb here, meaning "support", rather than a noun or adverb; its role depends on context.
Applications:
Open classes: new words can be added and old words can disappear
Class | Subcategories |
|---|---|
Nouns | Proper (Melbourne) / common; common nouns divide further into mass (water) / count (chair) |
Lexical verbs | Can have rich inflection (sing/sang/sung); transitive or intransitive according to use |
Adjectives | Gradable (very tall) / non-gradable (dead) |
Adverbs | Locative (here, there) / degree (very, extremely) |
Closed classes: relatively fixed membership, with additions and removals uncommon
The same word form can have several parts of speech, with a highly uneven distribution:
A simple baseline assigns each word its most frequent POS tag in the training set. This exploits the uneven distribution of tags but cannot disambiguate using the current context. Accuracy depends on the corpus and the treatment of OOV words.
Tagset | Number of tags | Characteristics |
|---|---|---|
Brown | 87 | One of the earliest corpus tagsets; fine-grained |
Penn Treebank (PTB) | 45 | The most widely used in NLP, including NN, NNS, NNP, VB, VBD, VBG, JJ, RB, IN, DT, MD, CC, PRP… |
CLAWS5 / BNC | 61 | One version of CLAWS; tag counts differ between versions |
Early Universal Tagset | 12 | NOUN, VERB, ADJ, ADV, PRON, DET, ADP, NUM, CONJ, PRT, ., X; do not confuse this with the 17 UPOS categories in Universal Dependencies |
A classic ambiguity example (Penn Treebank tags)
Time flies like an arrow
Time/NN flies/VBZ like/IN an/DT arrow/NN
Fruit flies like a banana
Fruit/NN flies/NNS like/VBP a/DT banana/NNThe same word, flies, is a verb in the first sentence ("time passes quickly") and a noun in the second ("fruit flies"). Context is needed to tell them apart.
Task: POS tagging—given the entire word sequence W = w_1 \dots w_n, find the optimal tag sequence T = t_1 \dots t_n.
Limitations of existing approaches: predicting each word independently cannot use dependencies between tags. A greedy classifier that conditions on previously predicted tags can propagate errors: an earlier mistake affects later predictions.
New idea: give the model the whole sentence and have it produce an entire tag sequence.
New problem: sentence length varies, and the number of possible tag combinations is \vert T\vert ^n, which is exponential, so enumeration is infeasible.
Solution: use a model that models individual words while treating the whole sentence as a unit during learning and prediction. This is called sequence labelling, or structured prediction.
How an HMM works: given a sentence, find the tag sequence with the highest probability among all possible sequences.
Advantages:
\hat{T} = \arg\max_{T} P(T \mid W)
= \arg\max_{T} \frac{P(W \mid T)\,P(T)}{P(W)}
= \arg\max_{T} P(W \mid T)\,P(T)(P(W) does not depend on T, so it can be ignored; this applies Bayes' rule and drops the denominator)
Figure 7-1 HMM graphical model: solid arrows represent state transitions
P(t_i\mid t_{i-1})(matrix A), and dashed arrows represent emissionsP(w_i\mid t_i)(matrix O).
Assumption | Statement | Role |
|---|---|---|
Output independence | The word at position | Factorises the sentence probability given the tags into a product over words |
Markov assumption | The current tag depends only on the previous tag: | Factorises the tag-sequence probability into a product of first-order transitions |
Therefore:
\hat{T} = \arg\max_{T} \prod_{i=1}^{n} \underbrace{P(w_i \mid t_i)}_{\text{emission}} \cdot \underbrace{P(t_i \mid t_{i-1})}_{\text{transition}}This also explains why an HMM is a generative model: it models the joint probability
P(W,T) = P(T)P(W\mid T).
Parameter | Name | Meaning |
|---|---|---|
| Emission / observation probability O | Probability that a tag generates a particular word |
| Transition probability A | Probability of a particular tag following the previous tag |
Estimation: again, use maximum likelihood estimation (MLE), by counting:
P(w_i \mid t_i) = \frac{\text{Count}(w_i, t_i)}{\text{Count}(t_i)},
\qquad
P(t_i \mid t_{i-1}) = \frac{\text{Count}(t_{i-1}, t_i)}{\text{Count}(t_{i-1})}What about the first tag? Add a special start symbol <s> before each sentence, so the first term is P(t_1 \mid \text{<s>}):
P(t_1 \mid \text{<s>}) = \frac{\text{Count}(\text{<s>}, t_1)}{\text{Count}(\text{<s>})}Similarly, append </s> at the end, making P(\text{</s>} \mid t_n) a learnable transition. The earlier product omits this end-of-sentence factor for brevity; the complete path probability also includes it.
What about unseen words? Use smoothing again (Section 4): add-k or add-one for the emission table, or map low-frequency words to <UNK> so that the emission probability of <UNK> is shared by all low-frequency words.
Given a trained HMM (two tables: transition matrix A and emission matrix O), predict the tag sequence for the input sentence.
Core idea: choose the tag combination with the highest joint probability:
\hat{t} = \arg\max_{t} P(W \mid t)\,P(t)
= \arg\max_{t} \prod_{i=1}^{n} P(w_i \mid t_i)\,P(t_i \mid t_{i-1})Why not predict one word at a time? (the limitation of greedy decoding)
\vert T\vert ^n combinations is infeasible → use Viterbi dynamic programming to find the global optimum; for a fixed tagset size, runtime grows linearly with sentence length.Aspect | Generative (HMM) | Discriminative (CRF / classifier) |
|---|---|---|
What is modelled | Joint probability | Conditional probability |
Typical uses | Can generate language; HMMs also support unsupervised learning | Classification, prediction and sequence labelling |
Training | Usually supervised or semi-supervised; also unsupervised through EM | Usually supervised |
Features | Limited features: uses emission probabilities for the observations themselves | Rich features such as prefixes, suffixes, word forms, context words and external dictionaries |
Data requirements | Simple structural assumptions may help when learning from small datasets | Often better predictions with sufficient data and features; still depends on the task and model |
Examples | Naïve Bayes, HMMs; neural language models can also perform generative modelling | Logistic regression, CRFs, SVMs and neural classifiers |
Discriminative models directly optimise "predict the output given the input", without explicitly modelling the input distribution
P(W). They can therefore focus on prediction; whether they perform better still depends on the task, data and model.
Keep not just "the best tag for the current word", but "the best path score for each possible ending tag", considering every combination when moving to the next word.
For each position t and tag j, record the cumulative score of the best path ending in j, \delta_t(j), and its backpointer \psi_t(j).
\delta_1(j) = P(t_1 = j \mid \text{<s>}) \cdot P(w_1 \mid j)\delta_t(j) = \max_{i \in T}\Big[\delta_{t-1}(i)\cdot P(j \mid i)\Big]\cdot P(w_t \mid j)\psi_t(j) = \arg\max_{i \in T}\Big[\delta_{t-1}(i)\cdot P(j\mid i)\Big]Termination:
\hat{t}_n = \arg\max_{j}\big[\delta_n(j)\,P(\text{</s>}\mid j)\big], \qquad
\hat{t}_{t} = \psi_{t+1}(\hat{t}_{t+1}) \ \text{(backtracking)}If the model has no explicit end state, simply compare \delta_n(j) at termination. Both examples below use this simplification.
Intuitive example: Can Play
Transition matrix (excerpt; rows give the conditioning event P(\cdot\mid \text{row}))
NNP | MD | VB | JJ | NN | RB | DT | |
|---|---|---|---|---|---|---|---|
<s> | 0.2767 | 0.0006 | 0.0031 | 0.0453 | 0.0449 | 0.0510 | 0.2026 |
NNP | 0.3777 | 0.0110 | 0.0009 | 0.0084 | 0.0584 | 0.0090 | 0.0025 |
MD | 0.0008 | 0.0002 | 0.7968 | 0.0005 | 0.0008 | 0.1698 | 0.0041 |
VB | 0.0322 | 0.0005 | 0.0050 | 0.0837 | 0.0615 | 0.0514 | 0.2231 |
JJ | 0.0366 | 0.0004 | 0.0001 | 0.0733 | 0.4509 | 0.0036 | 0.0036 |
NN | 0.0096 | 0.0176 | 0.0014 | 0.0086 | 0.1216 | 0.0177 | 0.0068 |
RB | 0.0068 | 0.0102 | 0.1011 | 0.1012 | 0.0120 | 0.0728 | 0.0479 |
DT | 0.1147 | 0.0021 | 0.0002 | 0.2157 | 0.4744 | 0.0102 | 0.0017 |
(Data from Jurafsky and Martin's Speech and Language Processing, Chapter 18, Figure 18.12, based on the WSJ corpus without smoothing. Only some tags are shown, so the rows need not sum to 1; it is the full transition distribution that is normalised.)
Emission matrix (Speech and Language Processing, Figure 18.13)
Janet | will | back | the | bill | |
|---|---|---|---|---|---|
NNP | 0.000032 | 0 | 0 | 0.000048 | 0 |
MD | 0 | 0.308431 | 0 | 0 | 0 |
VB | 0 | 0.000028 | 0.000672 | 0 | 0.000028 |
JJ | 0 | 0 | 0.000340 | 0 | 0 |
NN | 0 | 0.000200 | 0.000223 | 0 | 0.002337 |
RB | 0 | 0 | 0.010446 | 0 | 0 |
DT | 0 | 0 | 0 | 0.506099 | 0 |
Procedure: build a \vert T\vert \times n trellis, fill in \delta column by column, and record the preceding tag in each cell. Backtrack from the largest value in the final column.
This two-state toy model uses artificial values solely to demonstrate dynamic programming. N and V are state labels; it does not imply that they can function as a verb in real English.
Emission probabilities
they | fish | |
|---|---|---|
N | 0.7 | 0.3 |
V | 0.4 | 0.6 |
Transition probabilities
N | V | |
|---|---|---|
<s> | 0.6 | 0.4 |
N | 0.8 | 0.2 |
V | 0.7 | 0.3 |
Figure 8-1 they fish Viterbi trellis: each cell retains only the "best prefix score ending in this tag"
\delta. The red arrows show the optimal path recovered by backtracking: they/N → fish/N.
Enumerating all 4 paths
Path | Calculation | Probability |
|---|---|---|
N N |
| 0.1008 ✅ Optimal |
N V |
| 0.0504 |
V N |
| 0.0336 |
V V |
| 0.0288 |
Result: they/N fish/N. Looking only at the emission probabilities of fish, we find that P(\text{fish}\mid V)=0.6 exceeds P(\text{fish}\mid N)=0.3. Once transition probabilities are included, however, the optimal path ends in N. Emission probabilities are not tag posteriors and cannot directly determine the tag. This example demonstrates the value of transition information; it does not establish a case where greedy decoding that incorporates transitions at each step necessarily fails.
Property | Explanation |
|---|---|
Time complexity |
|
Space complexity | If only the optimal score is needed, retain two rolling columns, using |
Why it works | Optimal substructure: the best path to position |
Numerical underflow | Products of probabilities quickly underflow to 0. Practical implementations use log probabilities (multiplication becomes addition, with |
Higher-order variants | Use a tag trigram (second-order HMM): |