Explanation of the Sequence Models Simulator — What the Probability and the Estimate of a Hidden State Are Computing

This page explains what the line for “Probability degraded now” and the “Estimate of the true weight” seen in the simulator correspond to in the language of probability, and with what formulas they are drawn, in the order words → formulas → calculation procedure. The procedure for the detailed view, the conditions of the calculation, and the questions for checking are also collected here.

1. About this page

The Sequence Models Simulator is a tool for seeing how a “true state” that cannot be seen directly is estimated from clues (observations) that arrive at each time step. From Chapter 22 (Sequence Data and Hidden Markov Models), it covers the forward algorithm, backward algorithm, and Viterbi algorithm of the hidden Markov model (HMM), and the Kalman filter for a continuous hidden state.

The simulator has two views.

The two scenes of the simple view do the same calculations as ① and ② of the detailed view. We recommend this order: try the simple view, see what it really shows in Section 2, read the formulas in Section 3, and operate the detailed view with the procedure in Section 4.

2. What the simple view really shows

Both scenes express with probability what can be known, from the clues that have arrived, about a “state that cannot be seen directly.” The line in Scene A is “the probability that the furnace is degraded now,” and the line and band in Scene B are “the likely value of the true weight and its range.” Both are drawn by repeating, each time a clue arrives, “predict the next from the previous result → correct with the clue that arrived” (Section 3.1).

2.1 Scene A: Is the furnace normal or degraded right now?

The state inside the furnace (normal or degraded) cannot be seen from outside; only a thermometer reading (Low, Mid, High) arrives every hour. When the furnace is degraded, “High” tends to come out, and when it is normal, “Low” tends to come out, but every reading can come out in either state. This is the hidden Markov model of Section 22.3 of the text, with two states (1 = normal, 2 = degraded) and three observation values.

Table 1: Words on the screen in Scene A and the corresponding terms and symbols
Words on the screenTermSymbol or formula
State of the furnace (normal/degraded), TruthHidden statezt ∈ {1, 2} (1 = normal, 2 = degraded)
Thermometer reading (Low, Mid, High), ClueObservationxt ∈ {Low, Mid, High}
(Not changed on the screen) How easily the furnace state changesInitial distribution and transition matrixπ = (0.95, 0.05), A11 = 0.97, A22 = 0.95
How reliable the thermometer is (No clue / Ordinary / Reliable)Emission probability (separation of the emission distributions)Bjv, s = 0, 0.7, 0.9
Probability degraded now; Probability from the readings so far (solid line) (on a narrow screen, “Probability so far (solid)”)Filtering probabilityα̂t(2) = p(zt = 2 | x1:t)
Dotted line of “Look back later” (Probability also using later readings (dotted line); on a narrow screen, “Looked-back probability (dotted)”)Smoothing probability (computed from the n hours received)γt(2) = p(zt = 2 | x1:n)
Line above 0.5 = judged “degraded”The state with the largest posterior probability at each timeargmaxj p(zt = j | …)
Hit rateAccuracyFraction of times at which the judgment agrees with zt
Miss▲, Review◇Times of wrong judgment (filtering, smoothing)argmax ≠ zt
Truth (Check the answer)True state sequence used to generate the synthetic dataz1:T

The three cards for the thermometer choose the separation s that determines the emission probability B. How easily each reading comes out in the normal state is (Low, Mid, High) = ((1 + s)/3, 1/3, (1 − s)/3), and in the degraded state ((1 − s)/3, 1/3, (1 + s)/3). With “Ordinary” (s = 0.7), “High” comes out with probability 0.57 when degraded and 0.10 when normal. “Mid” has probability 1/3 in both states, so a “Mid” reading gives no evidence. With “No clue” (s = 0), the three readings come out with the same probability 1/3 in both states.

The dotted line of “Look back later” is the probability obtained by re-examining the state at each time t ≤ n using all the readings of the n hours received so far. After all 100 hours have been received (n = T = 100), it has the same values as the smoothing γt in ① of the detailed view.

Numbers for “Try it” (all computed on the record of furnace 1):

Where the analogy fits and where it does not

Where it fits: as in the furnace monitoring of Section 22.11 of the text, this is a hidden Markov model with two states, three observation values, and one step per hour, computed with the same functions as ① of the detailed view. The record of furnace 1 with the “Ordinary” thermometer is the same sequence as the defaults of ① in the detailed view (π1 = 0.95, A11 = 0.97, A22 = 0.95, s = 0.7, T = 100, seed 20261112).

