Sam Austinon December 1, 202613 min read

Hidden Markov Models Explained: Viterbi and the Forward Algorithm in Python

Hidden Markov Models Explained: Viterbi and the Forward Algorithm in Python
Contents

Figure 1: Hidden Markov Models Explained: Viterbi and the Forward Algorithm in Python — a trail through snowy woods, where the tracks are the observations and the animal that made them stays hidden

Your friend texts you "just cleaned the whole apartment" and you instantly guess the weather outside is awful. You just ran a hidden Markov model in your head. You saw a behavior and inferred the invisible cause.

I first met HMMs in a speech recognition class, where the professor filled three whiteboards with Greek letters. I understood nothing until I coded the thing in 30 lines. The math finally clicked.

Let me skip the whiteboards and save you the headache.

What Is a Hidden Markov Model?

A hidden Markov model (HMM) describes a system with two layers. The hidden states follow a Markov chain, but you can't see them. The observations depend on those hidden states, and you can see those.

If you read my Markov chain article, you already know the first layer. The new twist is that you never watch the chain itself. You only watch its side effects, like footprints in the snow.

Speech recognition works this way. The hidden states are the words someone says, and the observations are the audio signals your microphone records. The model works backward from sound to words [1].

The Five Ingredients

Every HMM needs the same parts:

  1. Hidden states: what you can't observe (Rainy, Sunny).
  2. Observations: what you can observe (walk, shop, clean).
  3. Start probabilities: how likely each hidden state is on day one.
  4. Transition probabilities: the odds of moving from one hidden state to another.
  5. Emission probabilities: the odds that each hidden state produces each observation.

Emission probabilities make an HMM different from a plain Markov chain. They link the hidden world to the visible one. Each row of every table must sum to 1, or your results will drift into nonsense.

Set Up the Model in Python

We'll use the classic setup: a friend's weather stays hidden, and you only learn what your friend did that day. I picked these numbers myself, so please don't bet money on them.

states = ["Rainy", "Sunny"]

start = {"Rainy": 0.6, "Sunny": 0.4}

trans = {
    "Rainy": {"Rainy": 0.7, "Sunny": 0.3},
    "Sunny": {"Rainy": 0.4, "Sunny": 0.6},
}

emit = {
    "Rainy": {"walk": 0.1, "shop": 0.4, "clean": 0.5},
    "Sunny": {"walk": 0.6, "shop": 0.3, "clean": 0.1},
}

Notice how sensible the emissions look. Your friend cleans on rainy days 50% of the time and walks on sunny days 60% of the time. Now we need to ask the model useful questions.

The Two Questions That Matter

HMMs mainly answer two questions, and each one has its own algorithm:

  1. Evaluation: "How likely is this sequence of observations under my model?" The forward algorithm answers this.
  2. Decoding: "What hidden sequence most likely produced these observations?" The Viterbi algorithm answers this.

A third question, learning, asks how to estimate the probabilities from data. We'll touch on that near the end. First, let's tackle the other two.

The Forward Algorithm

Say your friend walked, then shopped, then cleaned. You want the total probability of that observation sequence. The brute-force method adds up every possible weather sequence, and that gets out of hand fast. With N states and T days, you face N^T paths.

Ever tried to enumerate a million paths by hand? I don't recommend it. The forward algorithm uses dynamic programming to avoid the explosion.

How It Works

At each step, you track alpha: the probability of seeing the observations so far and landing in each state. You build each new alpha from the previous one:

  1. Initialize: multiply each start probability by the emission of the first observation.
  2. Recurse: for each state, sum the previous alphas times the transition probabilities, then multiply by the emission.
  3. Finish: sum the final alphas.

The algorithm runs in time proportional to T × N² instead of N^T. That difference separates "works" from "never finishes."

The Code

def forward(obs):
    alpha = {s: start[s] * emit[s][obs[0]] for s in states}
    for o in obs[1:]:
        alpha = {
            s: sum(alpha[p] * trans[p][s] for p in states) * emit[s][o]
            for s in states
        }
    return sum(alpha.values())

