Hidden Markov models

Inferring what we can’t see

Previously

We learned to make our work reproducible, with git and pixi

Today, back to probabilistic models and algorithms!

How can we learn about things we can’t see, from the clues they leave behind?

Hidden states

What we see vs. what we want to know

What we see What’s hidden
A genome: ...ACGGTCAGGTAAG... Where the genes, exons, and regulatory regions are
A protein sequence Which family it belongs to, and which parts are its domains
A GPS track of a bison Whether it’s resting, foraging, or traveling
A sound recording The words being spoken
A noisy signal to your phone The bits that were sent

A hidden Markov model (HMM) handles all of these, with the same model and the same algorithms

The occasionally dishonest casino1

  • A casino usually uses a fair die
  • Every now and then, it secretly switches to a loaded die that rolls a 6 half of the time
  • After a while, it switches back

Where was the casino cheating?

The occasionally dishonest casino

Red: loaded die; blue: fair die

  • Long runs with lots of sixes are easy to spot
  • Short runs, and exactly where runs start and end, are hard

An HMM has three parts

  1. Hidden states: Fair or Loaded
  2. Transition probabilities: the chance of each state at the next roll, given the state now
  3. Emission probabilities: the chance of each roll, given the state

Plus start probabilities for the first roll

The hidden states are a Markov chain, just like a site in our substitution models, but along a sequence instead of through time; we just can’t see it!

The probability of the rolls and a path

A path is a sequence of hidden states, one per roll

\[ P(\texttt{266}, \text{Fair Loaded Loaded}) = \underbrace{0.5}_{\text{start F}} \underbrace{\tfrac{1}{6}}_{\text{F rolls 2}} \underbrace{0.05}_{\text{F}\rightarrow\text{L}} \underbrace{0.5}_{\text{L rolls 6}} \underbrace{0.9}_{\text{L}\rightarrow\text{L}} \underbrace{0.5}_{\text{L rolls 6}} \approx 0.00094 \]

With many rolls, this gets tiny, so we use logs (just like tree likelihoods):

\[ \log P(x, \pi) = \log s_{\pi_1} + \log e_{\pi_1}(x_1) + \sum_{i = 2}^{n} \Big[ \log a_{\pi_{i - 1} \pi_i} + \log e_{\pi_i}(x_i) \Big] \]

Finding the best path

How many paths are there?

Each roll could be fair or loaded

Rolls Possible paths
3 \(2^3 = 8\)
30 \(2^{30} \approx 10^9\)
300 \(2^{300} \approx 2 \times 10^{90}\)
1,000,000 bases of DNA \(2^{1{,}000{,}000}\)

More paths than atoms in the universe (\(\approx 10^{80}\)), just like trees; we can’t try them all!

The Viterbi algorithm1

Key idea: The best path that ends in state \(k\) at roll \(i\) came through some state \(j\) at roll \(i - 1\), along the best path that ends in \(j\)

So, we only need the best path ending in each state, at each roll

We fill in a table with one row per state and one column per roll

  1. First column: \(V_k(1) = \log s_k + \log e_k(x_1)\)
  2. Each later column: \(V_k(i) = \max_j \big[ V_j(i - 1) + \log a_{jk} \big] + \log e_k(x_i)\), and remember the best \(j\) (a pointer)
  3. Traceback: Start at the best score in the last column, and follow the pointers backward

Viterbi, step by step

Haven’t we seen this before?

Fills in a table… At each cell… Then…
Alignment one cell per pair of positions takes the best of 3 moves traces back
Viterbi one cell per state and position takes the best previous state traces back
Pruning one row per node adds up over the hidden bases of each child averages at the root
Forward algorithm one cell per state and position adds up over previous states sums the last column

All four are dynamic programming: Solve a big problem by building up answers to small ones, and reuse them

Most probable ≠ true

For the 300 rolls in the exercise:

Path Log probability
Viterbi \(-543.1\)
Always fair \(-553.6\)
The true path \(-583.5\)
  • The true path switches dice many times, and each switch is improbable
  • The casino doesn’t always do the most probable thing!
  • Still, the Viterbi path has the right die for 85% of the rolls (“always fair”: 66%)

How different are the dice?

We can only recover hidden states if they emit different things

CpG islands

CpG depletion

  • A CpG is a C followed by a G on the same strand
  • In vertebrates, most CpG C’s are methylated, and methylated C’s easily mutate to T
CpGs in 2 Mb of human chromosome 19 Observed/expected
Whole stretch 0.45
Background 0.38
CpG islands 0.78

CpG islands: stretches of a few hundred to a few thousand bases where CpGs are not depleted, often where genes start (Gardiner-Garden and Frommer 1987)

Training an HMM by counting

When we have data with known hidden states, we can train an HMM by just counting:

  • \(e_k(s) = \dfrac{\text{times state } k \text{ emitted } s}{\text{positions in state } k}\)
  • \(a_{jk} = \dfrac{\text{times state } j \text{ was followed by } k}{\text{times state } j \text{ was followed by anything}}\)
  • Train on the first million bases, test on the second million
  • Start every count at 1 (a pseudocount), so no probability is 0

One base at a time, or pairs?

One base Pairs
Accuracy 0.921 0.959
(Everything background) 0.928 0.928
UCSC islands found (of 109) 65 70
HMM islands that are real 60 of 75 72 of 85
  • One base at a time: the HMM can only see GC content
  • Pairs: within each hidden state, the bases follow a Markov chain, \(P(\text{base} \mid \text{previous base})\), so it can see CpGs
  • \(P(\texttt{G} \mid \texttt{C})\): 0.11 in the background, 0.28 in islands

We use the same viterbi function as the casino! And 27 of 29 genes start near an HMM island.

HMMs are everywhere