Where it does not fit: the furnace states and readings are synthetic data for teaching purposes. In a real furnace, degradation usually only progresses and does not reverse, but in this model the furnace can also return from degraded to normal (A21 = 0.05). Also, the transition and emission probabilities are treated as known. In real monitoring, they must be estimated from records (the Baum–Welch algorithm of Section 22.4 of the text). Representing how the thermometer readings come out by the single choice “How reliable the thermometer is” is also a simplification of this model.

2.2 Scene B: Can a wobbly scale tell your true weight?

The true weight goes up and down a little every day, and the display of the scale wobbles further away from it. Each time a display arrives, the estimate of the true weight (line) and its range (band) are updated. This is the one-dimensional Kalman filter of Section 22.9 of the text, in which the hidden state zt follows a random walk and noise is added to the observation xt = zt + vt.

The calculation uses the same dimensionless quantities as ② of the detailed view, and the screen converts them to body weight (kg):

weight (kg)=60+0.5×zt,range of the estimate (kg)=±0.5×2Pt

This conversion is linear, so the shapes of the line and band stay the same; only the scale of the vertical axis changes. The variance of the daily change q = 0.2 corresponds to “going up and down by about 0.22 kg a day,” and the estimate before weighing, μ0 = 0, P0 = 1, corresponds to “about 60 kg (±1.0 kg).”

Table 2: Words on the screen in Scene B and the corresponding terms and symbols
Words on the screenTermSymbol or formula
True weightHidden state (continuous)zt (60 + 0.5zt kg on the screen)
(Not changed on the screen) Daily change in weightProcess-noise varianceq = 0.2
Display of the scale (×)Observationxt = zt + vt, vt ~ 𝒩(0, r)
How much the scale wobbles (Small wobble / Ordinary / Large wobble)Observation-noise variancer = 0.1, 1, 4 (standard deviation 0.16, 0.5, 1.0 kg)
Estimate before weighing (60 kg, ±1.0 kg)Initial mean and varianceμ0 = 0, P0 = 1
Last estimate (○; the prediction for that day)Mean of the predictionμt|t−1
Estimate of the true weight (line, ●)Filtering meanμt
Range of the estimate (band), ±… kg (about 95 %)Twice the filtering standard deviation±2√Pt
Trust in the new displayKalman gainKt = Pt|t−1/(Pt|t−1 + r)
Missed days (hatched)Missing observationNo update; Pt = Pt−1 + q
True weight (Check the answer)True state used to generate the synthetic dataz1:T

The band width ±2√Pt is the range that holds about 95 % of the probability of a normal distribution (the same as the band in ② of the detailed view). The “trust” is the fraction of the gap between the display and the estimate by which the estimate is moved; it is larger when the range of the estimate is wider (less confidence in one’s own estimate) and when the wobble of the scale is smaller. When weighing every day, Kt and Pt approach the steady-state values K∞ and P∞ (K∞ = 0.358 for the “Ordinary” scale, 0.732 for “Small wobble,” and 0.2 for “Large wobble”).

Numbers for “Try it” (all computed on the record of person 1):

Where the analogy fits and where it does not

Where it fits: this is a one-dimensional state-space model in which the true value changes slowly and noise is added to each measurement, computed with the same functions as ② of the detailed view. The sequence for person 1 with the “Ordinary” scale is the same sequence as the defaults of ② in the detailed view (q = 0.2, r = 1, μ0 = 0, P0 = 1, T = 100, seed 20261112), converted to kg.

Where it does not fit: a real body weight changes in a definite direction with diet and exercise, and also goes up and down within a day. A scale can also be biased (for example, always reading a little heavy). In this scene, the weight is a random walk with no direction, and the wobble of the scale is a normal distribution with mean 0 whose size is known. The weights and displays are synthetic data for teaching purposes. The numbers on the scale’s display and the movement of the estimate from ○ to ● are visual effects and are not used in the calculation.

3. How it works

3.1 Predict, then correct with the clue

Both the line in Scene A and the estimate in Scene B are computed in the following two stages each time the time advances by one step (Sections 22.5 and 22.9 of the text).

  1. Prediction: combine the result at the previous time with how easily the state changes (the transition matrix A in A, the daily change q in B) to make a prediction: “the state now is probably like this.”
  2. Update: multiply by how easily the clue that arrived comes out (the emission probability B in A, the wobble of the scale r in B) to correct the prediction (Bayes’ theorem).

In Scene A, these two stages are written as the following formula (the right side is divided so that it sums to 1 over the two states).

α^t(j)⏟probability now∝Bjxt⏟how the reading comes out×∑iα^t−1(i)Aij⏟prediction

