🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

POS Tagging with HMMs and Viterbi Decoding

Sequence LabelingPOS TaggingđŸŸĸ Free Lesson

One word, one decision, made in context

Part-of-speech tagging assigns a grammatical category to every token, and it looks trivial until you try to do it without context. Time flies like an arrow contains at least three readings of flies, and only the surrounding words settle it. The task is therefore not a lookup but a sequence-labelling problem: the best tag for a token often depends on the tag of its neighbour, because English grammar forbids many combinations outright. A determiner cannot be followed by another determiner, and a past-tense verb cannot follow an article.

That structural constraint is what made tagging a showcase for graphical models. Decoding the highest-scoring tag sequence is exponentially expensive if you enumerate sequences directly, yet it collapses to a linear-time dynamic program once the score factorises into local potentials — and Viterbi decoding is that program. Even if you will ship a transformer tagger, the reasoning survives as the intuition for why sequence models beat per-token classifiers.

Downstream systems care about tagging more than they let on. Lemmatization needs the tense to choose the right dictionary form, named entity recognition uses capitalisation and category priors from tags, and sentiment analysis leans on adjectives as its primary signal. Even a modern retrieval pipeline benefits, because parsing a query into its heads and modifiers — a step that needs tags — lets you drop modifiers that do not affect the match rather than treating every token as equally important.

Tag sets and what they trade off

A tag set is a resolution choice. Coarse sets are easier to annotate consistently and easier to learn from small data; fine sets capture the distinctions downstream components actually need.

Tag setSizeDistinguishesTypical use
Universal (UPOS)17Coarse grammatical classCross-lingual NLP, low-resource
Penn Treebank45Tense, number, personEnglish benchmarks, parsing
Penn with particles45+RP for phrasal verbsTreebank annotation
Brown87Subtle fine distinctionsLegacy corpora
Morphological (feats)VariableCase, gender, animacySlavic and Finnic languages

The Universal set is the pragmatic default for a pipeline that must run on several languages, because it exists for all of them and removes the constant translation between tag inventories. Reach for Penn's 45 tags when you are feeding a parser or building a rule that keys on verb tense specifically.

Ambiguity is measurable

Before modelling anything, quantify how hard the task is. The ambiguity rate — the fraction of word types that appear with more than one tag — and the token-level rate tell you the ceiling for any context-free approach. A tagger that ignores context can only ever reach the token-level unigram baseline.

python
from collections import defaultdict, Counter

def tag_ambiguity(tagged_sents):
    types = defaultdict(Counter)
    for sent in tagged_sents:
        for w, t in sent:
            types[w][t] += 1
    ambiguous = {w: c for w, c in types.items() if len(c) > 1}
    tokens = sum(sum(c.values()) for c in types.values())
    best = sum(max(c.values()) for c in types.values())
    return {
        "types": len(types),
        "ambiguous_types": len(ambiguous),
        "token_accuracy_ceiling": round(best / tokens, 4),
        "top_ambiguous": sorted(
            ambiguous, key=lambda w: -sum(ambiguous[w].values())
        )[:5],
    }

toy = [
    [("The", "DT"), ("time", "NN"), ("flies", "VBZ"), ("fast", "RB")],
    [("Time", "NN"), ("flies", "VBZ"), ("fast", "RB"), (".", ".")],
    [("They", "PRP"), ("flies", "VBP"), ("again", "RB"), (".", ".")],
]
print(tag_ambiguity(toy))
# {'types': 8, 'ambiguous_types': 2, 'token_accuracy_ceiling': 0.8125, ...}

The ceiling printed here is what a majority-vote tagger achieves with no context at all. Every point above it is attributable to sequence structure, which is a clean way to justify the complexity of what follows.

The HMM formulation

A hidden Markov model treats tags as hidden states and words as emissions. It makes two assumptions: the probability of a tag depends only on the previous tag (the Markov assumption), and the probability of a word depends only on its own tag. Estimation is counting with smoothing; decoding is dynamic programming.

QuantityDefinitionEstimate
Start probabilityP of first tagCount of sentence-initial tag over all sentences
TransitionP of tag j given tag iCount of i followed by j over count of i
EmissionP of word given tagCount of word tagged t over count of t
JointP of sequenceProduct of start, transitions, and emissions

The assumptions are wrong — flies depends on more than its tag — and the model works anyway, because decoding needs only a good ranking, not accurate joint probabilities. The practical failure is the vocabulary problem: any word not seen with a tag has zero emission probability and annihilates the sequence, so every implementation needs a backoff for unseen tokens.

Viterbi decoding in full

The algorithm carries a table of the best probability of ending in each state at each position, together with the pointer that produced it. Each step extends every previous state by one transition, taking the maximum, which turns an exponential search into T times S squared work.

python
import math

def viterbi(obs, states, start_p, trans_p, emit_p, unk_emit=1e-6):
    V = [{}]
    path = {}
    for s in states:
        V[0][s] = start_p.get(s, 0.0) * emit_p.get(s, {}).get(obs[0], unk_emit)
        path[s] = [s]

    for t in range(1, len(obs)):
        V.append({})
        newpath = {}
        for s in states:
            best_prob, best_state = max(
                (V[t - 1][p] * trans_p.get(p, {}).get(s, 1e-12) *
                 emit_p.get(s, {}).get(obs[t], unk_emit), p)
                for p in states
            )
            V[t][s] = best_prob
            newpath[s] = path[best_state] + [s]
        path = newpath

    final_state = max(states, key=lambda s: V[-1][s])
    return V[-1][final_state], path[final_state]

