Hidden Markov Models
local graph
Chapter 2 — Hidden Markov Models
Section titled “Chapter 2 — Hidden Markov Models”In the previous chapter, we discussed Markov chains, which are helpful in modelling a sequence of observations across time. In this chapter, we are going to study the Hidden Markov Model (HMM), which is also used to model sequential data but is much more flexible than Markov chains.
In this chapter, we will cover the following topics:
- Markov models
- The HMM
- Evaluation of an HMM
- Extensions of HMM
The Markov model is a stochastic model in which the state of the random variable at the next instance of time depends only on the outcome of the random variable at the current time. The simplest kind of Markov model is a Markov chain, which we discussed in Chapter 1, Introduction to Markov Process.
Suppose we have a set of sequential observations (x 1,…, x n) obeying the Markov property, then we can state the joint probability distribution for N observations as the following:

Graphical representation of a first-order Markov chain in which the distribution of the current observation is conditioned on the value of the previous observation
The preceding representation of the Markov chain is different from the representations we saw earlier. In this representation, the observations are presented as nodes and the edges represent conditional probability between two observations, namely Pr(x n |x n-1). This is how probabilistic graphical models are generally represented, where nodes represent random variables and edges represent a conditional probability distribution between these two variables. This graphical representation gives us insight into the causal relationships between random variables.
We can see that a simple Markov chain is very restrictive and does not work well for situations where we anticipate that several successive observations will provide important information required to predict the next observation. Fortunately, a Markov chain can be tweaked to support these cases as well:

Second-order Markov chain in which the distribution of the current observation is conditioned on the values of the last two observations
Let’s consider a Markov chain where the probability of the next state not only depends on the current state but also on the last state. This type of Markov chain is called a second-order Markov chain and the joint probability distribution can be represented as follows:
Using the d-separation property, we see that the conditional distribution of X n given X n-1 and X n-2 is independent of all observations, X 1,…, X n-3.
Similarly, we can extend this to an M th -order Markov chain in which the conditional distribution for a particular observation depends on the previous M observations. However, we are now paying the price of a large number of parameters for increased flexibility.
Suppose that the observations are discrete variables having K states. Then the conditional distribution, Pr(X n |X n-1),in a first-order Markov chain will be specified by a set of K-1 parameters for each of the K states of X n-1, giving a total of K(K-1) parameters. If we extend this to an M th -order Markov chain, where joint distribution is built up from conditionals, Pr(x n |x n-M,…, x n-1), the number of parameters in such a model would have K M-1 (K-1). Because this grows exponentially with M, it will often render this approach impractical for larger values of M. But, what if we want to build a model for sequential data that is not bounded by any order of Markov assumption, and yet it can be represented by a limited number of parameters?
Such models can be created by introducing latent (or hidden) variables. Latent variables allow us to create a rich class of models constructed out of simple components. Let’s assume that for each observation, x n, we have a latent variable, z n (which may or may not have the same dimensionality as the observed variable). If these latent variables form a first-order Markov chain, this type of model can be called a state space model, which is represented in the following diagram:

State space model representing a distribution, where each observation is conditioned upon a latent variable
Using the d-separation property, we can see that there is always a path between any two observed variables, x n and x m, via latent variables and this path can never be blocked. So the Pr(x n+1 |x 1,…, x n) distribution for observation x n+1 given all previous observations does not exhibit any conditional independence properties, and thus the prediction for x n+1 depends on all previous observations.
As the latent variables form a Markov chain, they satisfy the following conditional distribution:
Thus, the joint distribution of this model can be stated as follows:
An HMM is a specific case of state space model in which the latent variables are discrete and multinomial variables. From the graphical representation, we can also consider an HMM to be a double stochastic process consisting of a hidden stochastic Markov process (of latent variables) that we cannot observe directly, and another stochastic process that produces a sequence of the observation given the first process.
Before moving on to the parameterization, let’s consider an example of coin-tossing to get an idea of how it works. Assume that we have two unfaircoins, M 1 and M 2, with M 1 having a higher probability (70%) of getting heads and M 2 having a higher probability (80%) of getting tails. Someone sequentially flips these two coins, however, we do not know which one. We can only observe the outcome, which can either be heads (H) or tails (T):
We can consider the unfair coin selected to be the latent variable, and the outcome of the coin toss to be the observed data. To predict the next outcome sequence of observation, we would at least require information such as which coin was selected at first, the next coin to flip given the previous one, and the probability of getting H or T given the coin. Assuming that both of the coins have equal priority of getting selected at first and each coin is equally likely to get selected given the previous coin selected, we can create the following state diagram:

State diagram for coin toss HMM
In the previous diagram, z 1 and z 2 represent states of the latent variable coin selected *(*z 1 representing coin M 1 getting selected, and z 2 representing coin M 2 being selected). The arcs represent transition probabilities of moving from one state of latent variable to the other and the straight lines represent the probabilities of the observed variable (toss outcome) given the latent variable (coin selected).
In the previous section, we saw an example of an HMM to get an idea of how the model works. Let’s now formally parameterize an HMM.
As the latent variables of an HMM are discrete multinomial variables, we can use the 1-of-K encoding scheme to represent it, where the z n variable is represented by a K-dimensional vector of binary variables, z nk ∈ {0,1}, such that z nk = 1 and z nj = 0 for j ≠ k if the z n variable is in the k state.
With this in mind, we can create a matrix with the transition probability matrix A, where A ij = Pr(Z nj = 1| z n-1, i = 1). As the A ij represent the probability of moving from state i to state j, it holds the property of and can be expressed using the K(K-1) parameters. Thus we can represent the conditional probability distribution as follows:
The transition matrix is generally represented using a state-transition diagram, as we saw in Chapter 1, Introduction to Markov Process. But we can take the same representation and unfold it across time to get a lattice or trellis diagram, as presented in the following image. We will be using this representation of HMM in the following sections for learning parameters and making inferences from the model:

Trellis diagram for an HMM with latent variables with three states
As the initial latent node, z 1, does not have a parent node, it has a marginal distribution, Pr(z 1), which can be represented by a vector of probabilities, π, such that π k = Pr(z 1k = 1) with. Thus, the probability of Pr(z 1 |π) can be expressed as follows:
The third and final parameter required to parameterize an HMM is the conditional probability of the observed variable given the latent variable, namely the emission probability. It is represented by the conditional distribution, Pr(x n | z n, Φ), which is governed by some parameters, Φ. If the observed variable, x n, is discrete, the emission probability may take the form of a conditional probability table (multinomial HMM). Similarly, if the observed variable, x n, is continuous, then this distribution might be a Gaussian distribution (Gaussian HMM) where denotes the set of parameters governing the distribution, namely the mean and variance.
Thus, the joint probability distribution over both the latent and observed variables can be stated as follows:
Here, X = {x 1,…, x N }, Z = {z 1,…, z N } and θ = {A, π, Φ} denotes the set of parameters governing the model.
An HMM model is called a homogenous model when all the conditional distributions governing the latent variables share the same transition matrix, A, and all the emission probabilities share the same parameters, Φ.
Now, let’s try to code a simple multinomial HMM. We will start by defining a simple MultinomialHMM class and keep on adding methods as we move forward:
import numpy as np
class MultinomialHMM: def __init__(self, num_states, observation_states, prior_probabilities, transition_matrix, emission_probabilities): """ Initialize Hidden Markov Model
Parameters ----------- num_states: int Number of states of latent variable observation_states: 1-D array An array representing the set of all observations prior_probabilities: 1-D array An array representing the prior probabilities of all the states of latent variable transition_matrix: 2-D array A matrix representing the transition probabilities of change of state of latent variable emission_probabilities: 2-D array A matrix representing the probability of a given observation given the state of the latent variable """ # As latent variables form a Markov chain, we can use # use the previous defined MarkovChain class to create it self.latent_variable_markov_chain = MarkovChain( transition_matrix=transition_matrix, states=['z{index}'.format(index=index) for index in range(num_states)], ) self.observation_states = observation_states self.prior_probabilities = np.atleast_1d(prior_probabilities) self.transition_matrix = np.atleast_2d(transition_matrix) self.emission_probabilities = np.atleast_2d(emission_probabilities)Using the MultinomialHMM class, we can define the HMM coin that we discussed previously as follows:
coin_hmm = MultinomialHMM(num_states=2, observation_states=['H', 'T'], prior_probabilities=[0.5, 0.5], transition_matrix=[[0.5, 0.5], [0.5, 0.5]], emission_probabilities=[[0.8, 0.2], [0.3, 0.7]])For a given HMM parameterized by {A, π, Φ}, we can generate a sequence of observations, {x 1,…, x N }, using the following steps:
- Set n = 1
- Choose an initial state of the latent variable, z 1, according to the prior distribution, π
- Choose an observation, x 1, for the given value of z 1, by sampling the emission-probability distribution governed by Φ
- Transit to the next state of the latent variable, z n+1, according to the state-transition probability matrix, A
- Set n = n + 1 and repeat step 3 if n ≤ N, otherwise terminate
We can add a method to generate samples in the previously defined MultinomialHMM class, as follows:
def observation_from_state(self, state): """ Generate observation for a given state in accordance with the emission probabilities
Parameters ---------- state: int Index of the current state """ state_index = self.latent_variable_markov_chain.index_dict[state] return np.random.choice(self.observation_states, p=self.emission_probabilities[state_index:])
def generate_samples(self, no=10): """ Generate samples from the hidden Markov model
Parameters ---------- no: int Number of samples to be drawn
Returns ------- observations: 1-D array An array of sequence of observations
state_sequence: 1-D array An array of sequence of states """ observations = [] state_sequence = []
initial_state = np.random.choice(self.latent_variable_markov_chain.states, p=self.prior_probabilities)
state_sequence.append(initial_state) observations.append(self.observation_from_state(initial_state))
current_state = initial_state for i in range(2, no): next_state = self.latent_variable_markov_chain.next_state(current_state) state_sequence.append(next_state) observations.append(self.observation_from_state(next_state)) current_state = next_state
return observations, state_sequenceWe can use the generate_samples method on our HMM coin example to generate an observation sequence:
>>> coin_hmm.generate_samples()(['T', 'H', 'H', 'T', 'T', 'H', 'H', 'H', 'H'], ['z1', 'z0', 'z0', 'z1', 'z1', 'z0', 'z1', 'z1', 'z1'])HMM can also have a Gaussian distribution for the emission probability. Just like MultinomialHMM, we can also sample from GaussianHMM. In the next code example, we use the GaussianHMM class provided in the hmmlearn library to see how the samples are generated from this type of model:
source activate hmmconda install scikit-learnpip install hmmlearnOnce the Python packages are installed, we can use the following code to generate samples from Gaussian HMM:
from hmmlearn.hmm import GaussianHMMimport numpy as npimport matplotlib.pyplot as plt
startprob = np.array([0.6, 0.3, 0.1, 0.0])# The transition matrix, note that there are no transitions possible# between component 1 and 3transmat = np.array([[0.7, 0.2, 0.0, 0.1], [0.3, 0.5, 0.2, 0.0], [0.0, 0.3, 0.5, 0.2], [0.2, 0.0, 0.2, 0.6]])# The means of each componentmeans = np.array([[0.0, 0.0], [0.0, 11.0], [9.0, 10.0], [11.0, -1.0]])# The covariance of each componentcovars = .5 * np.tile(np.identity(2), (4, 1, 1))
# Build an HMM instance and set parametersmodel = hmm.GaussianHMM(n_components=4, covariance_type="full")
# Instead of fitting it from the data, we directly set the estimated# parameters, the means and covariance of the componentsmodel.startprob_ = startprobmodel.transmat_ = transmatmodel.means_ = meansmodel.covars_ = covars
X, state_sequence = model.sample(n_samples=100)
plt.plot(X[:, 0], X[:, 1], ".-", label="observations", ms=6, mfc="orange", alpha=0.7)for i, m in enumerate(means): plt.text(m[0], m[1], 'Component %i' % (i + 1), size=12, horizontalalignment='center', bbox=dict(alpha=.7, facecolor='w'))plt.legend(loc='best')plt.show()
Sampling from an HMM with a four-state latent variable, z, and a Gaussian emission model, p(x|z)
In the previous section, we discussed generating an observation sequence of a given HMM. But, in reality, most of the time we are not interested in generating the observation sequence, mostly because we don’t know the parameters of the HMM to generate observations in the first place.
For a given HMM representation, in most of the applications, we are always trying to address the following three problems:
- Evaluation of the model: Given the parameters of the model and the observation sequence, estimating the probability of the sequence
- Predicting the optimal sequence: Given the parameters of the model and the observation sequence, estimating the most probable sequence of the state sequence that had produced these observations
- Parameter-learning: Given a sequence of observations, estimating the parameters of the HMM model that generated it
In this section, we’ll discuss the first problem, the evaluation of the model, and in the following chapters, we will discuss the other two problems in detail. As we will see in the later chapters, evaluating the model forms the basis for solving the other two problems. Thus, solving this problem efficiently is the first stepping stone toward parameter-learning and inference.
Let’s formally describe the problem of model evaluation. Given an HMM parameterized by θ = {A, π, Φ} and an observation sequence, X = {x 1,…, x N }, we need to compute the probability of Pr(X|θ). From our discussions in the previous section, we can say that we can compute Pr(X|θ) by marginalizing the joint-probability distribution Pr(X, Z|θ), where Z = {z 1,…, z N }, with respect to Z:
In the previous section, we saw that the following is true:
Thus the Pr(X, Z|θ) probability can be stated as follows:
For a model with K states and an observation length of N, there are K T possible state sequences. Each term in the summation requires 2N operations. As a result, the evaluation becomes a mathematical operation of the order of 2N X K T. For example, if we consider a model with five states, K = 5, and an observation sequence of length N = 100, the number of required operations is of the order of 10 72, which makes this method of evaluation intractable even for a very small HMM.
In the previous sections, we discussed HMM, sampling from it and evaluating the probability of a given sequence given its parameters. In this section, we are going to discuss some of its variations.
Let’s consider the problem of modelling of several objects in a sequence of images. If there are M objects with K different positions and orientations in the image, there are be K M possible states for the system underlying an image. An HMM would require K M distinct states to model the system. This way of representing the system is not only inefficient but also difficult to interpret. We would prefer that our HMM could capture the state space by using M different K -dimensional variables.
A factorial HMM is such a representation. In this model, there are multiple independent Markov chains of latent variables and the distribution of the observed variable at any given time is conditional on the states of all the corresponding latent variables in that given time. The graphical model of the system can be represented as follows:

