Parameter Inference Using Maximum Likelihood
local graph
Chapter 4 — Parameter Inference Using Maximum Likelihood
Section titled “Chapter 4 — Parameter Inference Using Maximum Likelihood”In the previous chapter, we discussed the state inference in the case of a Hidden Markov Model (HMM). We tried to predict the next state for an HMM using the information of previous state transitions. But in each cases, we had assumed that we already knew the transition and emission probabilities of the model. But in real-life problems, we usually need to learn these parameters from our observations.
In this chapter, we will try to estimate the parameters of our HMM model through data gathered from observations. We will be covering the following topics:
- Maximum likelihood learning, with examples
- Maximum likelihood learning in HMMs
- Expectation maximization algorithms
- The Baum-Welch algorithm
Before diving into learning about maximum likelihood estimation (MLE) in HMMs, let’s try to understand the basic concepts of MLE in generic cases. As the name suggests, MLE tries to select the parameters of the model that maximizes the likelihood of observed data. The likelihood for any model with given parameters is defined as the probability of getting the observed data, and can be written as follows:
Here, D={D 1, D 2, D 3, …, D n } is the observed data, and θ is the set of parameters governing our model. In most cases, for simplicity, we assume that the datapoints are independent and identically distributed (IID). With that assumption, we can simplify the definition of our likelihood function as follows:
Here, we have used the multiplication rule for independent random variables to decompose the joint distribution into product over individual datapoint.
Coming back to MLE, MLE tries to find the value of θ for which the value of P(D|θ) is at a maximum. So, basically we now have an optimization problem at hand:
In the next couple of subsections, we will try to apply MLE to some simple examples to understand it better.
Let’s assume that we want to learn a model of a given coin using observations obtained from tossing it. Since a coin can only have two outcomes, heads or tails, it can be modeled using a single parameter. Let’s say we define the parameter as θ, which is the probability of getting heads when the coin is tossed. The probability of getting tails will automatically be 1-θ because getting either heads or tails are mutually exclusive events.
We have our model ready, so let’s move on to computing the likelihood function of this model. Let’s assume that we are given some observations of coin tosses as D={H,H,T,H,T,T}. For the given data we can write our likelihood function as follows:
Now, we would like to find the value of θ that would maximize P(D|θ). For that, we take the derivative of our likelihood function, equate it to 0, and then solve it for θ:
Therefore, our MLE estimator learned that the probability of getting heads on tossing the coin is 0.5. Looking at our observations, we would expect the same probability as we have an equal number of heads and tails in our observed data.
Let’s now try to write code to learn the parameter θ for our model. But as we know that finding the optimal value can run into numerical issues on a computer, is there a possible way to avoid that and directly be able to compute θ MLE? If we look closely at our likelihood equation, we realize that we can write a generic formula for the likelihood for this model. If we assume that our data has n heads and m tails, we can write the likelihood as follows:
Now, we can actually find θ MLE in a closed-form using this likelihood function and avoid relying on any numerical method to compute the optimum value:
We can see that we have been able to find a closed form solution for the MLE solution to θ. Now, coding this up would be to simply compute the preceding formula as follows:
import numpy as np
def coin_mle(data): """ Returns the learned probability of getting a heads using MLE.
Parameters ---------- data: list, array-like The list of observations. 1 for heads and 0 for tails.
Returns ------- theta: The learned probability of getting a heads. """ data = np.array(data) n_heads = np.sum(data)
return n_heads / data.sizeNow, let’s try out our function for different datapoints:
>>> coin_mle([1, 1, 1, 0, 0])0.59999999999999998
>>> coin_mle([1, 1, 1, 0, 0, 0])0.5
>>> coin_mle([1, 1, 1, 0, 0, 0, 0])0.42857142857142855The outputs are as we expect, but one of the drawbacks of the MLE approach is that it is very sensitive to randomness in our data which, in some cases, might lead it to learn the wrong parameters. This is especially true in a case when the dataset is small in size. For example, let’s say that we toss a fair coin three times and we get heads in each toss. The MLE approach, in this case, would learn the value of θ to be 1, which is not correct since we had a fair coin. The output is as follows:
>>> coin_mle([1, 1, 1])1.0In Chapter 5, Parameter Inference using Bayesian Approach, we will try to solve this problem of MLE by starting with a prior distribution over the parameters, and it modifies its prior as it sees more and more data.
In the previous section, we had a model with a single parameter. In this section, we will apply the same concepts to a slightly more complex model. We will try to learn the parameters of a normal distribution (also known as the Gaussian distribution) from a given observed data. As we know, the normal distribution is parametrized by its mean and standard deviation and the distribution is given as follows:
Here, µ is the mean and σ is the standard deviation of the normal distribution.
As we discussed earlier, for estimating parameters using MLE we would need some observed data, which, in this case, we are assuming to be coming from a normal distribution (or that it can be approximated using a normal distribution). Let’s assume that we have some observed data: X = {x 1, x 2,…,x N }. We want to estimate the parameters μ (mean) and σ 2 (variance) for our model.
We will follow the same steps as we took in the previous section. We will start by defining the likelihood function for the normal distribution. The likelihood is the probability of the data being observed, given the parameters. So, given the observed data, we can state the likelihood function as follows:
One issue that we usually run into while trying to work with the product of small numbers is that the number can get too small for the computer to work with. To avoid running into this issue, we instead work with the log-likelihood instead of the simple likelihood. Since log is an increasing function, the maximum of the log-likelihood function would be for the same value of parameters as it would have been for the likelihood function. The log-likelihood can be defined as follows:
We can then find the values of μ MLE and σ MLE that maximize the log-likelihood function by taking partial derivatives with respect to each of the variables, equating it to 0, and solving the equation. To get the mean value, we need to take the partial derivative of the log-likelihood function with respect to μ while keeping σ as constant, and set it to 0*,* which gives us the following:
Similarly, the MLE of standard deviation σ 2 can be computed by the partial derivative of the log-likelihood function with σ 2 while keeping μ constant, equating it to 0, and then solving for σ 2:
As we can see, we have again been able to derive a closed-form solution for the MLE and thus wouldn’t need to rely on numerical methods while coding it up. Let’s try to code this up and check if our MLE approach has learnt the correct parameters:
import numpy as np
def gaussian_mle(data): """ Returns the learned parameters of the Normal Distribution using MLE.
Parameters ---------- data: list, array-like The list of observed variables.
Returns ------- \mu: The learned mean of the Normal Distribution. \sigma: The learned standard deviation of the Normal Distribution. """ data = np.array(data) mu = np.mean(data) variance = np.sqrt(np.mean((data - mu)**2))
return mu, varianceWe have our learning function ready, so we can now generate some data from a known distribution and check if our function is able to learn the same parameters from the generated data:
>>> from numpy.random import normal>>> data = normal(loc=1, scale=2, size=10)>>> dataarray([ 1.8120102, 2.14363679, 1.49010868, -1.95531206, 1.62449155, 1.49345327, 1.48957918, -0.67536313, 4.31506202, 4.24883442])
>>> mu, sigma = gaussian_mle(data)>>> mu1.5986500906187573>>> sigma1.805051208889392In this example, we can see that the learned values are not very accurate. This is because of the problem with the MLE being too sensitive to the observed datapoints, as we discussed in the previous section. Let’s try to run this same example with more observed data:
>>> data = normal(loc=1, scale=2, size=1000)>>> data[:10]array([ 4.5855015, 1.55162883, -1.61385859, 0.52543984, 0.90247428, 3.40717092, 1.4078157, 0.01560836, -1.19409859, -0.01641439])
>>> mu, sigma = gaussian_mle(data)>>> mu 1.0437186891666821>>> sigma1.967211026428509In this case, with more data, we can see that the learned values are much closer to our original values.
Having a basic understanding of MLE, we can now move on to applying these concepts to the case of HMMs. In the next few subsections, we will see two possible scenarios of learning in HMMs, namely, supervised learning and unsupervised learning.
In the case of supervised learning, we use the data generated by sampling the process that we are trying to model. If we are trying to parameterize our HMM model using simple discrete distributions, we can simply apply the MLE to compute the transition and emission distributions by counting the number of transitions from any given state to another state. Similarly, we can compute the emission distribution by counting the output states from different hidden states. Therefore the transition and emission probabilities can be computed as follows:
Here, T(i,j) is the transition probability from state i to state j. And E(i,s) is the emission probability of getting state s from state i.
Let’s take a very simple example to make this clearer. We want to model the weather and whether or not it would rain over a period of time. Also, we assume that the weather can take three possible states:
- Sunny (S)
- Cloudy (C)
- Windy (W)
And the Rain variable can have two possible states; that it rained (R) or that it didn’t rain (NR). An HMM model would look something like this:
And let’s say we have some observed data for this which looks something like D={(S,NR), (S,NR), (C,NR), (C,R), (C,R), (W,NR), (S,NR), (W,R), (C,NR)}. Here, the first element of each datapoint represents the observed weatherthat day and the second element represents whether it rained or not that day. Now, using the formulas that we derived earlier, we can easily compute the transition and emission probabilities. We will start with computing the transition probability from S to S:
Similarly, we can compute the transition probabilities for all the other combinations of states:
And, hence, we have our complete transition probability over all the possible states of the weather. We can represent it in tabular form to look nicer:
| Sunny(S) | Cloudy(C) | Windy(W) | |
|---|---|---|---|
| Sunny(S) | 0.33 | 0.33 | 0.33 |
| Cloudy(C) | 0 | 0.66 | 0.33 |
| Windy(W) | 0.5 | 0.5 | 0 |
Table 1: Transition probability for the weather model
Now, coming to computing the emission probability, we can again just follow the formula derived previously:
Similarly, we can compute all the other values in the distribution:
And hence our emission probability can be written in tabular form as follows:
| Sunny(S) | Cloudy(C) | Windy(W) | |
|---|---|---|---|
| Rain (R) | 0 | 0.5 | 0.5 |
| No Rain (NR) | 1 | 0.5 | 0.5 |
Table 2: Emission probability for the weather model
In the previous example, we saw how we can compute the parameters of an HMM using MLE and some simple computations. But, because in this case we had assumed the transition and emission probabilities as simple discrete conditional distribution, the computation was much easier. With more complex cases, we will need to estimate more parameters than we did in the previous section in the case of the normal distribution.
Let’s now try to code up the preceding algorithm:
def weather_fit(data): """ Learn the transition and emission probabilities from the given data for the weather model.
Parameters ---------- data: 2-D list (array-like) Each data point should be a tuple of size 2 with the first element representing the state of Weather and the second element representing whether it rained or not. Sunny = 0, Cloudy = 1, Windy = 2 Rain = 0, No Rain = 1
Returns ------- transition probability: 2-D array The conditional distribution representing the transition probability of the model. emission probability: 2-D array The conditional distribution representing the emission probability of the model. """ data = np.array(data)
transition_counts = np.zeros((3, 3)) emission_counts = np.zeros((3, 2))
for index, datapoint in enumerate(data): if index != len(data)-1: transition_counts[data[index][0], data[index+1][0]] += 1 emission_counts[data[index][0], data[index][1]] += 1
transition_prob = transition_counts / np.sum(transition_counts, axis=0) emission_prob = (emission_counts.T / np.sum(emission_counts.T, axis=0)).T
return transition_prob, emission_probLet’s generate some data and try learning the parameters using the preceding function:
>>> import numpy as np>>> weather_data = np.random.randint(low=0, high=3, size=1000)>>> rain_data = np.random.randint(low=0, high=2, size=1000)>>> data = list(zip(weather_data, rain_data))>>> transition_prob, emission_prob = weather_fit(data)>>> transition_probarray([[ 0.3125, 0.38235294, 0.27272727], [ 0.28125, 0.38235294, 0.36363636], [ 0.40625, 0.23529412, 0.36363636]])
>>> emission_probarray([[ 0.3125, 0.38235294, 0.27272727], [ 0.28125, 0.38235294, 0.36363636], [ 0.40625, 0.23529412, 0.36363636]])In the previous section, we saw how we can use supervised learning in a case where we have all the variables observed, including the hidden variables. But that is usually not the case with real-life problems. For such cases, we use unsupervised learning to estimate the parameters of the model.
The two main learning algorithms used for this are the following:
- The Viterbi learning algorithm
- The Baum-Welch algorithm
We will discuss these in the next couple of subsections.
The Viterbi learning algorithm (not to be confused with the Viterbi algorithm for state estimation) takes a set of training observations O r, with 1≤r≤R, and estimates the parameters of a single HMM by iteratively computing Viterbi alignments. When used to initialize a new HMM, the Viterbi segmentation is replaced by a uniform segmentation (that is, each training observation is divided into N equal segments) for the first iteration.
Other than the first iteration on a new model, each training sequence O is segmented using a state alignment procedure which results from maximizing:
for 1<i<N where:
And the initial conditions are given by:
for 1<j<N. And, in the discrete case, the output probability is defined as:
where S is the total number of streams, v s (O st) is the output given, the input O st, and P js [v] is the probability of state j to give an output v.
If A ij represents the total number of transitions from state i to state j in performing the preceding maximizations, then the transition probabilities can be estimated from the relative frequencies:
The sequence of states that maximizes ∅ N (T) implies an alignment of training data observations with states. Within each state, a further alignment of observations to mixture components is made. Usually, two mechanisms can be used for this, for each state and each output stream:
- Use clustering to allocate each observation O st to one of M s clusters
- Associate each observation O st with the mixture component with the highest probability
In either case, the net result is that every observation is associated with a single unique mixture component. This association can be represented by the indicator function, which is 1 if is associated with a mixture component m of stream s of state j, and is zero otherwise.
The means and variances are then estimated by computing simple means:
And the mixture weights are based on the number of observations allocated to each component:
The expectation maximization (EM) algorithm (known as Baum-Welch when applied to HMMs) is an iterative method used to find the maximum likelihood or maximum a posteriori (MAP) estimates of parameters in statistical models, where the model depends on unobserved latent variables. The EM iteration alternates between performing an expectation (E) step, which creates a function for the expectation of the log-likelihood evaluated using the current estimate for the parameters, and a maximization (M) step, which computes parameters maximizing the expected log-likelihood found on the E step. These parameter estimates are then used to determine the distribution of the latent variables in the next E step.
The EM algorithm starts with initial value of parameters (θ old). In the E step, we take these parameters and find the posterior distribution of latent variables P(Z|X,θ old). We then use this posterior distribution to evaluate the expectation of the logarithm of the complete data likelihood function, as a function of the parameters θ, to give the function Q(θ,θ old), defined by the following:
Let’s introduce some terms that can help us in the future. γ(Z n) to denote the marginal posterior distribution of a latent variable:
ξ(z n-1, z n) denoting the marginal posterior distribution of two successive latent variables:
Thus, for each value of n, we can store γ(Z n) as a vector of K non-negative numbers that sum to 1, and, similarly we can use a K×K matrix of non-negative numbers that sum to 1 to save ξ(z n-1, z n).
As we have discussed in previous chapters, the latent variable z n can be represented as K dimensional binary variable where z nk = 1 when z n is in state k. We can also use it to denote the conditional probability of z nk = 1, and similarly ξ(z n-1, j, z nk) to denote the conditional probability of zn-1, j = 1, and z nk = 1. As the expectation of a binary random variable is just the probability of its value being 1, we can state the following:
As we discussed in the previous chapter, the joint probability distribution of an HMM can be represented as follows:
Thus we can write the data likelihood function as follows:
In the E step we try to evaluate the quantities γ(z n) and ξ(z n-1, z n) efficiently. For efficient computation of these two terms we can use either a forward backward algorithm or the Viterbi algorithm as discussed in the previous chapter. And in the M step, we try to maximize the value of Q(θ, θ old) with respect to the parameters θ={A, π, Φ} in which we treat γ(z n) and ξ(z n-1, z n) as constants.
In doing so, we get the MLE values of the parameters as follows:
If we assume the emission distribution to be a normal distribution such that, then the maximization of Q(θ, θ old) with respect to Φ k would result in the following:
The EM algorithm must be initialized by choosing starting values for π and A, which should, of course, be non-negative and should add up to 1.
The algorithms for parameter estimation look quite complex but hmmlearn, a Python package for working with HMMs, has great implementations for it. hmmlearn is also hosted on PyPI so it can be installed directly using pip:pip install hmmlearn. For the code example, we will take an example of stock price prediction by learning a Gaussian HMM on stock prices. This example has been taken from the examples page of hmmlearn.
For the example, we also need the matplotlib and datetime packages which can also be installed using pip:
pip install matplotlib datetimeComing to the code, we should start by importing all the required packages:
from __future__ import print_function
import datetime
import numpy as npfrom matplotlib import cm, pyplot as pltfrom matplotlib.dates import YearLocator, MonthLocator
try: from matplotlib.finance import quotes_historical_yahoo_ochlexcept ImportError: # For Matplotlib prior to 1.5. from matplotlib.finance import ( quotes_historical_yahoo as quotes_historical_yahoo_ochl )
from hmmlearn.hmm import GaussianHMM
print(__doc__)Next, we will fetch our stock price data from Yahoo! Finance:
quotes = quotes_historical_yahoo_ochl( "INTC", datetime.date(1995, 1, 1), datetime.date(2012, 1, 6))
# Unpack quotesdates = np.array([q[0] for q in quotes], dtype=int)close_v = np.array([q[2] for q in quotes])volume = np.array([q[5] for q in quotes])[1:]
# Take diff of close value. Note that this makes# \`\`len(diff) = len(close_t) - 1\`\`, therefore, other quantities also# need to be shifted by 1.diff = np.diff(close_v)dates = dates[1:]close_v = close_v[1:]
# Pack diff and volume for training.X = np.column_stack([diff, volume])Next, we define a Gaussian HMM model and learn the parameters for our data:
# Make an HMM instance and execute fitmodel = GaussianHMM(n_components=4, covariance_type="diag", n_iter=1000).fit(X)
# Predict the optimal sequence of internal hidden statehidden_states = model.predict(X)We can now print out our learned parameters:
print("Transition matrix")print(model.transmat_)print()
print("Means and vars of each hidden state")for i in range(model.n_components): print("{0}th hidden state".format(i)) print("mean = ", model.means_[i]) print("var = ", np.diag(model.covars_[i])) print()The output is as follows:
Transition matrix[[ 9.79220773e-01 2.57382344e-15 2.72061945e-03 1.80586073e-02] [ 1.12216188e-12 7.73561269e-01 1.85019044e-01 4.14196869e-02] [ 3.25313504e-03 1.12692615e-01 8.83368021e-01 6.86228435e-04] [ 1.18741799e-01 4.20310643e-01 1.18670597e-18 4.60947557e-01]]
Means and vars of each hidden state0th hidden statemean = [ 2.33331888e-02 4.97389989e+07]var = [ 6.97748259e-01 2.49466578e+14]
1st hidden statemean = [ 2.12401671e-02 8.81882861e+07]var = [ 1.18665023e-01 5.64418451e+14]
2nd hidden statemean = [ 7.69658065e-03 5.43135922e+07]var = [ 5.02315562e-02 1.54569357e+14]
3rd hidden statemean = [ -3.53210673e-01 1.53080943e+08]var = [ 2.55544137e+00 5.88210257e+15]We can also plot our hidden states over time:
fig, axs = plt.subplots(model.n_components, sharex=True, sharey=True)colours = cm.rainbow(np.linspace(0, 1, model.n_components))for i, (ax, colour) in enumerate(zip(axs, colours)): # Use fancy indexing to plot data in each state. mask = hidden_states == i ax.plot_date(dates[mask], close_v[mask], ".-", c=colour) ax.set_title("{0}th hidden state".format(i))
# Format the ticks. ax.xaxis.set_major_locator(YearLocator()) ax.xaxis.set_minor_locator(MonthLocator())
ax.grid(True)
plt.show()The output of the preceding code is as follows:

Figure 1: Plot of hidden states over time
In this chapter, we introduced algorithms for doing parameter estimation of a given HMM model. We started by looking into the basics of MLE and then applied the concepts to HMMs. For HMM training, we looked into two different scenarios: supervised training, when we have the observations for the hidden states, and unsupervised training, when we only have the output observations.
We also talked about the problems with estimation using MLE. In the next chapter, we will introduce algorithms for doing parameter estimation using the Bayesian approach, which tries to solve these issues.