Because the transition probability A12 = 0.03 is small, it is unlikely that a normal furnace has suddenly become degraded, so a single “High” reading does not raise the line much (Section 22.11 of the text). This is why, in “Try it,” going above 0.5 came 2 hours late.

In Scene B, the distribution remains a normal distribution throughout, so only the estimate (mean) and the range (variance) need to be updated. The update takes the form “move the estimate by Kt times the gap between the display and the estimate.”

μt⏟new estimate=μt∣t−1⏟last estimate+Kt⏟trust(xt−μt∣t−1⏟gap between display and estimate)

“Look back later” (smoothing) also uses the backward algorithm, which runs from later times to earlier times, and judges using the clues that arrived after that time as well. It is more accurate for that reason, but it cannot be computed until the later clues arrive, so it cannot be used for judging on the spot.

3.2 Formulas of the hidden Markov model

Let the hidden state be zt ∈ {1, 2} (1 = normal, 2 = degraded), the initial distribution πi = p(z1 = i), the transition matrix Aij = p(zt = j | zt−1 = i) (from i to j; each row sums to 1), and the emission probability Bjv = p(xt = v | zt = j). Then the joint distribution is

p(x1:T,z1:T)=πz1∏t=2TAzt−1zt∏t=1TBztxt

The forward algorithm (αt(j) = p(x1:t, zt = j)) and the backward algorithm (βt(j) = p(xt+1:T | zt = j)):

α1(j)=πjBjx1,αt(j)=Bjxt∑iαt−1(i)Aij,p(x1:T)=∑jαT(j)βT(i)=1,βt(i)=∑jAijBjxt+1βt+1(j)γt(j)=p(zt=j∣x1:T)=αt(j)βt(j)p(x1:T),p(zt=j∣x1:t)=αt(j)∑kαt(k)(filtering)

αt(j) is a product of probabilities, so for large T it shrinks exponentially and eventually rounds to 0 in floating-point numbers (in this simulator’s test it rounded to 0 at T = 2000). We therefore use the following scaling. At each time we divide by the normalizing coefficient ct = p(xt | x1:t−1) and compute the normalized α̂t(j) = p(zt = j | x1:t) in sequence.

ct=∑jBjxt∑iα^t−1(i)Aij,α^t(j)=Bjxt∑iα^t−1(i)Aijct,lnp(x1:T)=∑t=1Tlnctβ^T(i)=1,β^t(i)=1ct+1∑jAijBjxt+1β^t+1(j),γt(j)=α^t(j)β^t(j)

Inside the computation, a version that obtains the same quantities in logarithms (updating ln αt with log-sum-exp) is also computed in parallel, and the readout shows the difference between the two log-likelihoods (the size of the rounding error). For Gaussian observations, in place of Bjxt the density 𝒩(xt | μj, σ2) is used, and at each time we divide by the larger of the two densities before computing (the divided amount is added back to the log-likelihood).

The Viterbi algorithm takes a maximum instead of a sum. ωt(j) is “the joint probability of the most probable state sequence among those ending in state j at time t,” and ψt(j) is the previous state at that point (the back pointer). The computation is done in logarithms.

ω1(j)=πjBjx1,ωt(j)=Bjxtmaxiωt−1(i)Aij,ψt(j)=argmaxiωt−1(i)Aij

3.3 Formulas of the Kalman filter

The Kalman filter in ② is the forward algorithm for the case in which a continuous hidden state zt follows a random walk zt = zt−1 + wt (wt ~ 𝒩(0, q)) and the observation is xt = zt + vt (vt ~ 𝒩(0, r)). Because the distributions remain Gaussian throughout, only the mean and the variance need to be updated (the update is the same computation as “Bayesian Inference of the Mean of a Gaussian Distribution” in Chapter 4).

Prediction: μt∣t−1=μt−1,Pt∣t−1=Pt−1+q(for t=1: μ0, P0)Gain: Kt=Pt∣t−1Pt∣t−1+rUpdate: μt=μt∣t−1+Kt(xt−μt∣t−1),Pt=(1−Kt)Pt∣t−1=Pt∣t−1rPt∣t−1+rSteady state: P∞−=q+q2+4qr2,K∞=P∞−P∞−+r,P∞=K∞r

μt and Pt are the mean and variance of p(zt | x1:t) = 𝒩(zt | μt, Pt), and μt|t−1 and Pt|t−1 are the mean and variance of the prediction from the observations up to one step earlier. At a time when the observation is missing, no update is made: μt = μt|t−1 and Pt = Pt|t−1. The variance update is computed in the subtraction-free form Pt|t−1r/(Pt|t−1 + r), so it cannot become negative through rounding.