print(forward(["walk", "shop", "clean"]))  # about 0.0336

Let me walk through it by hand so you trust it. After "walk," alpha is 0.06 for Rainy (0.6 × 0.1) and 0.24 for Sunny (0.4 × 0.6). After "shop," those become 0.0552 and 0.0486. After "clean," they become 0.02904 and 0.004572, and the total comes to 0.033612.

The Viterbi Algorithm

Now the fun part. You know what your friend did, and you want the single most likely weather sequence. Viterbi looks almost identical to the forward algorithm, with one swap: it replaces sum with max.

Instead of adding up all the ways to reach a state, Viterbi keeps only the best way. It also remembers which previous state gave that best score, so it can rebuild the path at the end [2].

The Code

def viterbi(obs):
    v = {s: start[s] * emit[s][obs[0]] for s in states}
    paths = {s: [s] for s in states}

    for o in obs[1:]:
        new_v, new_paths = {}, {}
        for s in states:
            prob, prev = max((v[p] * trans[p][s], p) for p in states)
            new_v[s] = prob * emit[s][o]
            new_paths[s] = paths[prev] + [s]
        v, paths = new_v, new_paths

    best = max(states, key=lambda s: v[s])
    return paths[best], v[best]

print(viterbi(["walk", "shop", "clean"]))

The result: Sunny, Rainy, Rainy, with a path probability of about 0.0134. That makes sense. Your friend walked on day one (a sunny-day activity), then the weather turned and stayed rainy for the shopping and cleaning.

A Common Surprise

Look closely and you'll spot something odd. The most likely single path has a probability of 0.0134, but the total probability of the observations equals 0.0336. Those numbers differ because the forward algorithm counts every path, while Viterbi picks only the winner.

FYI, the best path doesn't always match the best state at each individual step. Viterbi optimizes the whole sequence together, which usually gives more coherent answers than choosing the likeliest state day by day.

Forward vs. Viterbi at a Glance

Feature Forward Viterbi
Question answered How likely are these observations? Which hidden path fits best?
Core operation Sum over paths Max over paths
Output One probability A state sequence plus its probability
Typical use Scoring, model comparison Decoding, tagging

IMO, you should learn forward first, because Viterbi then feels like a small edit. Both share the same table-filling structure.

Fix Underflow Before It Bites You

Here's the bug that ate my entire Saturday. Multiply enough small probabilities together and the result shrinks below what floating-point numbers can hold. Your program then returns zero for everything. :/

You have two standard fixes:

  1. Work in log space. Add log-probabilities instead of multiplying probabilities. For Viterbi, this works perfectly because max preserves ordering.
  2. Rescale at each step. In the forward algorithm, normalize alpha after every observation and record the scaling factors.

For the forward algorithm, log space needs the logsumexp trick, since you must sum probabilities. Viterbi only needs max and addition, so it's the easier one to convert.

Learning the Parameters

What if you don't know the probabilities? The Baum-Welch algorithm estimates them from observation sequences [3]. It's a special case of expectation-maximization, and it uses the forward algorithm plus its mirror image, the backward algorithm.

You don't need to code it from scratch. The hmmlearn library handles training and decoding for you [4]. Be warned, though: Baum-Welch finds a local optimum, so you should run it from several random starting points and keep the best result.

Where HMMs Show Up

HMMs power more than you'd expect:

  • Speech recognition decoded audio into words for decades before neural networks took over.
  • Part-of-speech tagging treats tags as hidden states and words as observations.
  • Bioinformatics uses HMMs to find genes and align protein families [5].
  • Finance applies them to detect hidden market regimes, like calm versus volatile periods.
  • Activity recognition infers what someone is doing from phone sensor data.

Modern deep learning beats HMMs on many of these tasks. But HMMs still win when you have little data, need a transparent model, or want something you can debug by reading a table. That is the same trade-off that keeps Bayesian networks useful next to bigger models.

