Part-of-speech tagging
Part-of-speech (POS) tagging assigns a part-of-speech label (noun, verb, etc.) to each token in a sentence; engineers use it for downstream NLP tasks like parsing, NER, and information extraction.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Part-of-speech (POS) tagging is the process of labelling each word token in a sentence with its grammatical category (noun, verb, adjective, etc.). Engineers use POS tagging as a foundational step in many NLP systems: it improves syntactic parsing, named-entity recognition, information extraction and other pipelines where knowing a word's role reduces ambiguity.
Key ideas
Start with definitions and simple assumptions.
- Token — a contiguous sequence of characters treated as a unit (usually a word). Define tokens before using them.
- Part-of-speech (POS) tag — a label that indicates the grammatical category of a token (for example, NN for noun, VB for verb). When I say "tag" I mean a POS tag.
- Tagset — the set of allowed POS tags (for example, Penn Treebank tags like NN, NNS, VB, VBD). Specify the tagset you use in an answer.
- Ambiguity — when a token can have more than one possible tag in different contexts (e.g., "book" can be a noun or a verb).
- Supervised tagging — a method that learns a model from a labelled corpus (sentences annotated with tags). Requires a training corpus.
- Rule-based tagging — uses hand-written rules (for example: "if a word ends in -ed and previous tag is VB, tag as VBD").
- Stochastic tagging — uses probabilistic models (e.g., HMM) trained from annotated data.
- Hidden Markov Model (HMM) — a probabilistic sequence model where the sequence of tags is a hidden state sequence and observed words are emissions from those states. The main assumptions are the Markov assumption for tags (usually first-order: each tag depends only on the previous tag) and conditional independence of words given their tag.
Exact derivation universities expect (HMM + maximum-likelihood): We want the best tag sequence t1..tn for words w1..wn. Start from the posterior: choose tags that maximise P(t1..tn | w1..wn). Using Bayes' rule this is equivalent to maximising P(w1..wn | t1..tn)·P(t1..tn) (denominator P(w1..wn) is constant for all tag sequences). Apply the HMM factorisation with the first-order Markov assumption and conditional independence of words given tag: P(t1..tn) = P(t1) · Π_{i=2..n} P(ti | t_{i-1}) P(w1..wn | t1..tn) = Π_{i=1..n} P(wi | ti) So we select tags that maximise P(t1)·Π_{i=2..n} P(ti | t_{i-1}) · Π_{i=1..n} P(wi | ti).
This argmax is computed efficiently with the Viterbi algorithm (dynamic programming). Define delta_i(j) = max probability of a tag sequence for the first i words that ends in tag j. The recurrence is: delta_1(j) = P(t1=j)·P(w1|t1=j) delta_i(j) = max_k [ delta_{i-1}(k)·P(ti=j | t_{i-1}=k) ] · P(wi | ti=j) Store backpointers to recover the best path. Time complexity of Viterbi is O(n|T|^2) and memory is O(n|T|) (or O(|T|) with rolling arrays plus backpointers); implement in log space to avoid underflow.
Training (MLE estimates) from labelled data:
- Transition probability P(t_j | t_i) = count(t_i followed by t_j) / count(t_i)
- Emission probability P(word | tag) = count(tag emits that word) / count(tag)
Handling unknown words and smoothing:
- Add-one (Laplace) smoothing: P(word|tag) = (count(tag->word) + 1) / (count(tag) + V) where V is vocabulary size. This is simple but not always best.
- Also smooth transition probabilities (e.g., add-k or backoff smoothing for tag bigrams), and include start/end transitions in the model.
- Better choices: Good-Turing, backoff to suffix-based or morphological models, or use open-class tags heuristics (use capitalisation, numeric patterns).
Other tagger types:
- Transformation-based tagging (Brill) — start with an initial guess (e.g., most frequent tag), then learn ordered transformation rules that improve accuracy.
- Maximum-entropy / Conditional models and CRFs — discriminative models that model P(tags | words, features) directly; often give higher accuracy and allow many features (prefixes, suffixes, capitalization, etc.).
- Neural sequence taggers (e.g., BiLSTM-CRF, Transformer/BERT-based) — use embeddings and contextual encoders; state-of-the-art accuracy with sufficient data; CRF layers are decoded with Viterbi-style DP.
Evaluation:
- Accuracy = correct tags / total tags.
- Per-tag precision/recall/F1 computed from true/false positives/negatives per tag.
- Use confusion matrices to inspect which tags are confused.
Practical issues: choice of tagset (granular vs coarse), domain mismatch between training and test data, unknown words, OOV rates, and speed vs accuracy trade-offs.
Formulas
argmax_{t1..tn} P(t1..tn | w1..wn) = argmax_{t1..tn} P(w1..wn | t1..tn) · P(t1..tn) — P(·) are probabilities; applies for MAP decoding.
P(t1..tn) = P(t1) · Π_{i=2..n} P(ti | t_{i-1}) — first-order Markov assumption for tags.
P(w1..wn | t1..tn) = Π_{i=1..n} P(wi | ti) — words independent given their tags (HMM emission assumption).
delta_1(j) = P(t1=j) · P(w1 | t1=j) — initialization in Viterbi; delta_i(j) defined as max joint prob for first i words ending in tag j.
delta_i(j) = [ max_k delta_{i-1}(k) · P(ti=j | t_{i-1}=k) ] · P(wi | ti=j) — Viterbi recurrence; use backpointers to recover argmax path.
P(t_j | t_i) = count(t_i, t_j) / count(t_i) — MLE for transitions; counts from tagged corpus.
P(word | tag) = count(tag -> word) / count(tag) — MLE for emissions.
P_smooth(word | tag) = (count(tag->word) + 1) / (count(tag) + V) — Laplace smoothing; V is vocabulary size.
(Each symbol: t_i is tag at position i, w_i is word at position i, count(·) are integer counts from training data; probabilities are unitless and dimensionless.)
Worked examples
Example 1 — Manual Viterbi computation (university style). Given a tiny HMM with tags {N, V}. Parameters: π(N)=0.6, π(V)=0.4 A (transition): a_NN=0.3, a_NV=0.7, a_VN=0.8, a_VV=0.2 B (emission) for words {fish, sleep}: b_N(fish)=0.5, b_V(fish)=0.1, b_N(sleep)=0.1, b_V(sleep)=0.6 Sentence: "fish sleep" (w1=fish, w2=sleep). Step 1 (i=1): delta1(N)=π(N)·b_N(fish)=0.6·0.5=0.300 delta1(V)=π(V)·b_V(fish)=0.4·0.1=0.040 Step 2 (i=2): compute for tag N: from N: 0.300·a_NN·b_N(sleep)=0.300·0.3·0.1=0.0090 from V: 0.040·a_VN·b_N(sleep)=0.040·0.8·0.1=0.0032 max = 0.0090 (backpointer = N) for tag V: from N: 0.300·a_NV·b_V(sleep)=0.300·0.7·0.6=0.1260 from V: 0.040·a_VV·b_V(sleep)=0.040·0.2·0.6=0.0048 max = 0.1260 (backpointer = N) Final: choose tag with max(delta2) = V with probability 0.126. Recover path using backpointers: t1=N, t2=V. Final answer: the best tag sequence is N V with joint probability 0.126.
Example 2 — Minimal Python Viterbi (runnable). This code implements the same HMM and prints the best tag sequence and probability.
# Minimal Viterbi for the tiny HMM used above
tags = ['N', 'V']
pi = {'N': 0.6, 'V': 0.4}
a = {('N','N'):0.3, ('N','V'):0.7, ('V','N'):0.8, ('V','V'):0.2}
b = {('N','fish'):0.5, ('V','fish'):0.1, ('N','sleep'):0.1, ('V','sleep'):0.6}
def viterbi(words):
n = len(words)
delta = [{}]
back = [{}]
# init
for t in tags:
delta[0][t] = pi[t] * b.get((t, words[0]), 0.0)
back[0][t] = None
# recursion
for i in range(1, n):
delta.append({})
back.append({})
for cur in tags:
best_prob = -1.0
best_prev = None
emit = b.get((cur, words[i]), 0.0)
for prev in tags:
prob = delta[i-1][prev] * a[(prev, cur)] * emit
if prob > best_prob:
best_prob = prob
best_prev = prev
delta[i][cur] = best_prob
back[i][cur] = best_prev
# termination
last_tag = max(tags, key=lambda t: delta[-1][t])
prob = delta[-1][last_tag]
# recover path
path = [last_tag]
for i in range(len(words)-1, 0, -1):
path.append(back[i][path[-1]])
path.reverse()
return path, prob
if __name__ == '__main__':
words = ['fish', 'sleep']
path, prob = viterbi(words)
print('Tagged sequence:', ' '.join(w + '/' + t for w,t in zip(words, path)))
print('Probability: {:.3f}'.format(prob))
Sample input (no stdin; run the script):
Exact output:
Tagged sequence: fish/N sleep/V Probability: 0.126
Example 3 — Model answer (short essay question). "Explain the main differences between rule-based, HMM and CRF taggers and when you would choose each." Model answer (points to include): definition of each method, data requirements (rule-based needs linguist effort, HMM needs annotated corpus), modelling direction (HMM generative P(words,tags), CRF discriminative P(tags|words,features)), ability to include arbitrary features (CRF yes), decoding algorithm (Viterbi for HMM and CRF-like models with dynamic programming), typical accuracy order (rule-based < HMM < CRF, depending on features), when to choose: rule-based for low-data, CRF for high accuracy with rich features, HMM as simple baseline and when generative model provides benefits.
Common mistakes
- Using raw counts where probabilities are required (not dividing by counts totals).
- Mishandling unknown words (assuming emission prob exists for every word-tag pair). Always state your OOV strategy.
- Confusing tokenisation and tagging: tokenisation must be done first and affects tagging.
- When showing Viterbi steps, mixing up multiplication order or forgetting to keep backpointers.
- Quoting accuracy without test set or cross-validation details (report dataset and OOV rate).
For your exam
Kinds of questions you will see:
- Definitions: define HMM, Viterbi, emission/transition probabilities. Full marks: give formal definition, assumptions, and a short example.
- Short notes: compare taggers (rule-based, HMM, CRF). Full marks: list pros/cons, data needs, and decoding complexity.
- Derivations: derive the HMM factorisation and Viterbi recurrence. Full marks: show Bayes rule step, factorisation details and the recurrence with explanation of backpointers.
- Numericals: small HMM parameter values and a short sentence; perform Viterbi manually. Full marks: show every step (initialisation, recursion with each candidate, backpointer choices) and the final tagged sequence with probability.
- Programs: implement Viterbi or training MLE. Full marks: clean code, correct I/O, handles unknown words or states assumption, prints result.
- Diagrams: draw a simple chain graphical model for HMM (nodes t1..tn as hidden states, w1..wn observed beneath each tag; arrows from t_{i-1} to t_i and from t_i to w_i). Label nodes and arrows clearly.
Quick check
- What is the main assumption of a first-order HMM for POS tagging?
- Write the Viterbi recurrence for delta_i(j) in words (not formula).
- Give one method to handle unknown (out-of-vocabulary) words in emission probabilities.
Answers: 1) Each tag depends only on the previous tag (first-order Markov). 2) delta_i(j) is the maximum over previous tags k of (delta_{i-1}(k) times transition prob from k to j), multiplied by the emission prob of the current word given tag j. 3) Use smoothing (e.g., add-one), use suffix/morphological backoff, or assign small uniform probability based on tag class.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?