A factorial HMM comprising two Markov chains
The motivation for considering factorial HMM can be seen by noting that in order to represent, say, 10 bits of information at a given time step, a standard HMM would need K = 2 10 = 1024 latent states, whereas a factorial HMM could make use of 10 binary latent chains. However, this presents additional complexity in training, as we will see in the later chapters.
In the previous section, we discussed factorial HMM, in which the latent variables formed independent Markov chains. This independence assumption about the latent variables can be relaxed by introducing some coupling between them. One way to couple latent variables is to order them such that depends on for all 1 ≤ l ≤ m. Furthermore, if all the output variables and the latent variables depend on some random input variable, x n, we obtain a tree-structured HMM represented as follows:

Graphical representation of a tree-structured HMM
The architecture of this model can be interpreted as a probabilistic decision tree. Let’s considered at first-time slice n=1, and try to understand how this model would generate data. Based on the value of x 1, the top node,, can take K values (assuming that the hidden variables have K states). This partitions the x space into K decision groups. The next node,, further partitions into K subregions, and so on. The output, y 1, is generated from the input, x 1, and K-way decisions at each node. At the next time slice, the same thing is going to happen, expect that each decision in the tree depends on the decision taken at that node in the previous time slice. Therefore, this model can be interpreted as a probabilistic decision tree with Markovian dynamics.
In this chapter, we got a detailed introduction to Markov model and HMM. We talked about parameterizing an HMM, generating samples from it, and their code. We discussed estimating the probability of observation, which would form the basis of inference, which we’ll cover in the next chapter. We also talked about various extensions of HMMs.
In the next chapter, we will take an in-depth look at inference in HMMs.