Navigation

Introduction to AI

Machine Learning

Deep Learning

NLP & LLMs

Computer Vision

Generative AI

Reinforcement Learning

AI Ethics & Governance

Tools & Frameworks

General

Hidden Markov Models - Sequence Modeling with Latent States

A Hidden Markov Model (HMM) models a sequence of observations generated by an underlying sequence of hidden states that follow a Markov chain. HMMs were central to speech recognition, part-of-speech tagging, and bioinformatics before deep learning.

Components

  • States S = {s1, ..., sN} (hidden)
  • Transition matrix A[i][j] = P(state j at t+1 | state i at t)
  • Emission distribution B[i](o) = P(observation o | state i)
  • Initial distribution pi

Two assumptions: the next state depends only on the current state (Markov property), and each observation depends only on the current state.

The Three Classic Problems

ProblemQuestionAlgorithm
EvaluationHow likely is this observation sequence?Forward algorithm
DecodingWhat is the most probable hidden state sequence?Viterbi
LearningWhich parameters best explain the data?Baum-Welch (EM)

Forward Algorithm

Dynamic programming over time avoids enumerating all N^T state paths:

alpha_1(i) = pi_i * B_i(o_1)
alpha_t+1(j) = [ sum_i alpha_t(i) * A[i][j] ] * B_j(o_t+1)
P(O) = sum_i alpha_T(i)

Viterbi Decoding

Replace the sum with a max and store backpointers:

import numpy as np

def viterbi(obs, pi, A, B):
    N, T = len(pi), len(obs)
    delta = np.zeros((T, N)); back = np.zeros((T, N), dtype=int)
    delta[0] = pi * B[:, obs[0]]
    for t in range(1, T):
        scores = delta[t-1][:, None] * A          # (N, N)
        back[t] = scores.argmax(axis=0)
        delta[t] = scores.max(axis=0) * B[:, obs[t]]
    path = [delta[-1].argmax()]
    for t in range(T-1, 0, -1):
        path.append(back[t][path[-1]])
    return path[::-1]

For long sequences, work in log space to avoid underflow.

Library Usage

from hmmlearn.hmm import GaussianHMM

model = GaussianHMM(n_components=3, covariance_type="diag", n_iter=100).fit(X)
states = model.predict(X)

Limitations

HMMs have limited memory (one step), assume conditionally independent observations, and require choosing the number of states. Recurrent networks and transformers model long-range dependencies far better, but HMMs remain useful for small data, interpretable regime detection, and as components in structured pipelines.