Common Beginner Mistakes

I made every one of these:

  • Mixing up transitions and emissions. One links hidden states to each other, and the other links hidden states to observations.
  • Ignoring underflow. Short test sequences work fine, then long real ones return zeros.
  • Forgetting the backpointers. Viterbi without path tracking gives you a probability but no answer.
  • Assuming the Markov property fits. If tomorrow depends on the last three days, a first-order HMM will struggle.
  • Trusting a single Baum-Welch run. Different starting points give different models.

Best Book to Read

CoverBookDescriptionGet it
Cover of “Speech and Language Processing” Speech and Language Processingby Daniel Jurafsky and James H. Martin the standard textbook on sequence models, with a clear chapter on HMMs, forward-backward and Viterbi that sits right next to the modern neural material [2]. View on Amazon

As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.

Read it after the weather example runs. Seeing the same three tables formalised in notation feels like a translation exercise rather than a new subject, and the book's tagging chapter is the natural sequel to this post.

Wrapping Up

A hidden Markov model pairs an invisible Markov chain with visible observations. The forward algorithm sums over all hidden paths to score a sequence, and the Viterbi algorithm takes the max to find the single best path. Both run in T × N² time, and both fit in about ten lines of Python.

Take the weather example and change the numbers. Make rainy days more persistent, or give your friend a strange cleaning habit, and watch the decoded path shift. Then try a longer observation sequence and add log-space math to survive the underflow.

If your model ever decides it's always sunny, check your transition table first. Mine once insisted on permanent sunshine, and the culprit was a typo, not the climate. :)

Frequently Asked Questions

What is a hidden Markov model in simple terms?

A hidden Markov model pairs an invisible Markov chain with visible observations. The hidden states follow normal transition probabilities, and each state emits observations with its own probabilities, so you see the effects and have to infer the causes.

What is the difference between the forward algorithm and Viterbi?

Both fill the same table. The forward algorithm sums over every possible hidden path to score the observation sequence, while Viterbi takes the maximum to find the single most likely path. Sum gives a likelihood, max gives a decision.

Why does Viterbi return a lower probability than the forward algorithm?

Because they answer different questions. The forward algorithm adds up the probabilities of all paths that produce the observations, while Viterbi reports only the single best path. The best path is part of that total, so its probability is always smaller.

How do I fix underflow in an HMM implementation?

Multiply enough small probabilities and floating point rounds them to zero. Either work in log space, adding log-probabilities instead of multiplying, or rescale alpha after every observation. The forward algorithm needs logsumexp in log space, while Viterbi only needs max and addition.

Are hidden Markov models still used in 2026?

Yes, in narrow and data-poor settings. Speech and part-of-speech tagging have largely moved to neural models, but HMMs remain common in bioinformatics, activity recognition, and financial regime detection, where small data and readable probability tables matter more than raw accuracy.

Sources

  • [1] Lawrence Rabiner, A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition (1989) - the canonical introduction, covering the three canonical problems and the algorithms that solve them: ieeexplore.ieee.org
  • [2] Jurafsky and Martin, Speech and Language Processing (3rd edition draft) - sequence labelling, HMMs, forward-backward and Viterbi in the context of tagging and speech: stanford.edu
  • [3] Rabiner and Juang, An Introduction to Hidden Markov Models (1986) - the shorter IEEE ASSP primer that introduced Baum-Welch training to a generation of engineers: ieeexplore.ieee.org
  • [4] hmmlearn documentation, Tutorial and API reference - working implementations of Gaussian and categorical HMMs, plus decoding and training routines: hmmlearn.readthedocs.io
  • [5] Durbin, Eddy, Krogh and Mitchison, Biological Sequence Analysis (1998) - profile HMMs, the forward-backward algorithm and Viterbi as used in gene finding and alignment: doi.org

What are You Looking For?

esc