HMMs in genomics

Problem Hidden states Observations
Gene finding (GENSCAN) (Burge and Karlin 1997) exon, intron, intergenic, … bases
Protein families (Pfam, HMMER) (Krogh et al. 1994; Eddy 2011) match, insert, delete amino acids
Conserved elements (phastCons) (Siepel et al. 2005) conserved or not alignment columns
Chromatin states (ChromHMM) (Ernst and Kellis 2012) promoter, enhancer, … histone marks
Population history (PSMC) (Li and Durbin 2011) time to common ancestor heterozygous sites

The first HMM for DNA split sequences into stretches with different base compositions (Churchill 1989), a lot like our CpG islands

Beyond genomics

Problem Hidden states Observations
Animal movement (Langrock et al. 2012) resting, foraging, traveling step lengths, turning angles
Speech recognition (Rabiner 1989) sounds, words audio
Digital communication (Viterbi 1967) the bits that were sent a noisy signal

Viterbi invented his algorithm to decode noisy digital signals, like those sent to cell phones and from spacecraft; we’re using it to read genomes!

Phylo-HMMs: HMMs meet pruning

  • Hidden states: Conserved (evolving slowly) or Not
  • Emission probability of a column = the probability of the column on the tree, from the pruning algorithm, with short branches in the conserved state (Siepel et al. 2005)

What about genes?

  • HBB (β-globin): gray: all 87 GTs and 81 AGs; red: the 2 real starts and 2 real ends of introns
  • A simple exon/intron HMM did worse than calling everything intron on chromosome 19 (65% vs. 78%)
  • Real gene finders use codon models, separate parameters for GC-rich and GC-poor DNA (Burge and Karlin 1997), and models of splice sites

Summary

  • An HMM has hidden states that follow a Markov chain (transitions), and emit what we can see (emissions)
  • The Viterbi algorithm finds the most probable path of hidden states by dynamic programming: fill in a table, then trace back
  • Max ↔︎ sum: Viterbi is like alignment; the forward algorithm is like pruning
  • The most probable path isn’t the true path, and we can only recover hidden states that emit different things
  • When we have data with known states, we can train an HMM by counting
  • The same code finds loaded dice, CpG islands, genes, protein domains, conserved elements, …

In the exercise

  1. simulate_hmm: Simulate a night at the casino
  2. log_joint_probability: How probable are the rolls and a path?
  3. viterbi_step and viterbi: Catch the casino cheating
  4. plot_paths: Plot the true and Viterbi paths
  5. train_hmm: Learn an HMM by counting, and find CpG islands in a human chromosome

Watch for

How many sixes in a row does it take to convince an HMM the die is loaded?

Exercise

  1. Log into molab
  2. Open the exercise in molab
  3. Click “Fork” button

References

Burge, Chris, and Samuel Karlin. 1997. “Prediction of Complete Gene Structures in Human Genomic DNA.” Journal of Molecular Biology 268 (1): 78–94. https://doi.org/10.1006/jmbi.1997.0951.
Churchill, Gary A. 1989. “Stochastic Models for Heterogeneous DNA Sequences.” Bulletin of Mathematical Biology 51 (1): 79–94. https://doi.org/10.1007/BF02458837.
Durbin, Richard, Sean R. Eddy, Anders Krogh, and Graeme Mitchison. 1998. Biological Sequence Analysis: Probabilistic Models of Proteins and Nucleic Acids. Cambridge University Press.
Eddy, Sean R. 2011. “Accelerated Profile HMM Searches.” PLoS Computational Biology 7 (10): e1002195. https://doi.org/10.1371/journal.pcbi.1002195.
Ernst, Jason, and Manolis Kellis. 2012. “ChromHMM: Automating Chromatin-State Discovery and Characterization.” Nature Methods 9 (3): 215–16. https://doi.org/10.1038/nmeth.1906.
Gardiner-Garden, M., and M. Frommer. 1987. “CpG Islands in Vertebrate Genomes.” Journal of Molecular Biology 196 (2): 261–82. https://doi.org/10.1016/0022-2836(87)90689-9.
Krogh, Anders, Michael Brown, I. Saira Mian, Kimmen Sjölander, and David Haussler. 1994. “Hidden Markov Models in Computational Biology: Applications to Protein Modeling.” Journal of Molecular Biology 235 (5): 1501–31. https://doi.org/10.1006/jmbi.1994.1104.
Langrock, Roland, Ruth King, Jason Matthiopoulos, Len Thomas, Daniel Fortin, and Juan M. Morales. 2012. “Flexible and Practical Modeling of Animal Telemetry Data: Hidden Markov Models and Extensions.” Ecology 93 (11): 2336–42. https://doi.org/10.1890/11-2241.1.
Li, Heng, and Richard Durbin. 2011. “Inference of Human Population History from Individual Whole-Genome Sequences.” Nature 475 (7357): 493–96. https://doi.org/10.1038/nature10231.
Rabiner, Lawrence R. 1989. “A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition.” Proceedings of the IEEE 77 (2): 257–86. https://doi.org/10.1109/5.18626.
Siepel, Adam, Gill Bejerano, Jakob S. Pedersen, et al. 2005. “Evolutionarily Conserved Elements in Vertebrate, Insect, Worm, and Yeast Genomes.” Genome Research 15 (8): 1034–50. https://doi.org/10.1101/gr.3715005.
Viterbi, Andrew J. 1967. “Error Bounds for Convolutional Codes and an Asymptotically Optimum Decoding Algorithm.” IEEE Transactions on Information Theory 13 (2): 260–69. https://doi.org/10.1109/TIT.1967.1054010.

Acknowledgements

I drafted and iterated on these slides in collaboration with Anthropic’s Claude (Opus 5.5 model).