3.4 Calculation procedure

  1. Choose the parameters (①/A: π, A, B (separation s); ②/B: q, r, μ0, P0) and the seed, and generate the synthetic data sequence. ①/A uses one uniform random number at a time at each time step, in the order state → observation. ②/B uses standard normal random numbers from the Box–Muller method.
  2. ①/A: compute α̂t(j) by the scaled forward algorithm, and β̂t(j) and γt(j) by the backward algorithm. “Look back later” in A redoes the same calculation using only the observations of the n hours received.
  3. ①/A: at each time, take the state with the larger probability as the judgment, and compare it with the true state to obtain the accuracy (if the probabilities are equal, normal).
  4. ②/B: at each time, do the prediction (Pt|t−1 = Pt−1 + q) → gain Kt → update. At times when the observation is missing, no update is made.

The calculations of the simple view call the same functions as the detailed view (in hmm.model.js: sampleHMM, analyze, forwardBackwardScaled, sampleRW, kalman, kalmanSteady, missingMask, and others). The only calculations added for the simple view are the look-back using the n hours received, counting the hit rate and the times of wrong judgments, and the conversion to kg (hmm.easy.js).

4. How to use the detailed view

The detailed view has two tabs, ① (Hidden Markov model) and ② (Kalman filter). In ①, “View” switches between “Generated sequence” and “Hand calc. (T = 3).” Opening the page as hmm-simulator.html?mode=hand starts in the hand-calculation mode of ①.

4.1 Procedure and what to observe

  1. In ①, look at the figure with the defaults (discrete three-valued, π1 = 0.95, A11 = 0.97, A22 = 0.95, separation s = 0.7, T = 100; the true state is degraded from time 69 to 86). What to look at: the dashed line (filtering) jumps around with each new observation and, even in a normal interval, wrongly exceeds 0.5 when “High” continues. The solid line (smoothing γt) also uses later observations, so it is smooth and catches the start of the degradation early. In the readout the accuracy is 0.90 for filtering, 0.99 for smoothing, and 0.98 for Viterbi.
  2. Press “Advance time” or repeat “Step 1 time step.” What to look at: in “Putting the current numbers into the formula,” the “prediction” (the previous filtering probability multiplied by the transition probabilities Aij and summed) is multiplied by the emission probability and normalized, which gives the filtering probability at that time.
  3. Set the separation s to 0, then to 1. What to look at: at s = 0 the observations say nothing about the state, so γt becomes the prior probability determined by the transitions alone, and the accuracy drops. As s increases, the estimate approaches the true state.
  4. Switch to “Gaussian” and change the degraded mean Δ. What to look at: when Δ is small (the two distributions overlap) the estimate becomes ambiguous, and when Δ is 3 or more it is almost always right.
  5. Switch to “Hand calc. (T = 3).” What to look at: α3(1) + α3(2) and the sum of the probabilities p(x1:3, z1:3) of the 8 state sequences give the same value p(x1:3) = 0.036280. γt agrees with the value marginalized from the full enumeration.
  6. In hand-calculation mode, press “Mismatch example (Low, High, Mid).” What to look at: the Viterbi path is Normal → Degraded → Degraded, yet the sequence of the state with the largest γt at each time is Normal → Degraded → Normal. Compare the probabilities of those two sequences in the full-enumeration table.
  7. In ②, turn on “Insert missing observations.” What to look at: at times with no observation only the prediction is made, so the band (±2√Pt) keeps widening and then narrows abruptly when observations return. In the lower figure, Kt = 0 and Pt grows by q at every step.
  8. In ②, uncheck “Use the same q, r as the data” and make the filter’s q smaller or larger. What to look at: assuming a small q makes the estimate sluggish (K∞ is small), and assuming a large one makes it swayed by the observation noise. The fraction of times the true value falls inside the ±2√Pt band (the coverage) deviates from 95 %.

With the keyboard, Tab moves to buttons and sliders, Enter (or Space) presses, and the arrow keys move sliders. The tabs can be switched with ←→. When embedded, ?only=hmm&mode=hand starts in hand-calculation mode.

5. Conditions of the calculation

5.1 Data and random-number conditions

5.2 Conditions fixed in the simple view

5.3 Simplifications

5.4 Conditions under which results become unstable

6. Questions for checking

