- Learn
- Computer Science & IT
- Computer Science
- Artificial Intelligence
- Hidden Markov Models
Markov Models and Hidden Markov Models
IntermediateLesson 7 of 10 in Artificial Intelligence Course
What you will learn
- Describe a system that moves between states over time, compute how likely a run of states is, predict where the system will be, and find its long-run behavior.
- Describe a system as a Markov chainName the states, write the transition model as a matrix or diagram, and compute the probability of a sequence of states.
- Predict how the state distribution evolvesUse the transition matrix to update a probability distribution over states one step at a time, and see how predictions forget their starting point.
- Find and interpret stationary distributionsSolve for the distribution a chain keeps once it reaches it, know when the chain converges to it, and use it to describe long-run behavior.
- Describe a system as a Markov chain
- Build models in which the true state is hidden and only noisy evidence is observed, and choose states, variables and parameters that make such models work for real problems.
- Build a hidden Markov modelCombine a hidden Markov chain with a sensor model, compute the joint probability of states and evidence, and name the questions such a model can answer.
- Design temporal models for real problemsChoose state variables, discretization and parameters so that the Markov assumptions are reasonable, and see how dynamic Bayesian networks extend hidden Markov models.
- Build a hidden Markov model
- Compute what the evidence says about the hidden states: track the current state, predict ahead, score the evidence, revise past estimates and find the single most likely sequence of states.
- Track the current state with filteringRun the forward algorithm, alternating a prediction step and an evidence update, to keep an up-to-date belief about the hidden state.
- Predict ahead and score the evidenceExtend the belief into the future without new evidence, forecast the next observation, and compute how likely the observed evidence is under a model.
- Revise past estimates with smoothingUse later evidence to improve the estimate of an earlier state with the forward–backward algorithm.
- Find the most likely explanation with the Viterbi algorithmFind the single most probable sequence of hidden states, and see why it can differ from the most likely state at each step.
- Track the current state with filtering
- Track a belief with a population of samples when the state space is too large or continuous for exact filtering, and judge how reliable that approximation is.
- Run a particle filter step by stepRepresent a belief by particles, move them with the transition model, weight them by the evidence and resample.
- Judge the accuracy and failures of particle filtersExplain how the number of particles affects accuracy, recognize degeneracy and impoverishment, handle impossible evidence, and choose between particle, exact and Kalman filtering.
- Run a particle filter step by step
- Use Markov models, hidden Markov models and particle filters to locate moving objects and robots, recognize speech and label words in a sentence.
- Track and localize moving objectsSet up tracking and robot localization as filtering problems, compute a localization update, and recognize the extensions used in practice.
- Recognize speech and label sequencesExplain how hidden Markov models and Markov language models were combined to recognize speech, decode with Viterbi, tag parts of speech, and place these methods in current practice.
- Track and localize moving objects
Hidden Markov Models study guide
1Modeling change and equilibrium
A transition rule lets you turn a description of change into a probability model. Start by choosing states and reading the direction of each transition, then combine many possible paths into one distribution over the next step. Long-run behavior adds a separate question: whether those distributions settle into a common balance. Periodic and absorbing examples show why the existence of a balance is only part of the answer.
1.1 States, transitions, and paths
A changing system needs a state for each moment and a rule for moving to the next moment. A discrete-time Markov chain records these states at evenly spaced steps. Choose the state and time step together: daily weather and a robot's location every second describe different processes.
What the current state must contain
The first-order Markov property is
Once the current state is known, earlier states add no information about the next one. This is conditional independence, not independence between consecutive states. Knowing yesterday's weather can help predict tomorrow's when today's weather is unknown.
A chain needs an initial distribution, , and a transition model. We use time-homogeneous transitions: the same probabilities apply at every step. Some AI texts call this a stationarity assumption. In probability theory, a stationary process has joint distributions unchanged by shifting time; fixed transitions alone do not ensure that. Starting a time-homogeneous chain in a stationary distribution does.
Read a transition matrix
For weather, let the states be Sunny (S) and Cloudy (C). Rows name the current state and columns the next state:
From Sunny, the next day is sunny with probability 0.8 and cloudy with probability 0.2. From Cloudy, those probabilities are 0.4 and 0.6. Every row sums to 1 because it lists every destination from one starting state. Columns need not sum to 1. A state diagram represents the same table with arrows, including arrows back to the same state.
Some books transpose this convention. Before calculating, read the definition of an entry: here . A correct set of numbers used in the wrong orientation gives the wrong prediction.
Multiply along a path
A particular path uses its initial probability and one transition for each move:
If day 1 is certainly sunny, the path Sunny, Sunny, Cloudy, Cloudy has probability
The first move contributes 0.8, the switch contributes 0.2, and staying cloudy contributes 0.6. Multiplying separate daily frequencies would discard the links between days. In a Bayesian network, those links are the arrows in .
Keep enough history in the state
A second-order model depends on the last two values. Turn it into a first-order model by defining the state as (yesterday, today). Two weather values then give four possible pairs. A transition from (Sunny, Cloudy) can lead only to a pair beginning with Cloudy, because adjacent pairs must overlap. For a process of order , store the last values together; the algorithms stay first-order, while the number of combined states grows.
Key Takeaways
- The Markov property removes dependence on earlier states after conditioning on the present.
- Rows of the transition matrix describe destinations from one current state.
- A path probability multiplies the initial probability and its transitions.
- Time-homogeneous transitions and stationary state distributions are different ideas.
- Storing recent history together turns a higher-order chain into a first-order chain.
1.2 Predicting a distribution
A chain occupies one state at each time, but you may not know which one. A state distribution stores that uncertainty as a row vector. Its entries give the probabilities of the possible states, not fractions of time within a single step.
Add every route into a destination
To predict Sunny tomorrow, consider both ways to get there: today may be Sunny or Cloudy. Weight each transition by the probability of its starting state:
For the complete vector, this is . After moves, . This update is sometimes called the mini-forward algorithm, the evidence-free version of HMM filtering.
Work through the weather chain
Use rows (0.8, 0.2) from Sunny and (0.4, 0.6) from Cloudy. Start with a certainly sunny day: . One move gives . For day 3, the sunny contribution is from Sunny and from Cloudy. Add them to get 0.72. The cloudy contributions are and , giving 0.28.
Thus . One further update gives and . Carry unrounded values between steps and round displayed results at the end.
Check the meaning and orientation
Each result must be nonnegative and sum to 1. Under the row convention, put the distribution on the left. Using instead gives the column (0.8, 0.4), whose total is 1.2. That calculation selects the probabilities of reaching Sunny from two different starts; it does not distribute one starting belief among destinations.
The value 0.72 on day 3 means about 72% of many independent runs with a sunny day 1 will be sunny on day 3. It describes neither a fixed repeating weather pattern nor a day that is 72% sunny.
Why prediction stays manageable
A dense update over states costs operations. It summarizes all past paths in the current vector, so the cost per move stays the same as time grows. Listing every path from a known start would instead require paths at time .
For this weather chain, successive sunny probabilities approach . If , then . Subtracting shows that the gap shrinks by a factor of 0.4 each step. Other chains can behave differently; convergence needs the conditions studied with stationary distributions.
You can also simulate a run. Draw the initial state, then draw from the transition row for the state currently occupied. From Sunny, a uniform random draw below 0.8 selects Sunny; a draw at least 0.8 selects Cloudy. Repeating many runs estimates the same predicted distribution and introduces the sampling idea used by particle filters.
Key Takeaways
- Prediction adds contributions from every possible previous state.
- With row vectors, use pₜ₊₁ = pₜT and pₜ₊ₖ = pₜTᵏ.
- A distribution describes uncertainty at one time, not a deterministic schedule.
- Dense prediction costs O(S²) per step and simulation can approximate it.
1.3 Long-run behavior and its limits
A distribution can stay unchanged even while individual runs keep moving. A stationary distribution describes this balance. It is useful for long-run forecasts, but its existence alone does not tell you whether a chain approaches it from a particular start.
Solve the balance equations
A stationary row vector satisfies together with and nonnegative entries. For the weather chain, probability flowing from Sunny to Cloudy must balance probability flowing back:
The first equation gives . Substitution gives , so . For a two-state chain with switching probabilities from state 1 to 2 and from 2 to 1, when .
For more states, write one incoming-flow equation per state. Replace one with the sum-to-1 equation and solve the linear system. The balance equations alone leave the scale undetermined. Finally multiply the proposed vector by the matrix to check it.
For bike-share stations A, B, C, take rows (0.6, 0.2, 0.2), (0.1, 0.8, 0.1), and (0.2, 0.2, 0.6). The solution is (0.25, 0.5, 0.25). For example, incoming probability at B is . Uniform probability would fail this check.
Separate three questions
| Question | Finite-chain result |
|---|---|
| Does a stationary distribution exist? | Every finite chain has at least one. |
| Is it unique? | Irreducibility is sufficient. |
| Does every starting distribution approach it? | Irreducibility plus aperiodicity is sufficient. |
Irreducible means every state can reach every other state, possibly through several moves. Aperiodic means returns are not locked into a fixed cycle longer than one step. The weather matrix has all entries positive, so both conditions hold. In a finite irreducible chain, stationary probabilities also give the long-run fractions of steps spent in each state, even when periodicity prevents convergence of the time-specific distribution.
Two revealing counterexamples
If two states always swap, the distribution from a certain first state alternates between (1, 0) and (0, 1). The unique stationary vector is (0.5, 0.5), but these predictions never approach it. Along a long run, each state still occupies half the steps.
If both states are absorbing, each stays where it is forever. Every vector (q, 1 − q) is stationary, so there is no unique equilibrium shared by all starts. These examples show why uniqueness, convergence, and time averages need separate checks.
The initial distribution describes the start; it equals a stationary distribution only when you start in equilibrium. Fixed transition probabilities describe the model's law, not its current distribution. PageRank uses stationary probabilities to rank pages in a random-surfer model. Markov chain Monte Carlo constructs a chain with a desired stationary distribution so its long run can supply samples.
Key Takeaways
- A stationary vector is nonnegative, sums to 1, and satisfies π = πT.
- Balance equations need a normalization equation to fix their scale.
- Every finite chain has a stationary distribution.
- Finite irreducible chains have a unique stationary distribution and matching long-run time fractions.
- Aperiodicity also ensures convergence from every start in a finite irreducible chain.
- Periodic or reducible chains require separate checks of their long-run behavior.
2Building models with hidden states
A reading can be perfectly observed while the state that produced it remains uncertain. Hidden Markov models separate the movement of that state from the noise in the observations. Choosing enough information for the state makes these assumptions useful; choosing too much can make inference costly. Parameter counts, training records, and sensor outliers give practical ways to judge and improve a model before running it.
2.1 Hidden states and noisy observations
A sensor reading gives evidence about a state without revealing it perfectly. In a hidden Markov model, or HMM, the state changes over time and each state produces an observation. A robot may know what its range sensor reported while remaining uncertain about its position.
Specify three probability models
An HMM needs an initial state distribution, a transition model, and a sensor model:
The hidden state is a discrete variable. The sensor model, also called the emission or observation model, tells you the likelihood of each observation in each state. We put a prior directly on and observe there. Texts that start with an unobserved perform a transition before the first observation instead.
The state has the first-order Markov property. The observation at a time depends only on that time's state: . In a Bayesian network, draw a hidden-state chain and add an arrow from each state to its observation.
Build the solar-panel model
The hidden weather is Sunny or Cloudy, with transition rows (0.8, 0.2) and (0.4, 0.6). Both initial states have probability 0.5. Daily panel output is High or Low:
| Hidden weather | High | Low |
|---|---|---|
| Sunny | 0.8 | 0.2 |
| Cloudy | 0.3 | 0.7 |
Each sensor row sums to 1. A cloudy day can still produce High output, so High does not identify Sunny with certainty. Likewise, is a statement about output on cloudy days. Finding also needs the prior and Bayes' rule.
Score states and evidence together
For a particular state path and observation sequence,
For Cloudy, Cloudy, Sunny with Low, Low, High, start at . Staying cloudy and observing Low gives . Switching to Sunny and observing High gives .
Observations can be dependent even though they have no direct arrows between them. Persistent cloudy weather makes successive Low readings tend to occur together. Conditioning on the hidden states removes that dependence. Evidence updates the observer's belief; observing Low does not itself make the weather change.
Choose the inference question
| Task | Quantity requested |
|---|---|
| Filtering | Current state given evidence so far |
| Prediction | Future state given evidence so far |
| Smoothing | Earlier state given later evidence too |
| Viterbi decoding | One most likely complete state path |
| Evidence likelihood | Probability of the observation sequence |
The same three models support all five tasks. What changes is which variables you retain, which you sum out, and whether you sum over paths or select the largest path score.
Key Takeaways
- An HMM combines a hidden chain, a prior, and a sensor model.
- An observation depends on its current hidden state under the sensor assumption.
- Sensor likelihoods and state posteriors condition in opposite directions.
- Joint path-and-evidence probabilities include one emission per observed step.
- Filtering, prediction, smoothing, decoding, and likelihood answer different questions.
2.2 Choosing states and learning model parameters
The state definition decides what the model can remember. A useful temporal model keeps the information needed to predict the next state, while keeping inference affordable. Its probabilities must also reflect the data and sensor failures it will encounter.
Choose enough state information
Position alone may be inadequate for an object with momentum: earlier positions reveal its direction. Adding velocity lets the current state explain that direction. Add season if the dynamics depend on it. These choices make the Markov approximation more reasonable; they are choices about what information travels forward.
A continuous quantity can be placed on a grid. Temperatures from 10 °C to 20 °C in 0.1 °C increments give 101 values, including both endpoints. Finer spacing increases the number of states. Combining several gridded quantities multiplies their counts, and dense exact inference costs per step.
Count independent parameters
A categorical row with entries has free parameters because the last entry is fixed by their sum. With states and observation values, an unrestricted HMM therefore needs
free parameters: prior, transitions, and emissions. The two-state, two-output solar model needs . Counting every table entry would count the row-sum constraints as additional choices.
Factor the state with a dynamic Bayesian network
A dynamic Bayesian network (DBN) keeps several state variables and gives each its own parents. It can express local dependencies without constructing a huge flat transition table. Twenty Boolean variables have joint states; a flat transition table has entries. If each next-step Boolean variable has three Boolean parents, its table needs eight probabilities, so all 20 need .
A discrete DBN can be flattened into an HMM by treating a complete assignment as one state. Factored storage is compact, but exact inference can still become costly when dependencies couple many variables. Particle methods can sample these assignments directly.
Estimate rows from data
When states are labeled, use conditional counts. Forty sunny successors out of 50 recorded transitions from Sunny give . The denominator counts transitions leaving Sunny, not every day in the record. A state at the end of a record has no observed successor.
Zero counts produce zero maximum-likelihood probabilities. Add-one correction gives each destination one pseudo-count and increases the row total accordingly. This avoids ruling out a transition solely because a small training record missed it. When states are hidden, Baum–Welch alternates smoothed expected counts with parameter re-estimation.
Give failures a place in the sensor model
If every possible state assigns zero likelihood to a reading, an update has zero total and cannot normalize. A small outlier component can give unusual readings some probability. A normalized mixture has the form . Both component distributions must be normalized.
The effect of a reading depends on likelihood ratios across states. Equal likelihoods leave the predicted belief unchanged after normalization. A small likelihood under every state can still be informative if the likelihoods differ greatly in relative terms.
Key Takeaways
- Choose state variables that carry the history needed for the next step.
- Finer grids and combined variables enlarge the state space.
- Row-sum constraints reduce the number of free parameters.
- DBNs store local conditional models without a full joint transition table.
- Labeled states permit counting; hidden states can be learned with Baum–Welch.
- A normalized outlier mixture can keep unusual sensor readings possible.
3Estimating states across time
The same observations support different questions about time. Tracking the present requires a forward belief update; forecasting moves that belief ahead; reconstructing the past adds a backward pass. Selecting one complete explanation changes addition over paths into maximization. Working through these operations on the same solar-panel model makes the differences visible in both their arithmetic and their interpretation.
3.1 The forward algorithm
Filtering tracks the current hidden state using every observation available so far. Its output is a belief distribution, . You update this compact distribution when a new reading arrives, without retaining every possible earlier path.
Predict, weight, normalize
For a later step, first move the belief through the transition model:
Then weight each destination by the likelihood of the new observation and normalize:
The prediction describes where the state may have moved. The evidence update is Bayes' rule at the new time. With a prior on , start by weighting that prior with the first observation; there is no move before it.
Day 1: observe Low
Use the solar-panel model: prior (0.5, 0.5), transition rows (0.8, 0.2) and (0.4, 0.6), and Low likelihoods (0.2, 0.7). Weighting gives for Sunny and for Cloudy. The total is 0.45. Divide each weight by it to get .
Day 2: observe Low again
Prediction gives . Cloudy has probability . The new weights are and . Their total is , producing .
The second Low only slightly increases the cloudy belief. Motion toward the chain's sunny-heavy equilibrium competes with the new evidence favoring Cloudy. Applying Low directly to yesterday's belief would miss that movement.
Day 3: observe High
Predict . High has likelihoods (0.8, 0.3), so the weights are approximately (0.3887, 0.1542). Divide by their total, approximately 0.5429, to obtain .
High is times as likely under Sunny as under Cloudy. That likelihood ratio shifts the odds toward Sunny. A large likelihood alone is less informative than its size relative to the competing state's likelihood.
Keep an online filter reliable
A dense step costs time and stores belief entries, independent of the length of the history. This is exact variable elimination: each past state is summed out as you advance.
Normalize at each observation. Without scaling, the vector stores joint state-and-evidence probabilities, which can shrink below floating-point range. Keep the discarded totals separately if you need evidence likelihood. A zero total requires model or particle-support recovery; division cannot repair it.
Our row-vector formula is , where the diagonal matrix contains the new likelihoods. For column beliefs the equivalent is . Mixing these conventions is a frequent source of errors.
Key Takeaways
- Filtering estimates the current state given observations so far.
- The first observation weights the prior directly.
- Each later observation follows prediction, likelihood weighting, and normalization.
- Likelihood ratios determine how evidence shifts relative state beliefs.
- Normalization controls numerical scale; retain update totals to score evidence.
- Dense filtering uses O(S²) time per step and O(S) belief memory.
3.2 Forecasts and evidence likelihood
A filtered belief supports two useful questions: what might happen next, and how well did the model explain the readings already seen? Both use the same transition and sensor models, but the answers describe different random quantities.
Predict without future readings
For a forecast steps ahead, apply the transition matrix times to the latest filtered belief:
No observation update belongs to an unobserved future step. After the solar model sees Low, Low, High, the day-3 belief is approximately (0.7159, 0.2841). One prediction gives . Continuing from unrounded values gives sunny probabilities 0.6745, 0.6698, 0.6679, and 0.6672.
These approach . The chain gradually loses its dependence on the latest belief. Mixing time specifies how many steps are needed to come within a chosen distance of equilibrium from every starting state. A forecast close to equilibrium still retains a small influence from current evidence; it is not an exact reset.
Prediction need not increase uncertainty at every step. From (0.5, 0.5), this weather chain predicts (0.6, 0.4), a more concentrated distribution. Convergence concerns loss of dependence on the starting belief, not a rule that forecasts must become uniform.
Forecast an observation
An output forecast averages the sensor likelihood over predicted states:
For High on day 4, use the day-4 state prediction, not the day-3 filter: . The sunny probability and High-output probability differ because both weather states can produce High output.
Retain the totals from filtering
Before each update normalizes, its total is the probability of that observation given earlier ones. Call it . The chain rule gives
For Low, Low, High, the totals are approximately 0.45, 0.4556, and 0.5429. Their product, computed before rounding, is 0.1113. This is a sum over every hidden path compatible with the evidence. The best path alone contributes 0.04704, only part of the total.
An unnormalized forward pass gives the same likelihood by summing its final entries. A normalized pass is more stable, provided the totals are kept. In long sequences, store instead of multiplying tiny values. Here the natural log is about −2.196.
Compare models on matching evidence
A likelihood measures how well one model accounts for a particular observation sequence. To compare candidate word HMMs on the same recording, score that recording under each model and combine with word priors when finding posterior word probabilities. Longer sequences usually have smaller raw likelihoods, so a smaller number from a longer recording alone does not show a worse model.
Key Takeaways
- Future-state forecasts apply transitions without invented observations.
- Observation forecasts average sensor likelihoods over predicted states.
- Evidence likelihood is the product of the update totals.
- Likelihood sums hidden paths; a Viterbi score keeps only the best one.
- Log-likelihood adds log totals to avoid underflow.
3.3 Revising the past with forward–backward
A later observation can change what you believe about an earlier state. Smoothing estimates for . It is useful when reconstructing a recorded trajectory or when an application can wait briefly before reporting a past estimate.
Divide the evidence at the target time
Filtering has already summarized evidence up to time as . A backward message summarizes the remaining observations as a likelihood, . Combine them state by state:
Normalize the products across states. The later evidence is weighted according to how plausible it would be from each candidate state at time .
Pass the future likelihood backward
At the last time, there are no later observations, so for every state. Moving back one step gives
For each possible successor, multiply the chance of moving there, the likelihood of its observation, and the remaining future likelihood. Then add over successors. A backward message is a likelihood function over possible starting states, not a state distribution; its entries need not add to 1.
Smooth day 2 in the solar example
The observations are Low, Low, High. After the two Low readings, the filtered day-2 belief is approximately (0.2146, 0.7854). For the final High reading, the backward likelihood from a sunny day 2 is . From a cloudy day 2 it is .
Multiply: the products are approximately and . Normalize their unrounded values to obtain a day-2 sunny probability of 0.2767. High on day 3 makes a sunny day 2 more plausible than the original filtered probability 0.2146 did.
Continue to day 1
The backward likelihood from Sunny on day 1 is . From Cloudy it is . Combine with and normalize. The smoothed sunny probability is approximately 0.1635, down from 0.2222: the full future includes another Low as well as the final High.
Later evidence need not move every past estimate in the same direction. At the final time, smoothing equals filtering because no later evidence exists.
Organize the computation
The forward–backward algorithm first stores all forward beliefs, then computes backward messages and normalized products. For steps and states, dense computation costs and stores values. Fixed-lag smoothing reports the state a fixed number of steps behind the present, trading delay for more evidence.
Reversing the list of observations and running an ordinary filter is a different calculation. The backward recursion uses the original forward transitions and future likelihoods; it does not introduce a new initial prior at the recording's end. Smoothed state probabilities also supply expected counts for Baum–Welch learning.
Key Takeaways
- Smoothing uses evidence from before and after the target time.
- Multiply the forward belief by the future-evidence likelihood, then normalize.
- The last backward message is all ones, not a uniform probability distribution.
- Backward recursion sums successor contributions using the original transition model.
- Fixed-lag smoothing trades reporting delay for later evidence.
3.4 Finding one best path
Sometimes the desired answer is one complete explanation of the observations. Viterbi decoding finds the most likely hidden-state sequence. It accounts for transitions between states, which separate most-likely choices at individual times can ignore.
Change the objective
The target is . Every candidate has the same evidence denominator, so maximizing the joint score selects the same path. This score differs from a final-state posterior, which adds every path ending in that state.
With solar observations High, Low, the most likely individual states after smoothing are Sunny on day 1 and Cloudy on day 2. Yet Sunny, Sunny is the most likely complete path: its posterior is about 0.3282, compared with 0.2872 for Sunny, Cloudy. With forbidden transitions, individually plausible states can even make an impossible path.
Keep the best prefix for each ending state
Let be the best joint path-and-evidence score ending in state . Initialize . Then use
Save the maximizing predecessor as a backpointer. Paths ending in the same state have the same possible future continuations, so a lower-scoring prefix can be discarded. The forward algorithm adds competing prefixes; Viterbi selects their maximum.
Fill the trellis for Low, Low, High
The initial scores are (0.10, 0.35). On day 2, the Sunny candidates before emission are and . Keep the second and multiply by 0.2 to get 0.028, pointing to Cloudy. For Cloudy, compare 0.02 with 0.21; multiplying the larger by 0.7 gives 0.147, also pointing to Cloudy.
On day 3, Sunny compares with . Multiplying the larger by the High likelihood 0.8 gives 0.04704. Cloudy compares 0.0056 with 0.0882; multiplying the larger by 0.3 gives 0.02646. Both final pointers lead to Cloudy on day 2.
Backtrack from the end
The largest final score is 0.04704 at Sunny. Follow its pointer to Cloudy on day 2, then that pointer to Cloudy on day 1. Reverse this backward traversal to obtain Cloudy, Cloudy, Sunny. Dividing by the evidence likelihood 0.1113 gives its posterior, approximately 0.4226.
Choosing the largest score separately at every column would discard the stored predecessor relationships. The final score vector also cannot be normalized into a filtering belief: it retains just one path per state, not their sums.
Use logarithms for long sequences
Products can underflow. Store log scores instead:
Logarithms preserve ordering, so the path and pointers stay unchanged. Zero probabilities become negative infinity. Equivalently, negative log scores turn decoding into a minimum-cost path through a time-layered graph, or trellis. Dense Viterbi costs time and stores pointers. If paths tie for the largest score, each is a valid most likely explanation.
Key Takeaways
- Viterbi maximizes one complete path, while filtering sums paths.
- Keep the best prefix per ending state and save its predecessor.
- Reconstruct the answer by backtracking from the largest final score.
- Per-time marginal modes can differ from the best complete path.
- Log-space computation preserves the maximizing path and avoids underflow.
4Filtering with sampled states
A sampled population can carry a belief when a full table is too large. Follow how particles move, gain weights from a reading, and produce a new population through resampling. Each operation has a clear counterpart in exact filtering, along with its own source of approximation. Population size, lost regions, and the shape of the belief then help decide whether sampling or an exact representation is the better fit.
4.1 Sampling a changing belief
A probability table becomes difficult to store when the state space is huge. Continuous beliefs also lack a finite table in general. A particle filter represents a belief using sampled states, allowing computation to focus on a manageable population of possibilities.
Represent probability with particles
Each particle is one complete state, not a separate physical object. After resampling, all particles have equal weight, and a state's estimated probability is the fraction occupying it. Ten particles split seven Sunny and three Cloudy represent the belief (0.7, 0.3).
Draw initial particles from . A prior of (0.5, 0.5) gives expected equal counts but does not force every random sample to split equally. Under our time convention, weight these initial particles by the first observation and resample before any transition.
Elapse time by sampling transitions
For each later step, move each particle independently using the transition row for its current state. With weather rows (0.8, 0.2) and (0.4, 0.6), seven Sunny and three Cloudy particles have an expected sunny count of after moving.
One realized sample might contain six Sunny and four Cloudy particles. An expected count can be fractional; a realized particle count must be an integer. Keeping exactly 6.8 particles would not be a sampling algorithm.
Weight by the reading
Suppose the new solar output is Low. Each Sunny particle gets likelihood 0.2; each Cloudy particle gets 0.7. The six Sunny particles have total weight , and the four Cloudy particles have . Out of total weight 4.0, Sunny has weighted probability 0.3 and Cloudy 0.7.
Counts matter as well as per-particle weights. Normalizing only 0.2 and 0.7 would ignore how much predicted probability each group represented. Weighting reuses the same Bayes update as exact filtering on this sampled prediction.
Resample a fresh population
Draw ten particles with replacement, each old particle selected in proportion to its weight. Each new draw is Sunny with probability 0.3 and Cloudy with probability 0.7. The expected sunny count is three, though a run may give two, four, or another count. Multiple copies are allowed; they represent probability mass.
Reset the resulting particles to equal weights. Evidence has already affected which particles were copied, so retaining the old likelihood weights would count it again. The next iteration moves this new population before processing the next observation.
Compare with the exact update
Exact filtering from (0.7, 0.3) predicts (0.68, 0.32). Low then gives weights (0.136, 0.224), so the exact sunny posterior is . The particle run's weighted result was 0.3 because its random motion produced only six Sunny particles. Resampling introduces another source of variation.
The loop is therefore initialization, first-observation weighting and resampling, followed by repeated motion, weighting, and resampling. Before resampling, read weighted fractions; afterward, read counts. A step costs roughly for particles when state sampling and weighting have fixed cost. For two weather states, exact filtering is simpler. Particle methods become useful when a large or continuous state lacks an affordable compact exact filter.
Key Takeaways
- A particle is one sampled state; a population represents uncertainty.
- Initialize at X₁ and process its observation before moving.
- Later iterations sample motion, weight by evidence, and resample.
- Resampling is with replacement and produces equal-weight particles.
- Particle estimates vary because motion and resampling are random.
- Work scales with particle count when sampling and weighting costs stay fixed.
4.2 Accuracy, lost hypotheses, and filter choice
A particle estimate is random, so its quality depends on both population size and where the particles survive. More particles improve the approximation, but a large population can still be ineffective when nearly all its useful information sits in a few samples.
Understand the accuracy scale
For an independent-sample estimate of a probability , the standard error is approximately . With , this is about 0.046 for 100 samples and 0.0046 for 10,000. Particle-filter error often has the same rough scale, though resampled particles are dependent and model difficulty matters.
Quadrupling the population roughly halves error; doubling it does not. For a fixed observation history, increasing the number of particles makes a consistent particle filter approach the exact belief. This does not make one finite run exact or remove errors in the underlying model. Fix a random seed for reproducible comparisons, or compare results across several runs.
Distinguish two failures
| Failure | What goes wrong | What helps |
|---|---|---|
| Weight degeneracy | A few particles carry nearly all the weight. | Resampling concentrates effort on likely states. |
| Sample impoverishment | Many surviving particles are copies and plausible regions disappear. | More particles or ways to introduce new states can preserve diversity. |
Without resampling, multiplying likelihoods over many steps can leave almost every particle with negligible weight. Resampling replaces that waste with copies of useful states. But it can also erase an alternative location that temporarily fits less well.
Resampling alone cannot recreate an absent region. Recovery depends on motion samples reaching it or another mechanism introducing particles there. If transitions make that region nearly inaccessible, recovery may be slow. Adding small random perturbations or replacing a small fraction with fresh particles can help, but these choices must respect the state representation and intended approximation.
Handle zero total weight
If every particle receives weight zero, resampling probabilities are undefined. The observation may be possible elsewhere in the model even though the sampled population missed those states. Reinitialize from a suitable distribution, such as the prior or a uniform distribution over valid states, and check the sensor model. A nonzero outlier component can reduce these failures. If the model itself rules out the observation everywhere, more particles alone cannot fix it.
Choose a representation that fits the model
Exact forward filtering suits small discrete state spaces. A Kalman filter is exact when the prior is Gaussian and the transition and sensor models are linear with Gaussian noise; a mean and covariance then describe the belief. A particle filter accommodates nonlinear models and beliefs with separated peaks.
A single Gaussian cannot faithfully represent a robot that is likely in either of two distant corridors but unlikely between them. Particle clusters can retain both alternatives. For a linear-Gaussian tracking model, the Kalman representation usually avoids unnecessary sampling noise.
In a DBN, each particle holds a full assignment to all state variables. Sample next-step variables in topological order from their parent-conditioned models. Factoring reduces work per sample compared with enumerating every joint state, although high-dimensional beliefs may still require many particles to cover their important regions.
Key Takeaways
- Error often shrinks roughly with 1/√N, so halving it needs about four times the particles.
- Resampling counters concentrated weights but can reduce state diversity.
- A lost region needs motion or new-particle generation to return.
- Zero total weight makes resampling undefined and calls for recovery.
- Linear-Gaussian models with Gaussian priors have exact Kalman filters.
- Particle filters can represent separate peaks and factored state assignments.
5Tracking and sequence recognition
A robot locating itself and a recognizer labeling speech face the same underlying problem: observations leave several hidden explanations plausible. The models differ in what counts as a state, a transition, and a reading. Corridor localization shows how repeated motion and sensing preserve or resolve alternative positions, while speech and grammatical tagging show how sequence probabilities connect labels across time.
5.1 Tracking position while keeping alternatives
Tracking combines uncertain motion with noisy measurements. The hidden state may contain position and velocity; observations may come from GPS, radar, or a camera. Filtering carries a distribution of plausible locations from one reading to the next.
Localize in a five-cell corridor
A robot occupies one of five cells, with doors at cells 1 and 4. Its sensor reports a door with probability 0.9 at a door and 0.2 elsewhere. Start uniformly, with probability 0.2 per cell. A door report gives weights (0.18, 0.04, 0.04, 0.18, 0.04), totaling 0.48.
The updated belief is Both door cells remain plausible. Selecting just one peak would throw away the symmetry the sensor has not resolved.
Move the whole belief
The robot tries to move one cell right. It succeeds with probability 0.8 and stays with probability 0.2; from cell 5 it stays with certainty at the wall. Every cell receives contributions from all starting cells that can reach it.
Cell 1 gets . Cell 2 gets . Cells 3 and 4 get approximately 0.0833 and 0.1417. Cell 5 gets : both arrivals from cell 4 and all existing cell-5 mass remain there.
The prediction is approximately (0.0750, 0.3167, 0.0833, 0.1417, 0.3833). Handling the boundary as another ordinary 0.8 move would lose probability beyond the modeled corridor.
Observe no door
The no-door likelihood is 0.1 in cells 1 and 4 and 0.8 elsewhere. Multiplying the unrounded prediction gives total weight approximately 0.6483. Normalizing produces (0.0116, 0.3907, 0.1028, 0.0219, 0.4730).
The likely locations are now cells 2 and 5, just after the two doors. The belief remains multimodal, with separate peaks. One sensor reading is evidence, not a true-position measurement; keeping alternatives gives later motion and readings a chance to distinguish them.
Extend to realistic robots
In Monte Carlo localization, a particle is a pose: position in meters and heading. Move each pose using commanded motion plus noise, then weight it by agreement between observed ranges and ranges predicted from a known map. A concentrated initial population tracks a known starting location; a broad one supports global localization.
If the map is also unknown, include it in the hidden state. Simultaneous localization and mapping, or SLAM, estimates map and pose together. With multiple objects, another issue is data association: deciding which detection belongs to which object. Different assignments produce different trajectory hypotheses.
Vehicle tracking can combine a motion prediction with GPS readings. At 15 m/s with one-second steps, the expected motion is about 15 m between readings. A suitable Kalman model combines uncertain motion and measurement to reduce the effect of noisy readings. A transition model with no allowance for real motion variation can exclude the true trajectory, even when its arithmetic is correct.
Key Takeaways
- Tracking models hidden motion and noisy readings separately.
- Localizing keeps all plausible positions until evidence separates them.
- Boundary transitions must conserve probability within the state space.
- Monte Carlo localization represents robot poses with particles.
- SLAM estimates both pose and map; data association links readings to objects.
5.2 Speech and other sequence labels
Sequence models can infer labels as well as physical states. A speech recognizer connects a changing sound signal to possible words. A part-of-speech tagger connects observed words to hidden grammatical labels. Both must score choices in context across time.
Combine sound fit and language probability
Speech recognition seeks the word sequence with greatest posterior probability:
The acoustic model scores how well words explain the sound; the language model scores their prior plausibility. The shared denominator does not affect the ranking. An acoustic likelihood is not itself a posterior probability of words.
For illustrative scores, compare “recognize speech” with “wreck a nice beach.” Acoustic likelihoods are 0.0004 and 0.0005; language probabilities are 0.00002 and 0.000001. The first product is and the second . Language context makes the first phrase win despite its slightly lower acoustic likelihood.
Turn audio into a time sequence
A common setup uses overlapping 25 ms frames beginning every 10 ms, yielding about 100 feature vectors per second. The vectors are observations. Hidden states represent parts of speech sounds, or phones, often with beginning, middle, and end states. A pronunciation dictionary connects words to phones.
Self-loops allow a sound state to occupy multiple frames. Without duration flexibility, changing speaking speed would require a fixed and often unsuitable alignment between frames and sound states. Different state paths express different alignments of the same observed recording.
Represent short language context
A bigram model approximates a word sequence with . A trigram uses the previous two words. Estimate these conditional probabilities from text counts. The Markov assumption here is a practical approximation: long-range grammatical and semantic relationships can extend beyond one or two preceding words.
Viterbi can find the best state path through linked phone and word models. For a large vocabulary, beam search discards less promising partial paths to reduce work. Once discarded, a path cannot win later, so a narrow beam can miss the best full path. Also, the best single state path for a word sequence differs in objective from summing all its possible alignments.
Use the same structure for tags
In part-of-speech tagging, states are tags and observations are words. Transitions score ; emissions score . In “They can fish,” “can” may describe ability or putting fish into cans. The tag path must account for both word likelihoods and transitions between tags.
Place HMMs in speech practice
Large-vocabulary systems from the 1980s to the early 2010s commonly combined HMMs with Gaussian mixture acoustic models. Around 2010–2012, neural acoustic models became prominent in hybrid DNN–HMM systems. Modern end-to-end neural systems can map audio to text without an explicit HMM. The shared ideas of uncertain alignment, sequence scoring, and dynamic programming remain useful, and HMMs also appear in applications such as gene finding in DNA.
Key Takeaways
- Word recognition combines acoustic likelihood with a language prior.
- Frames provide observations; phone-state self-loops model variable duration.
- Bigram and trigram models approximate language with short histories.
- Viterbi finds a best path; beam pruning can sacrifice that guarantee.
- Part-of-speech tagging treats tags as hidden states and words as evidence.
- Modern speech systems include hybrid and end-to-end neural approaches.
Hidden Markov Models examples
1Predict weather and test equilibrium
13 steps
- 1IntroductionFrom daily changes to long-run balance
A weather forecast begins with what you know now and a rule for what can happen next. That is the Markov property: the current state is enough to predict the next one. The same rule can score a particular run of days or predict a whole distribution.
We will use Sunny and Cloudy states to follow both calculations. Then we will ask when repeated forecasts settle into a balance, a stationary distribution, and why a balanced distribution does not mean the weather has stopped changing.
- 2ExplanationRead the current state first
The Markov property says that knowing the current state makes earlier history unnecessary for predicting the next one. It does not make neighboring days independent.
A complete chain needs a starting distribution and transitions. If those transitions stay fixed, the chain is time-homogeneous. Its state distribution can still change: the fixed rule describes movement, not a fixed mix of states.
- 3ExampleTurn the weather rule into rows
Use the order Sunny, Cloudy for both rows and columns:
The Sunny row says “stay sunny with probability 0.8; switch cloudy with probability 0.2.” The Cloudy row gives 0.4 and 0.6. Each row describes every destination from one starting state and sums to 1. A column collects arrivals from different starting states, so it need not sum to 1.
- 4ExampleFollow one weather path
Suppose day 1 is certainly Sunny. For Sunny, Sunny, Cloudy, Cloudy, multiply the probability of each move in order:
This is the probability of that complete path. The two Cloudy days contribute different factors because one is a switch from Sunny and the other is a continuation from Cloudy.
- 5ChallengeCarry the right history
A process depends on the last two weather values. Its combined state today is (Sunny, Cloudy). What must be the first component of the next combined state, and why?
---reveal---
It must be Cloudy. The next pair stores (today, tomorrow), so its first component copies the current pair’s second component. State augmentation stores needed history while keeping a first-order transition rule.
- 6ExampleCollect every way to become sunny
Starting certainly Sunny gives day-2 belief (0.8, 0.2). Day 3 can become Sunny from either state:
Add these contributions to get 0.72. Cloudy receives . Thus the distribution is (0.72, 0.28). Multiplying along one path and adding across alternative paths are different operations.
- 7TipKeep the vector on the left
With our transition convention, a row belief advances as . Repeating gives .
Check that all entries are nonnegative and total 1. Putting a Sunny point-mass column on the right of this matrix gives (0.8, 0.4), which totals 1.2. Those entries describe two different starting states’ chances of becoming Sunny, not one belief’s distribution of destinations.
- 8ChallengePredict one more day
The day-3 belief is (0.72, 0.28). With Sunny and Cloudy transition rows (0.8, 0.2) and (0.4, 0.6), what is the sunny probability on day 4?
---reveal---
The cloudy probability is 0.312. Both current states contribute to tomorrow. A single simulated run would instead occupy just one state on day 4; many runs estimate this distribution.
- 9ExampleFind the distribution that stays balanced
At equilibrium, probability leaving Sunny for Cloudy matches probability returning:
The flow equation gives . Therefore and . Applying the matrix to this vector returns the same vector. Individual days still change; only the distribution is unchanged by the transition.
- 10Key InsightExistence is only the first question
Every finite chain has a stationary distribution. Irreducibility, meaning all states can reach each other, ensures uniqueness. In a finite irreducible chain, stationary probabilities also describe long-run time fractions.
Add aperiodicity to guarantee convergence from every start. Our weather matrix has every entry positive, satisfying both conditions. A chain with fixed transition rows alone need not converge.
- 11ChallengeA balanced vector without convergence
Two states always swap, and the chain starts certainly in the first. Does its distribution converge to the stationary vector (0.5, 0.5)?
---reveal---
No. Its distributions alternate (1, 0), (0, 1), (1, 0), and continue forever. Each state still occupies half the steps in a long run. This separates convergence of a time-specific distribution from the limiting fractions along a trajectory.
- 12ChallengeConnect prediction and equilibrium
A two-state chain starts at (0.3, 0.7), and both states are absorbing. What will repeated prediction do, and is the unchanged vector the only stationary distribution?
---reveal---
Prediction always returns (0.3, 0.7), because each state keeps its mass. Every mixture is stationary, including both point masses. This start has a limit, but the chain has no unique stationary distribution shared across all starts.
- 13RecapChoose the quantity before calculating
For a path, multiply its initial probability and transitions. For a distribution at one time, add all incoming contributions through matrix prediction.
For long-run behavior, solve the stationary equations and then check reachability and periodicity. The same chain can have a stationary vector, oscillating predictions, and well-defined time fractions. Keeping those questions separate gives each number a clear interpretation.
2Build a model for hidden weather
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionInfer what a sensor cannot show directly
- 2ExplanationSeparate motion from observation
- 3ExampleFill the solar sensor model
- 4ExampleScore states and readings together
- 5ChallengeDo observations become independent?
- 6ExplanationChoose what the state remembers
- 7ExampleLearn a row from labeled transitions
- 8ChallengeCount choices after normalization
- 9ChallengeA surprising but uninformative reading
- 10RecapMatch the model to the question
3Follow the solar evidence through time
20 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionOne recording, several inference questions
- 2ExampleProcess the first Low
- 3ExampleMove before the second Low
- 4ExampleLet High shift the odds
- 5ChallengeDiagnose a missing operation
- 6ExampleForecast the next state and output
- 7Key InsightKeep the scales you divided out
- 8ChallengeForecast without new evidence
- 9ExplanationSend later evidence backward
- 10ExampleRevise day 2
- 11ExampleContinue back to day 1
- 12ChallengeUse the right backward quantity
- 13ExplanationSwitch from all paths to one path
- 14ExampleFill the second Viterbi column
- 15ExampleChoose the final winner
- 16TipAvoid multiplying tiny scores
- 17ChallengeCompare path and state estimates
- 18ChallengeGive the winning path a posterior
- 19ConnectionChoose latency and memory deliberately
- 20RecapRead each result by its objective
4Run and diagnose a particle filter
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReplace a large table with samples
- 2ExplanationOne population, one belief
- 3ExampleSample the motion step
- 4ExampleWeight the sampled prediction
- 5ExampleDraw replacements with equal weights
- 6ChallengeCompare the exact calculation
- 7ExplanationKnow what more particles buy
- 8Key InsightWeights and diversity are different
- 9ChallengeHandle a zero weight total
- 10ConnectionChoose a compact exact belief when available
- 11ChallengePreserve a location alternative
- 12RecapCheck both count and coverage
5Apply temporal reasoning to robots and speech
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLocate a robot and label a sequence
- 2ExampleStart with two doors
- 3ExampleMove probability to the right
- 4ExampleLet the next reading favor cells past doors
- 5ChallengeAvoid committing before the sensor can decide
- 6ConnectionGive particles a pose and a map
- 7ExplanationTurn sound into evidence
- 8ExampleCombine acoustic fit with language context
- 9ExplanationConnect word and sound models
- 10ChallengeIdentify a tagger’s components
- 11ConnectionPlace the methods in modern speech systems
- 12ChallengeChoose what the application needs
- 13RecapName the hidden quantity and the evidence
Hidden Markov Models practice questions
Set 1: Particles and localization10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Combined reasoning and model diagnosis10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: States, transitions, and observations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Filtering, smoothing, and decoding10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Absorbing state
Acoustic model
Aperiodicity
B
Backpointer
Backward message
Balance equation
Baum–Welch algorithm
Beam search
Belief state
Bigram model
C
Consistency
D
Data association
Discretization
Dynamic Bayesian network
E
Evidence likelihood
Evidence sequence
F
Filtering
Fixed-lag smoothing
Forward algorithm
Forward–backward algorithm
Free parameter
H
Hidden Markov model
Hidden state
I
Importance weight
Irreducibility
K
Kalman filter
L
Language model
Likelihood ratio
Localization
Log-likelihood
Log-space decoding
Long-run time fraction
M
Marginal mode
Markov chain
Maximum-likelihood estimate
Mini-forward algorithm
Mixing time
Monte Carlo localization
Multimodal belief
N
Normalization
O
Observation forecast
Outlier component
P
Part-of-speech tagging
Particle
Particle filter
Phone
Pose
Prediction step
Pseudo-count
R
Reinitialization
Resampling
S
Sample impoverishment
Sensor model
Simulation
SLAM
Smoothing
State
State augmentation
State distribution
Stationary distribution
T
Time-homogeneity
Transition matrix
Trellis
Trigram model
V
Viterbi algorithm
W
Weight degeneracy
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.