Further reading: not part of the course. This material is not included in the course, but it is relevant if you want to learn more about the topic.

Fitting HMMs in R: finding CpG islands

Further reading — Fitting HMMs in R

Quantitative biology and integrative omics

About this lecture

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:

  • Build an HMM in R with the CRAN HMM package via initHMM (states, symbols, \boldsymbol{\pi}, A, B).
  • Simulate sequence with simHMM and recover its likelihood with forward.
  • Decode the most likely hidden-state path with viterbi and read it as a predicted CpG-island map.
  • Learn the parameters A, B, \boldsymbol{\pi} from unlabelled sequence with baumWelch.
  • Discuss how many states to use and the main pitfalls.

Notation as in Hidden Markov models: transition matrix A, emission matrix B, initial distribution \boldsymbol{\pi}, hidden states \mathbf{z}, observations \mathbf{x}.

Recap and today’s tool

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
install.packages("HMM")   # once
library(HMM)

Building the model with initHMM

The 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.

Simulating sequence with simHMM

simHMM 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.

Likelihood with forward

forward 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.

Decoding with viterbi: the island map

viterbi 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.

Learning with baumWelch

So 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).

Learning can get stuck or swap state labels

baumWelch is powerful but easy to misuse:

  • Local optima. EM climbs to the nearest peak, not the global one. Different starting guesses → different fits. Run several inits, keep the best likelihood.
  • Label switching. Which learned state is “H” is arbitrary — the algorithm may swap them. Interpret by the emission profile (the GC-heavy one is your island state), not by the name.
  • Needs enough data. Short sequences give unstable estimates.
  • Garbage in, garbage out. The fitted states are just clusters; they are “CpG islands” only if you check their emission profile makes biological sense.

Extra states always fit better, so fit cannot choose

We assumed 2 states (island vs not). In general you must choose the number.

  • Let biology guide you first: island vs background is naturally 2; coding / intron / intergenic might want 3+.
  • More states always fit the training data better (higher likelihood) — so raw likelihood cannot pick the number. Penalise complexity with AIC/BIC, or use held-out sequence.
  • More states = more parameters = more data needed and more local optima.

Start simple, add states only if they earn their keep and stay interpretable.

The same tools scale to real genomes

What changes when you move from simHMM data to a real chromosome:

  • Symbols. Use the 4 bases, or richer features (dinucleotides like CpG, or k-mers) for sharper islands.
  • Scale. Real sequences are megabases long; forward/viterbi are linear in length, so this is fine — but work in logs (the package does).
  • Validation. Compare decoded islands against annotated CpG islands (e.g. UCSC tracks) to judge the model.
  • Beyond 2 states. Gene-finding HMMs (e.g. GENSCAN-style) use many states for exons, introns, splice sites — same machinery, bigger A and B.

Summary

  • The CRAN HMM package = one function per concept from Hidden Markov models: initHMM, simHMM, forward, viterbi, baumWelch.
  • Decode with viterbi; the runs of the GC-rich state are your predicted CpG islands.
  • Learn parameters from unlabelled sequence with baumWelch — but watch for local optima, label switching, and enough data.
  • Choosing the number of states is model selection: let biology lead, use AIC/BIC or held-out data, keep states interpretable.

That closes the linear-algebra block — from solving systems to chains and hidden chains.

Where this leads

This is the end of the linear-algebra block. The thinking carries forward:

  • Week 2 — PCA. From discrete hidden states to continuous latent directions: PCA finds the axes (eigenvectors!) that explain variation in omics data — the eigen-ideas from Eigenvalues & eigenvectors and Eigenvalues in R return.
  • Bayesian statistics. HMMs were our first latent-variable models with proper inference; the Bayesian block generalises “infer the hidden given the observed” with priors and full posteriors.
  • Single-cell analysis. Segmenting and annotating cells echoes today’s segmenting and annotating a genome.

You now have the full toolkit — linear systems, vectors, matrices, eigenvalues, Markov chains, and HMMs — that the rest of the course builds on.