states = ["DT", "NN", "VB", "RB"]
obs = ["the", "cats", "quietly", "sleep"]

start_p = {"DT": 0.7, "NN": 0.2, "VB": 0.05, "RB": 0.05}
trans_p = {
    "DT": {"NN": 0.9, "VB": 0.05, "RB": 0.05},
    "NN": {"VB": 0.6, "RB": 0.3, "DT": 0.1},
    "VB": {"RB": 0.5, "DT": 0.3, "NN": 0.2},
    "RB": {"VB": 0.8, "NN": 0.2},
}
emit_p = {
    "DT": {"the": 1.0},
    "NN": {"cats": 0.7, "sleep": 0.3},
    "VB": {"sleep": 0.6, "quietly": 0.1},
    "RB": {"quietly": 1.0},
}

prob, tags = viterbi(obs, states, start_p, trans_p, emit_p)
print(tags, round(prob, 8))
# ['DT', 'NN', 'RB', 'VB'] 0.00378

Two implementation details matter. Probabilities multiply across a whole sentence and underflow to zero quickly, so real decoders work in log space and add instead of multiply. And the unk_emit fallback is not optional — without it, one unseen word sends every path to zero and the returned tags are an arbitrary artefact of floating-point ordering.

Backoff chains and trained taggers

Statistical taggers are built as a cascade: a bigram tagger, backed off by a unigram tagger, backed off by a regex or default tagger. Each layer only handles what the previous one could not, which is a clean way to combine context sensitivity with coverage.

python
import nltk
from nltk.tag import UnigramTagger, BigramTagger, TrigramTagger, DefaultTagger
nltk.download("treebank", quiet=True)

sents = nltk.corpus.treebank.tagged_sents()
train, test = sents[:3000], sents[3000:]

default = DefaultTagger("NN")
uni = UnigramTagger(train, backoff=default)
bi = BigramTagger(train, backoff=uni)
tri = TrigramTagger(train, backoff=bi)

for name, tagger in [("default", default), ("unigram", uni),
                     ("bigram", bi), ("trigram", tri)]:
    print(f"{name:<9} accuracy {tagger.accuracy(test):.4f}")

# measure how much context each layer contributes
print("trigram alone:", round(TrigramTagger(train).accuracy(test), 4))
print("unigram alone:", round(UnigramTagger(train).accuracy(test), 4))

Printing the standalone accuracies next to the chained ones is the instructive part: trigrams alone are brittle because most trigram contexts are never observed, while the chained model retains context where it has evidence and falls back gracefully everywhere else.

What neural taggers changed

A neural tagger replaces the hand-built features with learned representations: an embedding for the word, character-level features that compose the word's morphology, and a contextual encoder — BiLSTM historically, a transformer now — that produces a representation conditioned on both directions. Character features are the largest single win, because they let the model recognise -ing, -ed, and capitalisation patterns for words it has never seen, which is exactly where count-based emission tables fail.

Tag sets also stopped being a hard constraint. With a shared contextual encoder, a single model can project onto any tag inventory, so switching from Universal to Penn tags becomes a new output layer rather than a new annotated corpus. What has not changed is the evaluation: accuracy on a held-out treebank section, compared against the context-free baseline you measured at the start.

💡Always report the context-free baseline

Print unigram-only accuracy beside your final number. If the gap is small, either the context is not being used or the test set is dominated by tags predictable from the word type alone.

Common Mistakes

Running a trigram tagger without backoff

Fix: Most contexts are unseen, so standalone accuracy collapses; chain trigram to bigram to unigram to a default tag.

Multiplying probabilities across a long sentence

Fix: Work in log space to avoid underflow, which silently zeroes every path and returns arbitrary tags.

Forgetting an emission fallback for unseen words

Fix: One unknown token annihilates all paths; provide a smoothed or default emission probability.

Comparing accuracy across different tag sets

Fix: Accuracy on 17 Universal tags and on 45 Penn tags are not comparable; state the inventory with the number.

Best Practices

  • Start with the Universal tag set unless a downstream component requires finer distinctions
  • Measure the context-free ceiling first so the value of sequence structure is explicit
  • Use chained backoff taggers for coverage and log-space decoding for numerical stability
  • Inspect confusion pairs, since most residual error concentrates in a handful of ambiguous tags

Interview Questions

Q1: Why does POS tagging require sequence decoding rather than per-word classification?

Because tag transitions are constrained — a determiner cannot follow another determiner — so the best tag for a token depends on its neighbours, and independent classification violates those constraints.

Q2: What is the time complexity of Viterbi decoding and why?

T times S squared, where T is sequence length and S the tag count, because each state extends from each previous state once and the maximum is cached rather than recomputed.

Q3: How does a neural tagger handle a word it has never seen?

Through character-level or subword features composed into an embedding, so morphology and capitalisation still inform the prediction instead of falling back to an unknown emission.

Key Takeaways

  • Tagging is sequence labelling: transitions between tags carry as much signal as the words themselves
  • Tag-set size trades annotation consistency against downstream usefulness
  • The context-free baseline measures exactly how much value sequence structure adds
  • Viterbi turns exponential sequence search into linear dynamic programming by caching the best path per state
  • Neural taggers win mainly through character-level morphology and bidirectional context, not through different decoding
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement