Skip to content

Linear, manifold, topic, tensor, and graph representations · Topic and discrete latent representations · REP049 · Model

Hidden Markov model (HMM)

Represent sequential observations using a latent discrete state process, useful for regime detection, symbolic sequences, and temporal segmentation.

Runs in CodeSplash Complete calculation CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Complete calculation
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through ts.hmm. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Represent sequential observations using a latent discrete state process, useful for regime detection, symbolic sequences, and temporal segmentation.

Question / hypotheses

Which latent sequence model best explains observed temporal dependence? This entry specifies an estimation or representation objective; it does not define a universal null hypothesis or p-value.

Architecture / computational structure

A finite latent-state chain emits observations through state-specific distributions; forward–backward supplies inference.

Assumptions

The standard model assumes first-order homogeneous state transitions and emissions conditionally independent given states.

Formula / computational definition

p(z1:T,x1:T)=πz1bz1(x1)∏t=2TAzt−1,ztbzt(xt)p(z_{1:T},x_{1:T})=\pi_{z_1}b_{z_1}(x_1)\prod_{t=2}^TA_{z_{t-1},z_t}b_{z_t}(x_t). The initial vector π\pi, transition matrix AA, and emission distributions bkb_k determine sequence probabilities.

Parameters and notation

Estimated/learned quantities: Initial probabilities, transition matrix, emissions, and state posteriors.

Hyperparameters and design choices: State count, emission family, transition constraints, priors, initialization, and EM or sampling controls. Numerical tolerances control computation; rank, priors, neighborhood scales, and loss weights alter the model where applicable.

Fitting, fine-tuning, and adaptation

Choose state count and emission family with sequence-aware validation. For adaptation, warm-start EM or update sufficient statistics under a defined online method; preserve transition semantics cautiously.

How to use and calibrate

Use held-out sequence likelihood, posterior predictive durations, transition stability, and sequence-aware splits. Distinguish posterior state probabilities, Viterbi paths, and true state uncertainty. Select these choices using the data split appropriate to the intended deployment; retain the final test split for evaluation. Report the actual objective or prediction metric rather than an invented significance level.

Example application

Segment a sensor stream into recurrent regimes. The included synthetic calculation illustrates the computational mechanism; a real analysis must preserve the corresponding sampling unit and missing-data policy.

Interpretation / pitfalls

Watch out

Geometric state durations may be inappropriate; labels can permute and EM can find local optima.

Python and R code examples

The paired examples run the forward recursion for a finite categorical HMM and return sequence likelihood. Full learning adds backward probabilities and parameter updates; R depmixS4 supplies richer emission models.

Scope: Complete forward likelihood for a short categorical HMM with known parameters; long sequences require scaling or logs.

Dependencies/validation: Python: NumPy/SciPy, executed successfully. R: base R, not executed. Run the corresponding shared setup first. These short examples are not evidence of complete package-level validation.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Complete calculation — Complete forward likelihood for a short categorical HMM with known parameters; long sequences require scaling or logs.

Shared setup for this chapter
import numpy as np
from scipy.linalg import eigh
from scipy.spatial.distance import pdist, squareform
rng = np.random.default_rng(17)
X = np.array([[1,2,0,1],[2,1,1,0],[3,4,1,2],[4,3,2,1],
              [5,6,2,3],[6,5,3,2],[7,8,3,4],[8,7,4,3]], dtype=float)
X = X - X.mean(axis=0)
V = X[:, :2] + np.array([0.3,-0.2])
N = np.abs(X) + 0.2
D = squareform(pdist(X))
K = np.exp(-D**2 / 20)
H = np.eye(len(X)) - np.ones((len(X),len(X)))/len(X)
G = np.array([[0,1,1,0],[1,0,1,0],[1,1,0,1],[0,0,1,0]], dtype=float)
P = G / G.sum(axis=1, keepdims=True)
E = np.array([[0.,0.],[1.,0.],[0.,1.],[1.,1.]])
C = np.array([[8.,1.,0.,2.],[1.,7.,2.,0.],[2.,0.,8.,1.]])
theta = np.array([[0.8,0.2],[0.3,0.7],[0.5,0.5]])
phi = np.array([[0.6,0.2,0.1,0.1],[0.1,0.2,0.3,0.4]])
def softmax(a):
    a = np.asarray(a); e = np.exp(a-a.max(axis=-1,keepdims=True))
    return e / e.sum(axis=-1,keepdims=True)

initial=np.array([.6,.4]); transition=np.array([[.8,.2],[.3,.7]])
emission=np.array([[.9,.1],[.2,.8]]); observations=[0,1,1,0]
forward=initial*emission[:,observations[0]]
for observation in observations[1:]: forward=(forward@transition)*emission[:,observation]
likelihood=forward.sum(); assert 0<likelihood<1; print(likelihood)
R

Complete calculation — Complete forward likelihood for a short categorical HMM with known parameters; long sequences require scaling or logs.

Shared setup for this chapter
set.seed(17)
X <- matrix(c(1,2,0,1, 2,1,1,0, 3,4,1,2, 4,3,2,1,
              5,6,2,3, 6,5,3,2, 7,8,3,4, 8,7,4,3), ncol=4, byrow=TRUE)
X <- scale(X, center=TRUE, scale=FALSE)
V <- sweep(X[,1:2], 2, c(0.3,-0.2), "+")
N <- abs(X)+0.2
D <- as.matrix(dist(X)); K <- exp(-D^2/20)
H <- diag(nrow(X))-matrix(1/nrow(X),nrow(X),nrow(X))
G <- matrix(c(0,1,1,0, 1,0,1,0, 1,1,0,1, 0,0,1,0),4,byrow=TRUE)
P <- G/rowSums(G)
E <- matrix(c(0,0,1,0,0,1,1,1),ncol=2,byrow=TRUE)
C <- matrix(c(8,1,0,2,1,7,2,0,2,0,8,1),ncol=4,byrow=TRUE)
theta <- matrix(c(.8,.2,.3,.7,.5,.5),ncol=2,byrow=TRUE)
phi <- matrix(c(.6,.2,.1,.1,.1,.2,.3,.4),ncol=4,byrow=TRUE)
softmax <- function(a) { z <- exp(a-max(a)); z/sum(z) }
pinv <- function(a) { s <- svd(a); keep <- s$d > max(s$d)*1e-10
    s$v[,keep,drop=FALSE] %*% diag(1/s$d[keep],sum(keep)) %*% t(s$u[,keep,drop=FALSE]) }

initial <- c(.6,.4); transition <- matrix(c(.8,.2,.3,.7),2,byrow=TRUE)
emission <- matrix(c(.9,.1,.2,.8),2,byrow=TRUE); observations <- c(1,2,2,1)
forward <- initial*emission[,observations[1]]
for(observation in observations[-1]) forward <- drop(forward%*%transition)*emission[,observation]
likelihood <- sum(forward); stopifnot(likelihood>0,likelihood<1); print(likelihood)

Sources

From the CodeSplash reference, entry REP049.