```
# Load libraries.
using Turing, StatsPlots, Random
# Set a random seed and use the forward_diff AD mode.
Random.seed!(12345678);
```

# Bayesian Hidden Markov Models

This tutorial illustrates training Bayesian Hidden Markov Models (HMM) using Turing. The main goals are learning the transition matrix, emission parameter, and hidden states. For a more rigorous academic overview on Hidden Markov Models, see An introduction to Hidden Markov Models and Bayesian Networks (Ghahramani, 2001).

In this tutorial, we assume there are \(k\) discrete hidden states; the observations are continuous and normally distributed - centered around the hidden states. This assumption reduces the number of parameters to be estimated in the emission matrix.

Let’s load the libraries we’ll need. We also set a random seed (for reproducibility) and the automatic differentiation backend to forward mode (more here on why this is useful).

## Simple State Detection

In this example, we’ll use something where the states and emission parameters are straightforward.

```
# Define the emission parameter.
= [
y 1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
2.0,
2.0,
2.0,
2.0,
2.0,
2.0,
3.0,
3.0,
3.0,
3.0,
3.0,
3.0,
3.0,
2.0,
2.0,
2.0,
2.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
];= length(y);
N = 3;
K
# Plot the data we just made.
plot(y; xlim=(0, 30), ylim=(-1, 5), size=(500, 250))
```

We can see that we have three states, one for each height of the plot (1, 2, 3). This height is also our emission parameter, so state one produces a value of one, state two produces a value of two, and so on.

Ultimately, we would like to understand three major parameters:

- The transition matrix. This is a matrix that assigns a probability of switching from one state to any other state, including the state that we are already in.
- The emission matrix, which describes a typical value emitted by some state. In the plot above, the emission parameter for state one is simply one.
- The state sequence is our understanding of what state we were actually in when we observed some data. This is very important in more sophisticated HMM models, where the emission value does not equal our state.

With this in mind, let’s set up our model. We are going to use some of our knowledge as modelers to provide additional information about our system. This takes the form of the prior on our emission parameter.

\[ m_i \sim \mathrm{Normal}(i, 0.5) \quad \text{where} \quad m = \{1,2,3\} \]

Simply put, this says that we expect state one to emit values in a Normally distributed manner, where the mean of each state’s emissions is that state’s value. The variance of 0.5 helps the model converge more quickly — consider the case where we have a variance of 1 or 2. In this case, the likelihood of observing a 2 when we are in state 1 is actually quite high, as it is within a standard deviation of the true emission value. Applying the prior that we are likely to be tightly centered around the mean prevents our model from being too confused about the state that is generating our observations.

The priors on our transition matrix are noninformative, using `T[i] ~ Dirichlet(ones(K)/K)`

. The Dirichlet prior used in this way assumes that the state is likely to change to any other state with equal probability. As we’ll see, this transition matrix prior will be overwritten as we observe data.

```
# Turing model definition.
@model function BayesHmm(y, K)
# Get observation length.
= length(y)
N
# State sequence.
= tzeros(Int, N)
s
# Emission matrix.
= Vector(undef, K)
m
# Transition matrix.
= Vector{Vector}(undef, K)
T
# Assign distributions to each element
# of the transition matrix and the
# emission matrix.
for i in 1:K
~ Dirichlet(ones(K) / K)
T[i] ~ Normal(i, 0.5)
m[i] end
# Observe each point of the input.
1] ~ Categorical(K)
s[1] ~ Normal(m[s[1]], 0.1)
y[
for i in 2:N
~ Categorical(vec(T[s[i - 1]]))
s[i] ~ Normal(m[s[i]], 0.1)
y[i] end
end;
```

We will use a combination of two samplers (HMC and Particle Gibbs) by passing them to the Gibbs sampler. The Gibbs sampler allows for compositional inference, where we can utilize different samplers on different parameters.

In this case, we use HMC for `m`

and `T`

, representing the emission and transition matrices respectively. We use the Particle Gibbs sampler for `s`

, the state sequence. You may wonder why it is that we are not assigning `s`

to the HMC sampler, and why it is that we need compositional Gibbs sampling at all.

The parameter `s`

is not a continuous variable. It is a vector of **integers**, and thus Hamiltonian methods like HMC and NUTS won’t work correctly. Gibbs allows us to apply the right tools to the best effect. If you are a particularly advanced user interested in higher performance, you may benefit from setting up your Gibbs sampler to use different automatic differentiation backends for each parameter space.

Time to run our sampler.

`setprogress!(false)`

```
= Gibbs(HMC(0.01, 50, :m, :T), PG(120, :s))
g = sample(BayesHmm(y, 3), g, 1000); chn
```

Let’s see how well our chain performed. Ordinarily, using `display(chn)`

would be a good first step, but we have generated a lot of parameters here (`s[1]`

, `s[2]`

, `m[1]`

, and so on). It’s a bit easier to show how our model performed graphically.

The code below generates an animation showing the graph of the data above, and the data our model generates in each sample.

```
# Extract our m and s parameters from the chain.
= MCMCChains.group(chn, :m).value
m_set = MCMCChains.group(chn, :s).value
s_set
# Iterate through the MCMC samples.
= 1:length(chn)
Ns
# Make an animation.
= @gif for i in Ns
animation = m_set[i, :]
m = Int.(s_set[i, :])
s = m[s]
emissions
= plot(
p
y;=:red,
chn=(500, 250),
size="Time",
xlabel="State",
ylabel=:topright,
legend="True data",
label=(0, 30),
xlim=(-1, 5),
ylim
)plot!(emissions; color=:blue, label="Sample $i")
end every 3
```

`[ Info: Saved animation to /tmp/jl_spiR8LsXYZ.gif`

Looks like our model did a pretty good job, but we should also check to make sure our chain converges. A quick check is to examine whether the diagonal (representing the probability of remaining in the current state) of the transition matrix appears to be stationary. The code below extracts the diagonal and shows a traceplot of each persistence probability.

```
# Index the chain with the persistence probabilities.
= chn[["T[1][1]", "T[2][2]", "T[3][3]"]]
subchain
plot(subchain; seriestype=:traceplot, title="Persistence Probability", legend=false)
```