Further reading — Fitting HMMs in R
This is an extra-material unit following Hidden Markov models. There you built HMMs by hand; today we let R do the heavy lifting on genome-like data. By the end you will be able to:
HMM package via initHMM (states, symbols, \boldsymbol{\pi}, A, B).simHMM and recover its likelihood with forward.viterbi and read it as a predicted CpG-island map.baumWelch.Notation as in Hidden Markov models: transition matrix A, emission matrix B, initial distribution \boldsymbol{\pi}, hidden states \mathbf{z}, observations \mathbf{x}.
Hidden Markov models: an HMM = hidden states + transition matrix A + emission matrix B + initial distribution \boldsymbol{\pi}, with three problems — likelihood (forward), decoding (Viterbi), learning (Baum–Welch).
The CRAN HMM package gives one function for each:
| Task (Hidden Markov models) | HMM function |
|---|---|
| build the model | initHMM |
| generate data | simHMM |
| likelihood P(\mathbf{x}) | forward (and backward) |
| decode best path \mathbf{z}^\* | viterbi |
| learn A, B, \boldsymbol{\pi} | baumWelch |
initHMMThe same 2-state model as in Hidden Markov models. States H (GC-rich), L (normal); symbols the bases.
library(HMM)
states <- c("H", "L")
symbols <- c("A", "C", "G", "T")
startProbs <- c(0.5, 0.5) # pi
transProbs <- matrix(c(0.8, 0.2, # A: rows = from, cols = to
0.3, 0.7),
nrow = 2, byrow = TRUE,
dimnames = list(states, states))
emissionProbs <- matrix(c(0.1, 0.4, 0.4, 0.1, # B: rows = state, cols = base
0.3, 0.2, 0.2, 0.3),
nrow = 2, byrow = TRUE,
dimnames = list(states, symbols))
hmm <- initHMM(States = states, Symbols = symbols,
startProbs = startProbs,
transProbs = transProbs,
emissionProbs = emissionProbs)Each matrix row must sum to 1 — exactly the constraint from Hidden Markov models.
simHMMsimHMM runs the generative story for you and, because it is a simulation, also hands back the true hidden states — a luxury you never get with real data, but perfect for testing.
set.seed(1)
sim <- simHMM(hmm, length = 30)
sim$observation # the emitted bases (this is your "data")
# [1] "G" "C" "C" "G" "A" ...
sim$states # the TRUE hidden path (normally unknown!)
# [1] "H" "H" "H" "H" "L" ...We will pretend we only saw sim$observation, then check whether decoding recovers sim$states.
forwardforward returns a matrix of log forward probabilities, states × position. The likelihood P(\mathbf{x}) is recovered from the last column.
obs <- sim$observation
f <- forward(hmm, obs) # log alpha values, rows = states, cols = positions
# total log-likelihood = log-sum-exp of the final column
logLik <- function(col) {
m <- max(col)
m + log(sum(exp(col - m)))
}
logLik(f[, length(obs)])
# e.g. -39.5 (a log-probability; use logs to remain stable for long sequences)Probabilities of long sequences are vanishingly small, so the package works in logs — this is why your by-hand products from Hidden Markov models shrank so fast.
viterbi: the island mapviterbi returns the single most likely hidden path — one label per base.
path <- viterbi(hmm, obs)
path
# [1] "H" "H" "H" "H" "L" "L" "L" "H" "H" ...
# How well did we recover the truth?
mean(path == sim$states) # fraction of positions correctly decoded, e.g. 0.87
# Read off predicted CpG islands: maximal runs of "H"
rle(path)
# Run Length Encoding
# lengths: int [1:5] 4 3 2 ...
# values : chr [1:5] "H" "L" "H" ...The runs of H are your predicted CpG islands. rle turns the path into segments.
baumWelchSo far we supplied A, B, \boldsymbol{\pi}. The realistic case: only raw sequence, no labels. baumWelch learns the parameters by EM.
# Start from an imperfect, asymmetric guess. Identical state rows would remain
# identical under EM, so they cannot teach the algorithm to distinguish states.
guess <- initHMM(states, symbols,
transProbs = matrix(c(0.5,0.5, 0.5,0.5), 2, byrow=TRUE,
dimnames=list(states,states)),
emissionProbs = matrix(c(0.3,0.2,0.2,0.3,
0.2,0.3,0.3,0.2), 2, byrow=TRUE,
dimnames=list(states,symbols)))
bw <- baumWelch(guess, obs, maxIterations = 100)
bw$hmm$transProbs # learned A; compare its stickiness with the generating model
bw$hmm$emissionProbs # learned B; identify the GC-heavy row (its label can switch)baumWelch returns $hmm (the fitted model) and $difference (convergence trace).
baumWelch is powerful but easy to misuse:
We assumed 2 states (island vs not). In general you must choose the number.
Start simple, add states only if they earn their keep and stay interpretable.
What changes when you move from simHMM data to a real chromosome:
CpG, or k-mers) for sharper islands.forward/viterbi are linear in length, so this is fine — but work in logs (the package does).HMM package = one function per concept from Hidden Markov models: initHMM, simHMM, forward, viterbi, baumWelch.viterbi; the runs of the GC-rich state are your predicted CpG islands.baumWelch — but watch for local optima, label switching, and enough data.That closes the linear-algebra block — from solving systems to chains and hidden chains.
This is the end of the linear-algebra block. The thinking carries forward:
You now have the full toolkit — linear systems, vectors, matrices, eigenvalues, Markov chains, and HMMs — that the rest of the course builds on.