Skip to content
ImagineWorld

State Inference – Predicting the States

node_idnode-book_markov-models-with-python_chapter-03-state-inference-predicting-the-states
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleState Inference – Predicting the States
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — State Inference – Predicting the States

Section titled “Chapter 3 — State Inference – Predicting the States”

In the previous chapters, we introduced Markov chains and the Hidden Markov Model (HMM), and saw examples of modeling problems using them. In this chapter, we will see how we can make predictions using these models or ask the models questions (known as inference). The algorithms used for computing these values are known as inference algorithms. In this chapter, we will specifically look into computing probability distribution over the state variables.

This chapter will cover the following topics:

  • State inference in HMM
  • Dynamic programming
  • Forward-backward algorithm
  • Viterbi algorithm

Let’s start with a simple example to show what kind of interesting questions we can ask our HMM models. We are taking an example of robot localization. There are a lot of variations of this example, but we are assuming that a robot is moving in a 2D grid, as shown in Figure 3.1. The robot also has four sensors on it. Each of these sensors detects whether there’s a wall right next to the robot in the sensor’s direction.

We would like to model the movement of the robot in the following grid along with the observations from our sensors:

Figure 3.1: The probability distribution of the position of the robot over time

In Figure 3.1, we see how the observations at different time instances change the probability of the location of the robot in the grid. Initially, we start with a uniform probability over all the positions in the grid. Now, at time t=1, let’s say the sensors of our robot show that there are walls on the top and bottom sides. Having this observation will change our perception of the location of the robot. Now we will have a higher probability of the robot being in either blocks 2, 4, 10, or 12, as shown in the second block in Figure 3.1. If we are at time instance t=2, our robot’s sensors say that there is a wall only at the top, we will have the highest probability of it being in block 3, as shown in the third block in Figure 3.1. This is because we knew its last most probable position and, when combining that information with the current sensor readings, block 3 is the robot’s likely location. Now, if we are at time t=3, the robot’s sensors indicate there are walls on the left and right, then it would mean that the robot is most likely in in block 7. This process enables us able to locate the position of our robot in the grid based on just the sensor readings over time.

Since we are modelling the transition of state (position in the grid) of the robot over some duration of time along with an outcome at each instance (sensor output), HMM seems to be the perfect model in the situation. In this example, we are assuming that we know the transition probability of the robot’s position. We are also assuming that we know the structure of the grid and therefore we will know the emission probabilities. We can use the emission probability to also model the uncertainty in the output of the sensors since they might give noise results at some instance:

Figure 3.2: An example HMM for the robot localization

Now let’s think about the kind of questions we might want to ask our model. We might be interested in knowing the position of our robot at any time instance given all the observations till that time instance. Another question that we might want to ask is the probability of our sensor output at some time instance given all the positions of the robot until that time instance. We might also be interested in computing the joint distribution over our observed variables and the position of the robot. All these values can be easily computed using the forward algorithm, backward algorithm, or forward-backward algorithm.

Now, instead of asking for distributions, we might be interested in the most probable path the robot took. To compute the most probable path, we would need to do a MAP inference over the state at each time instance of the robot. This can be done efficiently using the Viterbi algorithm.

In the following sections, we will introduce these algorithms formally and see how we can implement them. All of these algorithms rely on a very important programming paradigm known as dynamic programming*.* Dynamic programming allows us to run these inference algorithms in HMMs in tractable time. We will discuss dynamic programming in detail in the next section.

Dynamic programming is a programming paradigm in which we divide a complex problem into smaller sub-problems. We solve these sub-problems and store the results. Whenever we need to recompute the same sub-problem again, we just used our stored results, thus saving us computation time at the expense of using storage space. This technique of caching the results of sub-problems is known as memoization*.* Therefore, using dynamic programming allows us to speed up our computations by using memoization, and in some cases, it can bring the computational complexity from exponential to linear, as we will see in the following example.

One of the simplest examples of optimization using dynamic programming is computing the n th member of the Fibonacci sequence. Any term in a Fibonacci sequence is the sum of the last two terms, which can be formally defined as follows:

fib(0)=0

fib(1)=1

fib(n)=fib(n-1)+fib(n-2)

Here, fib(n) represents the n th number in the Fibonacci sequence. From the definition, we can easily compute the Fibonacci sequence as: 0, 1, 1, 2, 3, 5, 8, 13.

Now let’s say we want to write a function which would return the n th number in the Fibonacci sequence. A simple way to write this function could be to use recursion, as shown in the following code:

def fibonacci(n):
"""
Returns the n-th number in the Fibonacci sequence.
Parameters
----------
n: int
The n-th number in the Fibonacci sequence.
"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

In the preceding code, we have a simple if… else condition, where if n is less than or equal to 1, we return the value of n; otherwise, we use recursion to compute the sum of the previous two numbers in the sequence. Now let’s try to determine the number of calls to the fibonacci function for a small n, let’s say 5. Our function calls would look something like the following:

fibonacci(5) = fibonacci(4) + fibonacci(3)
fibonacci(5) = (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
fibonacci(5) = ((fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0))) + ((fibonacci(1) + fibonacci(0)) + fibonacci(1))
fibonacci(5) = (((fibonacci(1) + fibonacci(0)) + fibonacci(1)) + (fibonacci(1) + fibonacci(0))) + ((fibonacci(1) + fibonacci(0)) + fibonacci(1))

For such a small value of n, we can still see the repetition in the number of calls to the function with the same argument. We can see that fibonacci(1) is being called five times and fibonacci(0) is getting called three times. If we move a level up, we can see that fibonacci(2) is also getting called multiple times. In this case, the computation is still tractable, but for large values of n the run time of this function would grow exponentially; the runtime complexity is given by O(2 n). To give an idea of how fast the runtime grows, to compute the 1,000 th term in the Fibonacci sequence using this algorithm, we would need more time than the age of our universe on a computer built with all the electrons in our observable universe.

Since we have proved that it is impossible to compute the n th term of the Fibonacci sequence for any moderately large n, we will look at another algorithm that is based on dynamic programming and looks as follows:

cache = {0: 0, 1: 1} # Initialize the first two values.
def fibonacci(n):
"""
Returns the n-th number in the Fibonacci sequence.
Parameters
----------
n: int
The n-th number in the Fibonacci sequence.
"""
try:
return cache[n]
except KeyError:
fib = fibonacci(n-1) + fibonacci(n-2)
cache[n] = fib
return fib

In this case, we are storing the result of each of our calls to the function in a dictionary, which allows us to access it in O(1). Because of this cache, we only need to compute each term of the Fibonacci sequence exactly once. For each call, we first check whether we have already computed the value. If we have already computed it, we directly access it from the dictionary, otherwise we compute the value. The runtime complexity of this algorithm is O(n) since we are computing each term in the sequence exactly once. We can see, therefore, that using dynamic programming facilitates a trade-off between the runtime complexity and memory complexity, and this allows us to bring down the runtime complexity from being exponential to linear.

If we think about the way we have programmed the Fibonacci series, we start with trying to compute the n th number and then compute the values we are missing. This can be thought of as a top-down approach. Another approach could be a bottom-up approach, in which we start by computing the 0th term and then move to the first, second, and so on. The concept of dynamic programming is the same in both cases, but with just a minor difference in how we write the code, shown as follows:

cache = [0, 1] # Initialize with the first two terms of Fibonacci series.
def fibonacci(n):
"""
Returns the n-th number in the Fibonacci sequence.
Parameters
----------
n: int
The n-th number in the Fibonacci sequence.
"""
for i in range(2, n):
cache.append(cache[i-1] + cache[i-2])
return cache[-1]

As you can see, the code in the preceding example is much simpler, and we don’t need to check whether we have already computed the values. This works well in problems where we need all the previous values to compute the next value. However, if we don’t need all the previous values, we will end up computing unnecessary values with the bottom-up approach.

We will see in the next sections that the inference algorithms in HMMs allow us to use dynamic programming to break the problem into sub-problems, which makes computations tractable.

Let’s now formally define our problem for the forward algorithm. In the case of the forward algorithm, we are trying to compute the joint distribution of the position of the robot at any time instance using the output of the sensors till that time instance, as shown in the following diagram:

Forward algorithm: P(Z k, X 1:k)

Figure 3.3: HMM showing two time slices, k-1 and k

To compute this probability distribution, we will try to split the joint distribution term into smaller known terms. As we will see, we can write a recursion formula over time for the distribution. We start by introducing a new variable, Z k-1, in the distribution, P(Z k, X 1:k), as follows:

The marginalization rule of probability is:

The product rule of probability is:

Here, we are basically using the marginalization rule of probability to introduce Z k-1 and then summing its states. In this case, we have assumed that Z k-1 has m states, so now we can use the product rule of probability to split this term as follows:

In the last chapter, we saw how the d-separation property of HMM can make variables independent from each other. Here, we will apply some of those conditions to simplify our terms in the preceding equation. As we know that, given the hidden state, the observation is independent of all the terms in previous time instances, we also know:. Applying this to the first term of our preceding equation, we can write it as the following:

Similarly, we know that the current hidden state is dependent on the last hidden state and is independent of hidden states before that. Hence, in this case, the formula is. Using this property, we can write our second term in the equation as follows:

Now, if we compare our last term with the term we were trying to compute, we should see there is a similarity between them. Let’s define a new function, α, as follows:

Now we can rewrite our original equation as the following:

So, we now have a nice recursive equation and we are familiar with all the terms in the equation. The first term, P(X k |Z k), is the emission probability of the HMM. The second term of the equation, P(Z k |Z k-1), is the transition probability and is also known. Now we can focus on solving this recursive equation. When solving any recursive equation, we need to know at least one of the values, so we can start computing consecutive terms. In this case, we know the value of α(1), which is given as follows:

Here, P(Z 1) is the initial probability of the position of the robot, which we know, and P(X 1 |Z 1) is the emission probability of HMM, which is also known. Using these two values, we can compute the value of α(1). Once we have the value of α(1), we can use our recursive equation to compute all the α values.

Now let’s talk about the computational complexity of this algorithm to see whether the inference is tractable. As we can see in the equation for computing each α, we are doing a sum over all the states of Z k-1, and we have assumed that it has m states; for each one of these steps, we do m multiplications for computing P(X k |Z k)P(Z k |Z k-1)α(k-1). Therefore, to compute the next α, we do m 2 computations. If we want to compute α(n), we will need nm 2 computations, which gives us the computational complexity of the algorithm as O(nm 2).

Let’s now try to write the code for our robot localization problem to compute the joint distribution using the forward algorithm. For simplicity, let’s assume that we have only one sensor on the robot that checks whether there is a wall on the left-hand side of the robot. To define the model, we mainly need two quantities: the transition matrix and the emission matrix. In our example, we assume that the robot can either stay at its original position or move a block in any possible direction in any given time instance. Therefore, if the robot is at position 1 at any given time, it can be in positions 1, 2, or 6 at the next time instance with equal probabilities of 0.33.

In this way, we can write the transition probability from state 1 as:

In a similar way, we can write the transition probabilities, P(Z t+1 |Z t), from each of the position, and we will get the following transition matrix:

import numpy as np
transition_matrix = np.array([[0.33, 0.33, 0, 0, 0, 0.33, 0, 0, 0, 0, 0, 0, 0],
[0.33, 0.33, 0.33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0.25, 0.25, 0.25, 0, 0, 0.25, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0.33, 0.33, 0.33, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0.33, 0.33, 0, 0, 0.33, 0, 0, 0, 0, 0],
[0.33, 0, 0, 0, 0, 0.33, 0, 0, 0.33, 0, 0, 0, 0],
[ 0, 0, 0.33, 0, 0, 0, 0.33, 0, 0, 0, 0.33, 0, 0],
[ 0, 0, 0, 0, 0.33, 0, 0, 0.33, 0, 0, 0, 0, 0.33],
[ 0, 0, 0, 0, 0, 0.33, 0, 0, 0.33, 0.33, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0.33, 0.33, 0.33, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.33, 0.33, 0.33, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.33, 0.33, 0.33],
[ 0, 0, 0, 0, 0, 0, 0, 0.33, 0, 0, 0, 0.33, 0.33]])

Coming to the emission probability in this problem, P(X t |Z t), we should have the emission probability of 1 for the states that have a wall on their left. Hence, the emission probability would be as follows:

emission = np.array([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])

However, as we don’t know the position of our robot at t=0, we will assume that it has a uniform distribution over all the possible states. Therefore, the initial probability, P(Z 0), can be written as follows:

init_prob = np.array([0.077, 0.077, 0.077, 0.077, 0.077, 0.077, 0.077,
0.077, 0.077, 0.077, 0.077, 0.077, 0.077])

With these values in hand, we should be able to run the forward algorithm, but before that, we need to code up the algorithm, as follows:

def forward(obs, transition, emission, init):
"""
Runs forward algorithm on the HMM.
Parameters
----------
obs: 1D list, array-like
The list of observed states.
transition: 2D array-like
The transition probability of the HMM.
size = {n_states x n_states}
emission: 1D array-like
The emission probability of the HMM.
size = {n_states}
init: 1D array-like
The initial probability of HMM.
size = {n_states}
Returns
-------
float: Probability value for the obs to occur.
"""
n_states = transition.shape[0]
fwd = [{}]
for i in range(n_states):
fwd[0][y] = init[i] * emission[obs[0]]
for t in range(1, len(obs)):
fwd.append({})
for i in range(n_states):
fwd[t][i] = sum((fwd[t-1][y0] * transition[y0][i] * emission[obs[t]]) for y0 in
range(n_states))
prob = sum((fwd[len(obs) - 1][s]) for s in range(n_states))
return prob

We can try to compute the probability by running it over some observations, as follows:

>>> obs = [0, 0, 0, 0] # Staying in the same location
>>> forward(obs, transition_matrix, emission, init_prob)
0.97381776799999997
>>> obs = [0, 10, 8, 6] # Should be 0 because can't jump from state 0 to 10.
>>> forward(obs, transition_matrix, emission, init_prob)
0.0

Using the forward algorithm, we have been able to compute the value of P(Z x, X), so we might be tempted to think that we will easily be able to compute the conditional distribution P(Z k, X) using the following product rule:

Computing the distribution, P(X) however, is computationally intractable, as we will see. We can express P(Z k, X) as follows:

And hence we can compute P(X) as the following:

If we look at the computational complexity of computing P(X) using the preceding equation, it is O(m n), which is intractable for any sufficiently large value of m and n. And hence it is impossible to compute the conditional distribution of our hidden state using just the forward algorithm. In the next sections, we will introduce the backward algorithm and then we will show you how can we compute these conditional distributions.

Let’s formally define the problem statement for the backward algorithm. In this case, we are trying to compute the probability of observation variables given the current state:

Backward algorithm: P(X k+1:n |Z k)

Figure 3.4: HMM showing two time slices, k and k+1

Similar to what we did in the case of the forward algorithm, we will again try to convert this probability term into a recursive equation in terms of known distributions, so that we can recursively compute the probabilities at different time instances. First, we introduce a new term, Z k+1 in P(X k+1:n |Z k), using the marginalization rule:

Here, we are marginalizing over the Z k+1 variable by summing over all of its possible states, which we have assumed to be m. Now, we can use the product rule of probability to split the preceding equation as:

Now, from the d-separation property of our model, we know that. Also, we know from the definition of HMMs that. Using these independent conditions, we can write our equation as:

Now, the terms in our equation look familiar. The second term is the emission probability and the last term is the transition probability of our HMM. Now, to express it as a recursion, let’s define a new function, β, given as:

We can use β in the previous equation to represent it as a recursion:

Now, since we have the recursive equation, we can start computing the different values of β k. But for computing the values, we will need to know at least one term of the recursion, so let’s compute the value of β(1):

def backward(obs, transition, emission, init):
"""
Runs backward algorithm on the HMM.
Parameters
----------
obs: 1D list, array-like
The list of observed states.
transition: 2D array-like
The transition probability of the HMM.
size = {n_states x n_states}
emission: 1D array-like
The emission probabilitiy of the HMM.
size = {n_states}
init: 1D array-like
The initial probability of HMM.
size = {n_states}
Returns
-------
float: Probability value for the obs to occur.
"""
n_states = transition.shape[0]
bkw = [{} for t in range(len(obs))]
T = len(obs)
for y in range(n_states):
bkw[T-1][y] = 1
for t in reversed(range(T-1)):
for y in range(n_states):
bkw[t][y] = sum((bkw[t+1][y1] * transition[y][y1] * emission[obs[t+1]]) for y1 in
range(n_states))
prob = sum((init[y] * emission[obs[0]] * bkw[0][y]) for y in range(n_states))
return prob

We can run this algorithm also on the same observations to see whether the results were correct:

>>> obs = [0, 0, 0, 0] # Staying in the same location
>>> backward(obs, transition_matrix, emission, init_prob)
0.97381776799999997
>>> obs = [0, 10, 8, 6] # Should be 0 because can't jump from state 0 to 10.
>>> backward(obs, transition_matrix, emission, init_prob)
0.0

Coming to the forward-backward algorithm, we are now trying to compute the conditional distribution of the hidden state given the observations.

Taking the example of our robot localization, we are trying to now find the probability distribution of the robot’s position at some time instance given the sensor readings:

Forward-backward algorithm: P(Z k |X)

Figure 3.5: HMM showing three time slices, k-1, k, and k+1

Now, since we have been given all the observed variables in the model, we can say that the value of P(Z k |X) is going to be proportional to the joint distribution over Z k and X:

Now, we know that we can write X={X 1:k, X k+1:n }. Replacing this in the preceding equation, we get:

We can apply the chain rule in the preceding equation to write it as:

From our model structure, we know that, and using this independence property we can write the preceding equation as:

Now if we look at the preceding terms, the first term is P(X k+1:n |Z k), which is what we computed in our backward algorithm. The second term is P(Z k, X 1:k), which we computed in the case of the forward algorithm. So for computing P(Z k| X), we can compute both the terms using the forward and the backward algorithm. But since P(Z k| X) is proportional to the product of these two terms, we will need to normalize the distribution.

So far, we have been trying to compute the different conditional and joint probabilities in our model. But one thing that we can’t do with the forward-backward algorithm is find the most probable state of the hidden variables in the model given the observations. Formally, we can write this problem as, we know the observed variable, the transition probabilities and the emission probability of the network and we would like to compute Z *, which is defined as:

Where,

Z={Z 1, Z 2, …, Z n }

And,

X={X 1, X 2, …, X n }

Properties of operations on probability distributions: When we do operations on the probability distributions (marginalization, maximization, and so on), we can push in the operation through the independent terms of the distribution. We can see these examples in the case of marginalization and argmax:

Figure 3.6: HMM showing three time slices k-2, k-1, and k

Since we saw that P(Z|X)∝ P(Z, X), and since we are trying to compute the argmax, it wouldn’t matter if we compute on either of these two terms. And hence we can say that:

Now, we will again try to formulate our equation as a recursion so that it is easier for us to compute. So, let’s introduce a new term, µ(k), defined as:

And again, we will try to break this term into known terms. Using the chain rule, we can write it as:

Now, we start pushing in the argmax argument using the property (see information box for details). And this gives us:

These terms look familiar, P(X k |Z k) is the emission probability, P(Z k |Z k-1) is the transition probability, and is µ(k-1). So now we have a recursive equation to work with:

Since we have the recursive formula, we can compute the values for any k if we have the first term. So, let’s look at the first term of the recursion, which is µ(1):

Here, the first term is P(Z 1), which is our initial probability, which is known. The second term is P(X 1 |Z 1), which is the emission probability of our model:

import numpy as np
def viterbi(obs, transition, emission, init=None):
"""
Return the MAP estimate of state trajectory of Hidden Markov Model.
Parameters
----------
y : array (T,)
Observation state sequence. int dtype.
transition : array (K, K)
State transition matrix. See HiddenMarkovModel.state_transition for
details.
emission : array (K,)
Emission matrix. See HiddenMarkovModel.emission for details.
init: optional, (K,)
Initial state probabilities: Pi[i] is the probability x[0] == i. If
None, uniform initial distribution is assumed (Pi[:] == 1/K).
Returns
-------
x : array (T,)
Maximum a posteriori probability estimate of hidden state trajectory,
conditioned on observation sequence y under the model parameters.
T1: array (K, T)
the probability of the most likely path so far
T2: array (K, T)
the x_j-1 of the most likely path so far
"""
# Cardinality of the state space
K = transition.shape[0]
emission = np.repeat(emission[np.newaxis:], K, axis=0)
# Initialize the priors with default (uniform dist) if not given by caller
init = init if init is not None else np.full(K, 1 / K)
T = len(obs)
T1 = np.empty((K, T), 'd')
T2 = np.empty((K, T), 'B')
# Initilaize the tracking tables from first observation
T1[:, 0] = init * emission[:, obs[0]]
T2[:, 0] = 0
# Iterate throught the observations updating the tracking tables
for i in range(1, T):
T1[:, i] = np.max(T1[:, i - 1] * transition.T * emission[np.newaxis:, obs[i]].T, 1)
T2[:, i] = np.argmax(T1[:, i - 1] * transition.T, 1)
# Build the output, optimal model trajectory
x = np.empty(T, 'B')
x[-1] = np.argmax(T1[:, T - 1])
for i in reversed(range(1, T)):
x[i - 1] = T2[x[i], i]
return x, T1, T2

We can try it out with the same observations:

>>> x, T1, T2 = viterbi([0, 0, 0, 0], transition_matrix, emission, init_prob)
>>> print(x)
array([0, 0, 0, 0], dtype=uint8)
>>> print(T1)
array([[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715],
[ 0.077, 0.02541, 0.0083853, 0.00276715]])
>>> print(T2)
array([[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 1, 1, 1],
[ 0, 3, 3, 3],
[ 0, 3, 3, 3],
[ 0, 0, 0, 0],
[ 0, 6, 6, 6],
[ 0, 4, 4, 4],
[ 0, 5, 5, 5],
[ 0, 8, 8, 8],
[ 0, 6, 6, 6],
[ 0, 10, 10, 10],
[ 0, 7, 7, 7]], dtype=uint8)
>>> x, T1, T2 = viterbi([0, 10, 8, 6], transition_matrix, emission, init_prob)
>>> print(x)
array([0, 0, 0, 0], dtype=uint8)
>>> print(T1)
array([[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ],
[ 0.077, 0., 0., 0. ]])
>>> print(T2)
array([[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 1, 0, 0],
[ 0, 3, 0, 0],
[ 0, 3, 0, 0],
[ 0, 0, 0, 0],
[ 0, 6, 0, 0],
[ 0, 4, 0, 0],
[ 0, 5, 0, 0],
[ 0, 8, 0, 0],
[ 0, 6, 0, 0],
[ 0, 10, 0, 0],
[ 0, 7, 0, 0]], dtype=uint8)

In this chapter, we introduced algorithms for doing inference over our HMM models. We looked at the forward-backward algorithm to do predictions for our hidden states given the observations. We also discussed the Viterbi algorithm, which is used to compute the most probable states in our model.

In all these algorithms, we assumed that we knew the transition and the emission probabilities of the model. But in real-world problems, we need to compute these values from the data. In the next chapter, we will introduce algorithms for computing transition and emission probabilities using the maximum-likelihood approach.