← All posts

Part-of-Speech Tagging with a Hidden Markov Model and Viterbi

On this page
hidden tags DET NOUN VERB P(NOUN | DET) P(VERB | NOUN) words the count was P(count | NOUN)

“Count” is a noun in “the count was wrong” and a verb in “count the votes”. A dictionary can’t tell which; only the context can. Choosing the right grammatical role for every word — part-of-speech (POS) tagging — sits underneath speech synthesis, search and plenty of other NLP tasks.

For an individual NLP project I built a POS tagger on a Hidden Markov Model (HMM) and tested it on the Brown corpus. The results were real, and so was the mistake I made along the way — one that’s very easy to repeat.

The model

The diagram at the top of this article shows the idea. The tags (DET, NOUN, VERB, …) are hidden states — we can’t see them. What we see are the words. The model has two tables, and both of them are just counts from a tagged corpus:

Table Question it answers Estimated as
Transition P(tagᵢ │ tagᵢ₋₁) How likely is a NOUN after a DET? count(DET→NOUN) / count(DET)
Emission P(word │ tag) If the tag is NOUN, how likely is the word “count”? count(NOUN, "count") / count(NOUN)
Start P(tag₁) How likely does a sentence start with DET? count(sentences starting with DET) / count(sentences)

For the data I used the Brown corpus from NLTK with the universal tagset (12 tags). It has 57,340 tagged sentences, which I split 80% for training and 20% for testing.

Step 1 — Train by counting

Training an HMM means counting. There is no gradient descent:

from collections import Counter, defaultdict

def train(tagged_sentences):
    start, trans, emit, tag_count = Counter(), defaultdict(Counter), defaultdict(Counter), Counter()
    for sent in tagged_sentences:                       # sent = [("the","DET"), ("count","NOUN"), ...]
        tags = [t for _, t in sent]
        start[tags[0]] += 1
        for (w, t) in sent:
            emit[t][w.lower()] += 1
            tag_count[t] += 1
        for prev, cur in zip(tags, tags[1:]):
            trans[prev][cur] += 1
    return start, trans, emit, tag_count

Step 2 — Decode with Viterbi

Now we need to find the best tag sequence for a new sentence. Trying every combination is impossible: 12 tags over a 20-word sentence is 12²⁰ sequences. The Viterbi algorithm uses dynamic programming instead: for every word and every tag, it keeps only the best path that ends in that tag, then follows the back-pointers at the end:

"count" "the" "votes" NOUN VERB DET Best path: VERB → DET → NOUN — "count" before "the" reads as a verb.
import math

def viterbi(words, tags, start, trans, tag_count, emit_logp):
    words = [w.lower() for w in words]
    n = sum(start.values())
    tr = lambda p, t: math.log((trans[p][t] + 1) / (tag_count[p] + len(tags)))
    # best[i][t] = (log-prob of the best path ending in tag t at word i, back-pointer)
    best = [{t: (math.log((start[t] + 1) / (n + len(tags))) + emit_logp(t, words[0]), None) for t in tags}]
    for i in range(1, len(words)):
        col = {}
        for t in tags:
            p, score = max(((p, best[i-1][p][0] + tr(p, t)) for p in tags), key=lambda x: x[1])
            col[t] = (score + emit_logp(t, words[i]), p)
        best.append(col)
    t = max(best[-1], key=lambda k: best[-1][k][0])   # follow the back-pointers
    path = [t]
    for i in range(len(words) - 1, 0, -1):
        t = best[i][t][1]
        path.append(t)
    return path[::-1]

This runs in O(n × T²): for 20 words and 12 tags, that is under 3,000 steps instead of 12²⁰.

Numerical trap: Always work with log probabilities. Multiplying 20 small probabilities becomes 0.0 in floating point (underflow). Adding their logs doesn’t.

Step 3 — Emission probabilities and the mistake I made

A word that never appeared with a tag in training gets probability 0, and one zero kills every path through it. The textbook fix is add-one (Laplace) smoothing: add 1 to every count. So the obvious first version uses it for emissions too:

def laplace_emit(emit, tag_count, V):
    return lambda t, w: math.log((emit[t][w] + 1) / (tag_count[t] + V))   # V = vocabulary size

Then I compared it with the simplest possible baseline — tag every word with the tag it had most often in training (and NOUN for unknown words). These are the real results on the 232,177 test words:

Model Accuracy Unknown words
Most-frequent-tag baseline 94.61% 60.24%
HMM + Viterbi, Laplace emissions 93.96% ❌ 45.39%

The HMM lost to the baseline. The reason is the unknown words (2.2% of the test words). The vocabulary has 45,153 words, so adding 1 for every word gives each unseen word almost the same tiny probability under every tag. The model has no idea which tag an unknown word probably is.

The fix is to handle two different cases separately:

  1. A word we know, but never saw with this tag → a very small probability.
  2. A word we have never seen at all → estimate how often each tag produces new words. A good estimate is the share of words that appeared only once with that tag (called hapax words). Open classes like NOUN have many of them; closed classes like DET almost none.
def make_emit_logp(emit, tag_count, vocab, k=0.001):
    hapax = Counter(t for t in emit for w, c in emit[t].items() if c == 1)
    def emit_logp(t, w):
        c = emit[t][w]
        if c:          return math.log(c / tag_count[t])          # seen with this tag
        if w in vocab: return math.log(1e-12)                     # known word, never with this tag
        return math.log((hapax[t] + k) / tag_count[t])            # unknown word: how often t makes new words
    return emit_logp

And the result:

Model Accuracy Unknown words
Most-frequent-tag baseline 94.61% 60.24%
HMM + Viterbi, Laplace emissions 93.96% 45.39%
HMM + Viterbi, hapax unknown-word model 96.43% ✅ 62.69%

And of course the sentences from the introduction:

count the votes .      →  count/VERB  the/DET  votes/NOUN  ./.
the count was wrong .  →  the/DET  count/NOUN  was/VERB  wrong/ADJ  ./.

Step 4 — Evaluate honestly

This experiment is a good reminder of three rules worth following for any model:

  1. Always compare with a simple baseline first. Without the baseline, 93.96% would have looked like a good result.
  2. Report unknown words separately. The overall number hides how badly a model handles words it has never seen.
  3. Split by sentence, and never evaluate on sentences the model was trained on.

The real lesson

An HMM is trained by counting and decoded with Viterbi, and it can still tell “count the votes” from “the count was wrong”. But the biggest lesson wasn’t the algorithm — it was the evaluation. Textbook smoothing made the model worse than a one-line baseline, and only a proper unknown-word model fixed it. Hidden states, transition scores and dynamic programming come back again in speech recognition and machine translation, my next two projects. To experiment yourself, the NLTK book chapter on tagging is a great start.