A patient visits the clinic at weeks 0, 3, 19 and 24. At week 12 nobody looks. The last reading says stage 3 has a 6% chance. A CT-HMM lets the hidden stage drift for the nine silent weeks and says 52%.
Pick what the belief may use, then drag the week. Watch the coloured band between visits. Then we build, piece by piece, the rates, the noisy reading, the gap, the filter, the smoother, the decoder and the learner.
You need a continuous-time Markov chain (a rate matrix Q and P(Δt) = eQΔt; see Continuous-Time Markov Chains) and a little Python. A discrete HMM helps but is not needed.
An illustrative patient. Rates 0.2 and 0.1 per week, the reading table of Chapter 2, readings normal, borderline, borderline, abnormal. We made up the hidden path so you can grade the belief; the belief never sees it.
Chapter 0
See two clocks that never tick together, and why a grid fits neither
A kidney patient moves through three stages: mild, moderate and failure. You never see the stage. You see a blood test, and only on the days the patient comes in: week 0, week 3, week 19, week 24.
The disease has its own clock. It changes stage at any moment, often in the middle of a long silence. The clinic has a second clock, set by when the patient shows up. You need a model that reasons from one clock to the other.
The top line is the hidden stage. Pink dots are visits. Press New patient a few times, then turn on the weekly grid.
Illustrative patients from the rates of Chapter 1 (0.2 and 0.1 per week). Visits fall on half weeks, 1 to 12 weeks apart.
A discrete HMM uses one transition table for one fixed step, say a week. Count what a grid costs on the story's 24 weeks. A daily grid has 7 × 24 = 168 cells. Four cells hold a reading. The other 164, or 98%, are empty steps the model must still march through.
A weekly grid is cheaper but wrong in another way: a visit on day 3 of a week has no cell. No step size fits both a one-day follow-up and a year of silence. The fix is to drop the grid. One rate matrix gives a table for any gap, so the model does one step per real gap.
Symptom: a model that carries the last reading forward says a patient seen 16 weeks ago has not changed.
Measure: compare its belief with the stage at the next visit, sorted by gap length. The error grows with the gap.
Fix: let the belief drift by the real gap. That is Chapter 3.
Chapter 1
Turn one rate matrix into the right transition table for any gap length
The hidden stage follows a continuous-time Markov chain: it stays in a stage for a random time, then jumps. The CTMC lesson derives everything here. We carry forward one object and one operation.
The object is the generator Q. Its off-diagonal entry qij is the rate of jumps from stage i to stage j, per week. Its diagonal entry is minus the holding rate qi, the total rate of leaving i, so each row sums to zero. Our patient has q12 = 0.2, q23 = 0.1, and stage 3 is absorbing: its row is all zeros.
The operation answers: if the patient is in stage i now, what is the chance of stage j after a gap of Δt weeks? Call that table P(Δt).
P of delta-t equals e to the Q delta-t.
Multiply Q by the gap Δt. Take the matrix exponential. Read row i to get where a patient in stage i will be.
From stage 1, the chance to still be in stage 1 is e−0.2Δt. After 3 weeks the row is 0.549, 0.384, 0.067. After 16 weeks it is 0.041, 0.322, 0.637. Same Q, a different table.
Each row is a starting stage. Drag the gap. Then switch on the element-wise mistake and watch the row sums.
Rates 0.2 and 0.1 per week, an illustrative choice. The page computes eQΔt by scaling and squaring a Taylor series.
Symptom: transition “probabilities” above 1, or rows that do not sum to 1.
Measure: check every row sum of P(Δt). At Δt = 5, e of each entry gives row 1 the values 0.368, 2.718 and 1.
Fix: call a matrix exponential (scipy.linalg.expm), never numpy.exp.
Chapter 2
Turn one blood test into a belief over the three stages
At each visit the test gives one of three readings: normal, borderline or abnormal. A moderate patient reads borderline most of the time, but not always. The emission table B holds the chance of each reading in each stage.
| Stage | normal | borderline | abnormal |
|---|---|---|---|
| 1 mild | 0.70 | 0.25 | 0.05 |
| 2 moderate | 0.20 | 0.60 | 0.20 |
| 3 failure | 0.05 | 0.30 | 0.65 |
The reading depends only on the stage at that moment. It does not depend on the gap or on past stages. This split is the whole model: the gap acts only on the stage, and the reading acts only on the belief at the visit.
Call the belief just before a reading α−k, three numbers that sum to 1. Call the chance of reading o in stage j bj(o), one entry of B. Bayes' rule gives the belief after the reading.
Alpha-k of j equals alpha-minus-k of j, times b-j of o-k, divided by c-k.
Multiply each stage's belief by how well that stage explains the reading. Add the three products to get ck. Divide each product by ck.
With an even belief of 1/3 each and a borderline reading: products 0.083, 0.200, 0.100, so ck = 0.383. The belief becomes 0.217, 0.522, 0.261.
Pick a starting belief. Press a reading to multiply by its column of B. Press the same reading again: no time passes between presses.
The reading table above is illustrative. Ghost bars show the belief before the last reading.
Symptom: a belief whose three numbers do not sum to 1.
Measure: sum the belief after every update.
Fix: divide by ck. Keep ck: Chapter 4 turns it into the likelihood.
Chapter 3
Let the belief drift across a real gap with one matrix product
The patient leaves the clinic with a belief. Nobody looks for five weeks. During that time the stage can move, and the belief must move with it. A long gap blurs the belief more than a short one.
Call the belief after visit k−1 αk−1, a row of three numbers. Call the gap to the next visit Δtk. The belief just before visit k is α−k.
Alpha-minus-k equals alpha-k-minus-one times P of delta-t-k.
For each stage j, add up the belief in every stage i times the chance to go from i to j in Δtk weeks. That sum is the new belief in j.
After a normal reading the belief is 0.945, 0.051, 0.004. Across 5 weeks: stage 2 gets 0.945 × 0.477 + 0.051 × 0.607 = 0.482. The full row is 0.348, 0.482, 0.170.
Left is the belief after a visit. Right is the belief before the next one. Band widths are the flows from stage to stage. Drag the gap.
Rates 0.2 and 0.1 per week (illustrative). The flow from i to j is α(i) times row i, column j of P(Δt).
Two checks keep the predict step honest. The belief still sums to 1, because every row of P(Δt) sums to 1. And with Δt = 0 nothing moves, because e0 is the identity.
Symptom: the belief at a visit after a year of silence is as sharp as after a week.
Measure: print the predicted belief for two gaps of different length. They must differ.
Fix: pass each visit's own gap into eQΔt. The Code Lab below starts with the identity; replace it.
Chapter 4
Alternate predict and update along the visits, and collect the likelihood on the way
Three visits: normal at week 0, borderline at week 5, abnormal at week 7. The gaps are 5 and 2 weeks. The forward algorithm repeats two moves, visit after visit.
Press Step. Each visit shows the prediction (outline) and the update (fill). Drag the first gap and step again.
Illustrative rates and reading table. With a 5 week gap the numbers match the table below and the Code Lab.
Each ck is the chance of reading k given the readings before it. Their product is the chance of all the readings, the likelihood L. A product of many small numbers underflows, so we add logs.
Log L equals the sum over k of log c-k.
At each update, keep the normalizer ck you divided by. Take its log. Add the logs over all visits.
c0 = 0.593, c1 = 0.427, c2 = 0.292. log L = −0.523 − 0.851 − 1.232 = −2.606.
| Visit | Predicted α− | Reading | Updated α | ck |
|---|---|---|---|---|
| week 0 | prior 0.80, 0.15, 0.05 | normal | 0.945, 0.051, 0.004 | 0.593 |
| week 5 | 0.348, 0.482, 0.170 | borderline | 0.204, 0.677, 0.120 | 0.427 |
| week 7 | 0.136, 0.615, 0.249 | abnormal | 0.023, 0.421, 0.555 | 0.292 |
Symptom: the belief turns into zeros or NaN after a few hundred visits.
Measure: if ck is near 0.4, then 0.4800 ≈ 10−318, below the smallest normal double.
Fix: divide by ck at every visit and add log ck.
Chapter 5
Carry later readings backward, and read the belief at any moment between visits
Take two stages, Healthy and Diseased, with qHD = 0.1 per week and no way back. A test reads “looks Healthy” or “looks Diseased” and is right 90% of the time. At week 0 it says Healthy. At week 10 it says Diseased. What was the stage at week 5?
The filter only knows week 0, so it leans Healthy. But the week 10 reading is evidence about week 5 too. The backward message βk(i) carries it: the chance of all later readings, if the stage at visit k is i. The smoothed belief γk is αk times βk, then divided by its sum.
Beta-k equals P of delta-t-k-plus-one, times b of o-k-plus-one entry by entry with beta-k-plus-one.
Score each stage at the next visit by its reading and its own β. Pull those scores back across the gap with P(Δtk+1).
With β1 = 1, 1 and the Diseased reading column 0.1, 0.9: β0(H) = 0.368 × 0.1 + 0.632 × 0.9 = 0.605, and β0(D) = 0.9.
Between visits the same parts apply at a moment τ weeks after visit k, with the next visit Δtk+1 weeks later. Drift the past forward by τ. Pull the future back by the rest of the gap.
Gamma of tau is proportional to alpha-k times P of tau, entry by entry with P of the rest of the gap, times the next reading's column times beta-k-plus-one.
Compute the past part and the future part for each stage. Multiply them stage by stage. Divide by the sum.
At week 5 the past part is 0.599, 0.401 and the future part is 0.415, 0.9. Products 0.248 and 0.361, so γ(5) = 0.408 Healthy, 0.592 Diseased.
Blue uses week 0 only. Yellow uses both visits. Change the week 10 reading, then drag the moment.
Illustrative toy: prior 0.9 Healthy, a test that is right 90% of the time, qHD = 0.1 per week.
Chapter 6
Find the single best sequence of stages at the visits, and see why it can disagree with the smoother
A doctor wants one story: “mild, then moderate, then moderate”. The smoother gives a belief at each visit, not a story. The Viterbi algorithm finds the one sequence of stages at the visits with the highest joint chance.
Call δk(j) the chance of the best sequence that ends in stage j at visit k, together with the readings so far. It keeps a max where the filter keeps a sum.
Delta-k of j equals the max over i of delta-k-minus-one of i times P-i-j of delta-t-k, times b-j of o-k.
For each stage now, try every stage before it. Keep the best product and remember where it came from. At the end, start from the best final stage and follow the back-pointers.
The Chapter 4 visits. δ0 = 0.56, 0.03, 0.0025. δ1(2) = 0.56 × 0.477 × 0.6 = 0.160. At week 7, δ2(2) = 0.160 × 0.819 × 0.2 = 0.0263 beats δ2(3) = 0.160 × 0.181 × 0.65 = 0.0189.
Each circle is a stage at a visit, sized by δ. Switch between the best path and the best stage at each visit. Then drag the first gap.
Readings normal, borderline, abnormal; second gap 2 weeks; illustrative rates and reading table.
At week 7 the smoother gives stage 3 the most belief, 0.555. The best path still ends in stage 2. Paths into stage 3 must make a second jump in two weeks, and the best path weighs the whole story at once. The best path holds 0.0263 / 0.0738, or 36%, of all the probability.
Chapter 7
Run the whole model on a patient you generate, and break it with sparse visits and bad tests
Now everything runs at once. The device draws a hidden patient over 40 weeks. It places visits, draws a noisy reading at each, and runs the forward and backward passes. Then it paints the smoothed belief at every moment, and the Viterbi stages at the visits.
Top: the hidden truth. Middle: the readings and the Viterbi stage (ring) at each visit. Bottom: the smoothed belief. Move the sliders, then press New patient.
Illustrative. Rates 0.2 and 0.1 per week. A test of accuracy a names the right stage with chance a and each wrong stage with chance (1 − a)/2. Agreement is the share of the 40 weeks where the smoothed belief's top stage equals the hidden stage.
Three things to try. Make visits sparse: the band widens in long gaps and pinches at visits. Make the test poor: the band blurs even at visits. Make visits dense and tests sharp: the band hugs the truth, and agreement passes 90%.
Look at where the model is wrong. It is wrong just after a hidden jump, until a visit reveals it. No model can see a jump before any reading of it. The band shows that doubt instead of hiding it.
Chapter 8
Estimate the rates with EM, using expected jumps and expected time in each stage
So far we knew Q. In practice you have readings from many patients and must learn the rates. If you saw every jump, the answer would be a count over a time: a rate is jumps per week spent in the stage. We never see the jumps, so we use their expected values. That is EM (expectation maximization).
Q-hat-i-j equals the expected N-i-j divided by the expected T-i.
Add up the expected jumps from i to j. Add up the expected weeks in i. Divide.
With made-up totals: 40 expected jumps from stage 1 to 2 over 230 expected weeks in stage 1 give q̂12 = 40 / 230 = 0.174 per week.
Inside one gap, the expected values need an integral over the moment of the jump. Van Loan's trick gets it from one bigger matrix exponential. Put Q on both diagonal blocks and a marker matrix E in the top-right block, with a single 1 at (i, j).
The top-right block of e to the block matrix Q, E, zero, Q times delta-t equals the integral from zero to delta-t of e to the Q-s, times E, times e to the Q times delta-t minus s, d-s.
Build the block matrix, multiply by Δt, exponentiate, read the corner. Entry (a, b) times qij, divided by Pab(Δt), is the expected i→j jumps for a gap that starts in a and ends in b. With E at (i, i), entry (a, b) divided by Pab(Δt) is the expected weeks in i.
Healthy to Diseased, q = 0.08, Δt = 10. The corner gives 6.883. Times 0.08 is 0.551, which equals PHD(10), so a gap that ends Diseased holds exactly one jump.
EM starts both rates at 0.5. Press Run. Dashed lines are the true rates; red dots are the endpoint-counting shortcut.
Simulated patients from rates 0.2 and 0.1, five visits each, 1 to 12 weeks apart, the Chapter 2 test. EM learns only the two rates; B and the prior stay fixed. The shortcut gets the true stage at every visit and still misses.
On 200 patients EM moves from 0.5 and 0.5 to 0.173 and 0.089 in about 40 steps. log L climbs from −1,038 to −944.7. A direct optimizer lands within 0.001 of the same rates. The gap to 0.2 and 0.1 is sampling noise; 800 patients shrink it. The shortcut, endpoint changes over gap weeks, gives 0.096 and 0.057 even with the true stages. It counts a whole gap as time in the start stage and misses jumps inside the gap.
Chapter 9
Spot the traps that fit the data well and still give a wrong Q
A CT-HMM rarely fails loudly. A wrong model can fit the readings well. Here is the sharpest case. Model A goes straight to failure at rate 0.1 per week. Model B passes through a hidden middle stage, with two steps at rate 0.175 each. Both put 86.5% of patients in failure at week 20.
Solid is model A, dashed is model B. Visits at weeks 0 and 20 cannot tell them apart. Drag the extra visit.
Illustrative models, matched at week 20: 1 − e−2 = 0.865 for A, and 1 − e−3.505(1 + 3.505) = 0.865 for B.
With visits only at 0 and 20, both models give the readings the same likelihood. The data cannot choose: Q is not identifiable from this schedule. A visit at week 5 separates them, 39% against 22%. The schedule decides what you can learn.
| Trap | Symptom | Fix |
|---|---|---|
| Sparse schedule | two different Q fit equally well | more or better-placed visits, a prior on Q, a fixed structure |
| Stiff rates | rates 5 and 0.01: (I + QΔt) for one week gives a “probability” of −4 | a real expm (scaling and squaring), never a crude step |
| Absorbing stage | readings after failure teach nothing about the rates | expect it; report how many patients carry the estimate |
| Memoryless stays | real stage durations are not exponential | split a stage into sub-stages, or use a semi-Markov model |
| Telling visit times | sick patients come in more often | model the visit process too; the CT-HMM assumes the timing says nothing |
Symptom: a fitted Q that changes a lot between EM runs from different starts.
Measure: run EM from several starts and refit on bootstrap samples of patients. Look at the spread of each rate.
Fix: report the spread, add visits where the models disagree, or constrain Q.
Chapter 10
Keep the terms, the numbers, the code and the sources in one place
A CT-HMM is a discrete HMM whose transition table is eQΔt, recomputed for each real gap. Filtering, smoothing and decoding keep their discrete shape. Learning swaps counted transitions for expected jumps and expected time, from Van Loan's block matrix. On an even grid of step h, eQh is one fixed table, so the discrete HMM is the special case.
| Term | What it is | Number on this page |
|---|---|---|
| Q, qij, qi | generator, rate i→j, holding rate | q12 0.2, q23 0.1 per week |
| P(Δt) = eQΔt | transition table for one gap | row 1 at 5 wk: 0.368, 0.477, 0.155 |
| B, bj(o) | reading table | borderline column 0.25, 0.60, 0.30 |
| αk, ck | filtered belief, normalizer | week 7: 0.023, 0.421, 0.555 |
| log L | sum of log ck | −2.606 |
| βk, γ | backward message, smoothed belief | week 5 toy: 0.408 Healthy |
| δk(j) | best-path score | path 1, 2, 2 with 0.0263 |
| Nij, Ti | jumps, time in stage | EM on 200 patients: 0.173, 0.089 |
pythonimport numpy as np from scipy.linalg import expm def forward_backward(Q, B, pi, obs, gaps): # obs: K ints, gaps: K floats (gaps[0] unused) K, N = len(obs), len(pi) P = [None] + [expm(Q * g) for g in gaps[1:]] # one table per real gap a = pi * B[:, obs[0]]; c = [a.sum()]; al = [a / c[0]] for k in range(1, K): a = (al[-1] @ P[k]) * B[:, obs[k]] # predict, then update c.append(a.sum()); al.append(a / c[-1]) be = [np.ones(N)] * K for k in range(K - 2, -1, -1): be[k] = P[k + 1] @ (B[:, obs[k + 1]] * be[k + 1]) / c[k + 1] gamma = [x * y / (x * y).sum() for x, y in zip(al, be)] return al, gamma, np.log(c).sum() # log L = -2.606 on the Chapter 4 visits def van_loan(Q, E, dt): # integral of e^(Qs) E e^(Q(dt-s)) ds n = len(Q); A = np.block([[Q, E], [np.zeros((n, n)), Q]]) return expm(A * dt)[:n, n:]
Liu, Li, Li, Song and Rehg, Efficient Learning of Continuous-Time Hidden Markov Models for Disease Progression (NIPS 2015), build EM for CT-HMMs. They compare three ways to get the expected statistics: Van Loan's block matrix (Expm), uniformization (Unif) and eigendecomposition (Eigen). On a 105-state glaucoma model, Soft Expm took 18 minutes per iteration, Soft Unif over 105, and Eigen failed because the Q matrices were often not diagonalizable. They also fit a 277-state Alzheimer's model.
Van Loan, “Computing integrals involving the matrix exponential”, IEEE Transactions on Automatic Control (1978), gives the block-matrix identity. Jackson's msm package for R (Journal of Statistical Software, 2011) fits these models to panel data, including hidden Markov models for misclassified stages. The kidney patient, the rates, the reading table and every simulated patient on this page are illustrative.
Now press Present or Teach and explain from memory: the generator, eQΔt, the update, the predict step, the backward pass, the best path and the EM ratio. Then go back to the hero and say why the band moves between visits.