Questions 1 and 2 can be answered with the simple view alone. Questions 3–6 use the detailed view.

  1. In Scene A of the simple view (furnace 1, “Ordinary” thermometer), the furnace is really degraded from hour 69, but the line went above 0.5 at hour 71. Why does a single “High” reading not push the line above 0.5? And why does “Look back later” raise the probability at hour 69 to 0.77?
    Sample answer

    The probability of moving from normal to degraded is as small as 0.03 per hour, so at the prediction stage the chance that “it is degraded now” is small, and even when one “High” arrives (it also comes out with probability 0.10 when normal), the judgment does not switch to degraded at once. Only when “High” continues does “degraded” explain the sequence of readings better. When looking back, it is also known that “High” continued from hour 70 on, so it becomes clear that hour 69, the start of that run, was probably already degraded (0.77).

  2. In Scene B of the simple view, when weighing with “Add missed days,” on the day right after the missed days end, the display is trusted more than usual (with the “Ordinary” scale, 36 % → 78 %). Why?
    Sample answer

    On missed days there is nothing to correct the estimate with, so it becomes unclear how far the true weight has moved, and the range of the estimate widens every day (±1.8 kg on day 45). When you are not confident in your own estimate, even the display of a wobbly scale is more reliable than the estimate. The trust is “uncertainty of the estimate ÷ (uncertainty of the estimate + wobble of the scale),” so it is larger when the range of the estimate is wider.

  1. In the hand-calculation mode defaults (π = (0.6, 0.4), A11 = 0.7, A22 = 0.6, observations Low, Mid, High), compute α1(1), α2(1), and p(x1:3) by hand.
    Sample answer

    α1(1) = 0.6 × 0.5 = 0.30000, α1(2) = 0.4 × 0.1 = 0.040000. α2(1) = B1,Mid(0.3 × 0.7 + 0.04 × 0.4) = 0.4 × 0.226 = 0.090400. Similarly α2(2) = 0.3 × (0.3 × 0.3 + 0.04 × 0.6) = 0.034200, α3(1) = 0.1 × (0.0904 × 0.7 + 0.0342 × 0.4) = 0.0076960, and α3(2) = 0.6 × (0.0904 × 0.3 + 0.0342 × 0.6) = 0.028584. p(x1:3) = 0.0076960 + 0.028584 = 0.036280. This agrees with the sum over the 8 enumerated sequences.

  2. In the “Mismatch example (Low, High, Mid),” why does the sequence of the state with the largest γt at each time (Normal, Degraded, Normal) differ from the Viterbi path (Normal, Degraded, Degraded)?
    Sample answer

    γ3 = (0.54627, 0.45373) is the probability summed over (marginalized over) both the sequences in which z2 is normal and those in which it is degraded. The last observation “Mid” is hard to distinguish, with B1,Mid = 0.4 and B2,Mid = 0.3, and once the sequences passing through z2 = normal are included, z3 = normal becomes slightly more probable. On the other hand, the single most probable sequence, Normal, Degraded, Degraded (probability 0.0097200), is more probable than Normal, Degraded, Normal (0.0086400) because the probability of staying degraded, A22 = 0.6, is larger than the probability of returning from degraded, A21 = 0.4. “The most probable state at each time” and “the most probable state sequence” are different questions.

  3. With the defaults in ①, what are the accuracies of filtering and smoothing? Why does smoothing tend to be higher? Which of the two can be used in real-time monitoring?
    Sample answer

    With the defaults (seed 20261112), filtering is 0.90, smoothing (γ max) is 0.99, and Viterbi is 0.98. Smoothing also uses observations after time t, so it can correct, after the fact, a judgment made just after the state switched. However, it cannot be computed until the later observations arrive, so in real-time monitoring, where a decision must be made at that time, only filtering can be used (smoothing can be used when analyzing a record afterwards).

  4. With the defaults in ② (q = 0.2, r = 1, P0 = 1), find K1, K2, and K∞. How does Pt change over an interval in which the observations are missing?
    Sample answer

    K1 = 1/(1 + 1) = 0.5, P1 = 0.5. P2|1 = 0.5 + 0.2 = 0.7, K2 = 0.7/1.7 = 0.41176. The steady-state values are P∞− = (0.2 + √(0.04 + 0.8))/2 = 0.55826 and K∞ = 0.55826/1.55826 = 0.35826. When observations are missing no update is possible, and Pt = Pt−1 + q grows by 0.2 at every step (by 3.0 over 15 steps), and the gain at the time observations return becomes large.

7. Corresponding sections of the text and references

References (from the end of Chapter 22):

Back to the Sequence Models Simulator | Machine Learning — From Probability to GPT (Contents) | Equations are typeset with the browser’s built-in MathML (no external library).