Hidden Markov models
A response at one occasion may be consistent with more than one unobserved state. Responses before and after that occasion can change which state seems most plausible, particularly when states tend to persist over time. The order of observations therefore matters when a researcher wants to distinguish a change in state from variation in responses within a state. A hidden Markov model relates these two sources of change, allowing inference about a person’s state to draw on the sequence of observations rather than a single response. The chapter computes the likelihood of a short count sequence first by listing every state path and then by recursion, uses the same recursions for estimation and for inference about the states, and compares numbers of states on simulated and observed series.
13.1 Latent Markov chains, state-dependent response distributions, and latent transitions
Hidden Markov models (HMMs) are also called latent Markov models in longitudinal social research. Let $S_t$ be the unobserved state at occasion $t$ and $Y_t$ the observed response. One person’s sequence of responses is a single sampling unit. To examine a sequence probability, consider a constructed example with a count at each of three occasions. There are two states. Their initial probabilities $\pi_k=P(S_1=k)$ are 0.6 and 0.4. In general these probabilities are nonnegative and sum to one. The transition matrix $A$ gives the conditional probabilities for each subsequent occasion. Its entry $a_{kl}=P(S_{t+1}=l\mid S_t=k)$ has the departing state in row $k$ and the arriving state in column $l$. Here the rows are $(0.8,0.2)$ and $(0.3,0.7)$ at both transitions. Each row lists all possible destinations from one state, so its entries are nonnegative and sum to one.
Given state $k$, the count is Poisson with mean $\lambda_k$, here 1 or 4. This is the expected count at one occasion in that state; its conditional variance is also $\lambda_k$. The conditional response probability $b_k(y)=e^{-\lambda_k}\lambda_k^y/y!$ is the probability of observing count $y$ in that state. A zero thus has probability $e^{-1}$ in state 1 and $e^{-4}$ in state 2. Using the same transition matrix at each interval is the time-homogeneous Markov assumption. It does not require the initial distribution to be stationary.
For a particular path, what is the probability of both following it and seeing the recorded counts? Assume that, given the present state, the distribution of the next state is independent of the earlier states and responses. Given the full path, responses at different occasions are independent, and each response distribution depends only on its state at that occasion. Here a path is a sequence of state labels at the scheduled occasions. Write $s_{1:T}$ for a specified path of length $T$ and $y_{1:T}$ for the observed counts. With parameters $\theta=(\pi,A,\lambda)$, the two assumptions give
\[P_\theta(S_{1:T}=s_{1:T},Y_{1:T}=y_{1:T}) =\pi_{s_1}\prod_{t=2}^{T}a_{s_{t-1},s_t} \prod_{t=1}^{T}b_{s_t}(y_t).\]The first product has one factor for every change of occasion, including occasions on which the state stays the same. The second has one factor for every observation. The paths are mutually exclusive and exhaust the possibilities. Adding their joint probabilities therefore gives the probability of the observed counts. Viewed as a function of the parameters, that sum is the observed-data likelihood,
\[L(\theta;y_{1:T})=\sum_{s_{1:T}} P_\theta(S_{1:T}=s_{1:T},Y_{1:T}=y_{1:T}).\]For the counts $(0,1,3)$, there are eight possible paths. The function hmm_model() checks the probability vectors, transition matrix and response parameters and stores them in one list. It constructs a model at supplied parameter values; it does not estimate them. From the book directory, load the functions. The constructor they supply is shown below.
1
2
3
for (file in c("stability", "result", "differentiation", "dogleg", "factored_secant",
"simulation", "mixtures", "hmm", "study_records"))
source(paste0("code/lib/", file, ".R"))
1
2
3
4
5
6
7
8
9
10
11
12
13
hmm_model <- function(initial, transition, parameter, family = c("poisson", "normal", "indicators")) {
family <- match.arg(family)
K <- length(initial)
stopifnot(K > 0L, is.matrix(transition), all(dim(transition) == K),
all(is.finite(c(initial, transition))), min(initial, transition) >= 0,
abs(sum(initial) - 1) <= 1e-10, max(abs(rowSums(transition) - 1)) <= 1e-10)
if (family == "poisson") stopifnot(length(parameter) == K, all(is.finite(parameter)), all(parameter > 0))
if (family == "normal") stopifnot(is.matrix(parameter), all(dim(parameter) == c(K, 2)),
all(is.finite(parameter)), all(parameter[, 2] > 0))
if (family == "indicators") stopifnot(is.matrix(parameter), ncol(parameter) == K,
all(is.finite(parameter)), all(parameter >= 0 & parameter <= 1))
list(initial = initial, transition = transition, family = family, parameter = parameter)
}
For the Poisson model, the returned fields represent the quantities in the path probability as follows. The family determines how to interpret parameter; the conditional response probabilities themselves are evaluated at the observed counts.
| Field | Quantity in the model |
|---|---|
initial[k] | Initial state probability $\pi_k$ |
transition[k,l] | Transition probability $a_{kl}$ from state $k$ to state $l$ |
parameter[k] | Poisson mean $\lambda_k$ in $b_k(y)$ |
family | "poisson", specifying the conditional response distribution |
Construct tiny with the probabilities and rates just specified. The call to enumerate_hmm() lists the paths and evaluates the transition and conditional response products for each one. It is in code/lib/hmm.R, with hmm_emission(), which supplies $\log b_k(y_t)$ for every occasion and state.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
hmm_emission <- function(y, model) {
K <- length(model$initial)
if (model$family == "indicators") return(lca_log_emission(as.matrix(y), model$parameter))
stopifnot(is.numeric(y), all(is.finite(y) | is.na(y)))
if (model$family == "poisson") stopifnot(all(is.na(y) | (y >= 0 & y == floor(y))))
log_emission <- matrix(0, length(y), K)
observed <- !is.na(y)
for (k in seq_len(K)) {
log_emission[observed, k] <- if (model$family == "poisson")
dpois(y[observed], model$parameter[k], log = TRUE) else
dnorm(y[observed], model$parameter[k, 1], model$parameter[k, 2], log = TRUE)
}
log_emission
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
enumerate_hmm <- function(y, model) {
emission <- hmm_emission(y, model)
n <- nrow(emission)
K <- ncol(emission)
stopifnot(n >= 1L, n * log(K) <= log(1e5))
paths <- as.matrix(expand.grid(rep(list(seq_len(K)), n)))
log_initial <- log(model$initial[paths[, 1]])
log_transition <- log_emission <- numeric(nrow(paths))
for (t in seq_len(n)) {
log_emission <- log_emission + emission[t, paths[, t]]
if (t > 1L) log_transition <- log_transition +
log(model$transition[cbind(paths[, t - 1L], paths[, t])])
}
joint <- log_initial + log_transition + log_emission
list(paths = paths, initial = exp(log_initial), transitions = exp(log_transition),
emissions = exp(log_emission), joint = exp(joint), loglik = logsumexp(joint),
posterior = normalize_logweights(joint))
}
In hmm_emission(), row $t$ and column $k$ contain $\log b_k(y_t)$: the Poisson or normal log density, or for binary indicators the sum computed by lca_log_emission() (Section 12.1); a missing response contributes zero. In enumerate_hmm(), each row of paths is one sequence of states, log_initial is $\log\pi_{s_1}$, log_transition adds $\log a_{s_{t-1}s_t}$ and log_emission adds $\log b_{s_t}(y_t)$. Their sum joint is the log probability of the counts and that path; logsumexp() and normalize_logweights() (Sections 1.3 and 1.4) give the log likelihood and the posterior probability of each path. The function refuses more than $10^5$ paths.
1
2
3
4
5
tiny <- hmm_model(c(.6, .4), matrix(c(.8, .2, .3, .7), 2L, byrow = TRUE), c(1, 4))
y <- c(0, 1, 3)
exact <- enumerate_hmm(y, tiny)
print(data.frame(exact$paths, initial = exact$initial, transition = exact$transitions,
emission = exact$emissions, joint = exact$joint, posterior = exact$posterior))
1
2
3
4
5
6
7
8
9
Var1 Var2 Var3 initial transition emission joint posterior
1 1 1 1 0.6 0.64 0.0082978447 3.186372e-03 0.501321082
2 2 1 1 0.4 0.24 0.0004131254 3.966003e-05 0.006239827
3 1 2 1 0.6 0.06 0.0016525015 5.949005e-05 0.009359740
4 2 2 1 0.4 0.21 0.0000822732 6.910949e-06 0.001087319
5 1 1 2 0.6 0.16 0.0264400232 2.538242e-03 0.399348912
6 2 1 2 0.4 0.06 0.0013163712 3.159291e-05 0.004970603
7 1 2 2 0.6 0.14 0.0052654850 4.423007e-04 0.069588440
8 2 2 2 0.4 0.49 0.0002621531 5.138200e-05 0.008084077
In the first row, Var1, Var2 and Var3 give the successive states $(1,1,1)$. Starting there has probability 0.6, and staying there twice contributes $0.8^2=0.64$. The three Poisson probabilities at mean 1 multiply to $e^{-3}/6=0.0082978447$ to the precision shown. Multiplying those three columns gives the joint probability 0.00318637 of that path and the counts together. The sum of joint over all eight rows, 0.00635595, is the probability of observing these counts. Dividing the first row’s joint probability by that sum gives 0.50132, the posterior probability of the path given the counts. The fifth row shows why the other paths matter. Switching to state 2 on the last occasion is less probable than staying in state 1, but a count of 3 is more probable at the higher rate. That path still has posterior probability about 0.39935. This posterior probability conditions on the supplied parameter values; it does not average over uncertainty about those parameters.
How much can changing the initial probabilities alone change the likelihood? With the rates and transition matrix fixed, consider a different sequence, $(4,3,2)$. Let $L_k$ denote the probability of these counts conditional on starting in state $k$. Grouping the eight paths by their first state gives $L(\pi)=\sum_k\pi_kL_k$. Within each group, the starting state is already specified, so only transition and response factors enter $L_k$.
1
2
3
4
5
6
7
8
9
10
11
other_y <- c(4, 3, 2)
other_paths <- enumerate_hmm(other_y, tiny)
first_state <- other_paths$paths[,1]
sequence_probability_given_state <- vapply(seq_along(tiny$initial), function(k) {
# These paths all begin in state k.
use <- first_state == k
sum(other_paths$transitions[use] * other_paths$emissions[use])
}, 0.0)
print(data.frame(first_state=seq_along(sequence_probability_given_state),
sequence_probability_given_state,initial_probability=tiny$initial,
joint_state_and_sequence_probability=tiny$initial*sequence_probability_given_state))
1
2
3
4
5
6
first_state sequence_probability_given_state initial_probability
1 1 0.000227152 0.6
2 2 0.004848819 0.4
joint_state_and_sequence_probability
1 0.0001362912
2 0.0019395277
The logical index use selects the four paths with the designated first state. Their products sum to 0.000227152 for state 1 and 0.004848819 for state 2. With the stipulated initial probabilities, the last column gives the two terms $\pi_kL_k$ in the marginal probability, about 0.002076 in total. Moving initial probability from state 1 to state 2 increases the multiplier of the larger term. For this sequence the maximizing choice of $\pi$ puts all initial probability on state 2. Any maximizing initial distribution allocates all its probability to states with maximal $L_k$. When several states share that value, any mixture on those states attains it. Grouping by the first state clarifies that result, but enumerating paths still takes $K^T$ rows for $K$ states, with $2T$ factors in each row.
Simulated sequences and missing responses
Beyond the three-count example, the chapter uses a longer simulated series. The simulated count series HMM2 has 250 occasions and its own generating parameters. Its Poisson means are 2 and 8. Once in the lower-rate state, the chain stays there with probability 0.95, and once in the higher-rate state it stays there with probability 0.90. The series is generated by simulate_hmm() in code/lib/hmm.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
simulate_hmm <- function(n, model) {
K <- length(model$initial)
stopifnot(length(n) == 1L, n >= 1L, n == as.integer(n))
state <- integer(n)
y <- matrix(0, n, if (model$family == "indicators") nrow(model$parameter) else 1L)
for (t in seq_len(n)) {
p <- if (t == 1L) model$initial else model$transition[state[t - 1L], ]
k <- state[t] <- sample.int(K, 1L, prob = p)
y[t, ] <- switch(model$family, poisson = rpois(1, model$parameter[k]),
normal = rnorm(1, model$parameter[k, 1], model$parameter[k, 2]),
indicators = rbinom(ncol(y), 1L, model$parameter[, k]))
}
list(observed = if (model$family == "indicators") y else c(y), state = state)
}
At the first occasion the state is drawn from the initial probabilities and afterwards from the row of the transition matrix for the previous state; the response is then drawn from that state’s Poisson, normal or binary distribution.
1
2
3
4
truth <- hmm_model(c(.6, .4), matrix(c(.95, .05, .10, .90), 2L, byrow = TRUE), c(2, 8))
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(1301)
series <- simulate_hmm(250L, truth)
Inside simulate_hmm(), the first state is sampled with probabilities 0.6 and 0.4. Suppose the preceding draw was state 2. The expression model$transition[state[t - 1L], ] selects the second row, so the next draw has probability 0.10 of moving to state 1. If that move occurs, the count for the new occasion is drawn at mean 2. The generator returns both the counts and the path that produced them. For fitting, the input is series$observed. To use the distributed counts directly, set series <- list(observed = readRDS("data/source/ch13/HMM2.rds")). The separately saved state path permits an assessment of decoding accuracy after fitting.
A new person starts a new path. For independent respondents the likelihood multiplies their sequence probabilities, each with one initial factor for that person’s first state. All first states are drawn from the same unrestricted initial distribution. Later responses from one person can help infer that person’s first state through the transitions. Observing many people from their first occasion supplies repeated starts for estimating the population’s initial proportions.
A missed interview within a person’s sequence has a different consequence. Ignoring the missingness mechanism requires missing at random together with distinct missingness and response parameters: after conditioning on observed responses, missingness must not additionally depend on unobserved responses or states. Under this ignorable mechanism, summing over all possible responses at that occasion gives a response factor of one for every state. If an interview between two observed occasions is missed, the two transitions on either side still enter the path probability. Retain the scheduled row for a missed interview so that both transitions remain in the model.
The function hmm_emission() implements this omission by leaving the conditional log probability or density at zero for a missing count or continuous measurement. When just one item is missing from an interview, lca_log_emission() omits that item’s factor and retains the information in the remaining answers. This likelihood treatment does not imply that every fitting routine below handles missing responses.
Latent transition analysis
Latent transition analysis uses this structure to describe changes in latent classes measured by repeated categorical responses. The simulated panel contains 200 respondents. A latent transition model measures the state at each of three occasions with the same six questions. Let $p_{jk}$ be the probability of a yes answer to item $j$ in state $k$, shared across occasions. Given state $k$, the items are independent, so a vector of binary answers $\mathbf y_t$ has conditional response probability $b_k(\mathbf y_t)=\prod_{j=1}^6 p_{jk}^{y_{tj}}(1-p_{jk})^{1-y_{tj}}$. In indicators each column contains the six success probabilities for one state. The three initial proportions are 0.3, 0.4 and 0.3. Each transition row assigns 0.85 to staying and 0.075 to each other state. Constraining these item probabilities to be equal across occasions imposes measurement invariance over time; it is separate from requiring equal transition matrices. The state numbers label response profiles and do not impose an ordinal scale.
1
2
3
4
5
6
7
8
indicators <- cbind(c(.15, .20, .25, .20, .15, .25), c(.70, .65, .60, .25, .20, .30),
c(.80, .85, .75, .80, .85, .75))
A <- matrix(.075, 3, 3)
diag(A) <- .85
lta <- hmm_model(c(.3, .4, .3), A, indicators, "indicators")
set.seed(1311)
panel <- replicate(200, simulate_hmm(3L, lta), simplify = FALSE)
occasions <- lapply(panel, function(p) p$observed)
Each element of occasions contains one person’s observed responses, with occasions in rows and items in columns. The saved list can also be loaded with occasions <- readRDS("data/source/ch13/latent-transition.rds"). For the first person, occasions[[1]][2, ] selects the six no answers at the second interview.
1
print(hmm_emission(occasions[[1]], lta))
1
2
3
4
[,1] [,2] [,3]
[1,] -5.566197 -6.117028 -5.566197
[2,] -1.346689 -4.037586 -9.785705
[3,] -3.543914 -4.479419 -7.588480
In the second row, for state 1 the six failure probabilities give $\log(0.85\times0.80\times0.75\times0.80\times0.85\times0.75)=-1.347$ after rounding. The corresponding values for states 2 and 3 are $-4.038$ and $-9.786$. The answers favor state 1.
Filtering conditions on responses through the occasion being assessed; smoothing conditions on the entire observed sequence. To obtain the filtering probability of state 1 at the second interview, weight each state’s response probability by its predicted probability after the first interview and normalize across states. Its smoothing probability also takes the third interview into account. Throughout these calculations the model parameters are fixed. Latent transition models are available in depmixS4.
13.2 Forward likelihood recursion with scaling and log calculations
After one interview, what information from a respondent’s history is needed at the next interview? Return to the counts $y=(0,1,3)$ and the two states in tiny. Suppose two paths have reached the same state. Given that state, both paths have the same probabilities for the next transition and response. Their joint probabilities with the observations so far can therefore be added before taking the next step. For each state $k$, define the forward quantity $\alpha_t(k)=P(Y_{1:t}=y_{1:t},S_t=k)$ at the specified model parameters. Summing over $k$ gives the probability of the counts so far, $L_t$. When $L_t>0$, dividing each entry by $L_t$ gives the filtering probability $f_t(k)=P(S_t=k\mid Y_{1:t}=y_{1:t})$. For a continuous response, $\alpha_t(k)$ is a joint density in the observed responses with the state fixed at $k$ and $L_t$ is the marginal response density. The ratio still gives a probability for a discrete state.
At the first occasion the only choice is the initial state, so $\alpha_1(k)=\pi_k b_k(y_1)$. A zero count gives joint probabilities $0.6e^{-1}=0.220727665$ and $0.4e^{-4}=0.007326256$, rounded. Dividing the first term by their sum gives $0.220727665/(0.220727665+0.007326256)\approx0.9678749$. Seeing a zero has raised the probability of state 1 from 0.6 to almost 0.97. For the next occasion, group paths ending in state $k$ according to the state $i$ they occupied one step earlier. Each group contributes to the transition sum its previous forward quantity times the probability of moving from $i$ to $k$. All groups then have the same conditional response probability at the destination. Thus
\[\alpha_t(k)=b_k(y_t)\sum_{i=1}^K \alpha_{t-1}(i)a_{ik}.\]The same transition sum applied to the filtering probabilities gives the prediction $q_t(k)=P(S_t=k\mid Y_{1:t-1}=y_{1:t-1})$. For instance, the predicted probability of state 1 at the second occasion is $0.9678749(0.8)+0.0321251(0.3)\approx0.78394$. Both terms use column 1 of the transition matrix. Multiplying this prediction by the probability of the second count in state 1 incorporates the new observation.
Scaling by predictive probabilities
How can the likelihood be retained while the state probabilities are expressed on a usable numerical scale? Start with $q_1(k)=\pi_k$. At time $t$, let $c_t=\sum_k q_t(k)b_k(y_t)$. This is the predictive probability of the current count given the preceding counts. Dividing each summand by $c_t$ gives $f_t(k)$. By the multiplication rule, $L_t=L_{t-1}c_t$ with $L_0=1$, so the sequence log likelihood is $\ell=\sum_{t=1}^T\log c_t$. For a continuous response $c_t$ is a predictive density evaluated at the observation and may exceed one. Repeatedly multiplying small predictive probabilities can underflow, meaning that their positive product becomes too small for the numerical representation and can be rounded to zero. The scaled branch of hmm_forward() in code/lib/hmm.R also protects the conditional response calculation by subtracting the largest conditional log probability or density in each row before exponentiating. The following update uses the same count vector and model. Here scaling means dividing by a positive row sum during the recursion and retaining its logarithm for the likelihood; it is not a change in the measurement units of the response.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
model <- tiny
emission <- hmm_emission(y, model)
K <- ncol(emission)
n <- nrow(emission)
shift <- emission[cbind(seq_len(n), max.col(emission, ties.method = "first"))]
relative <- exp(emission - shift)
filtered <- matrix(0, n, K)
scale <- numeric(n)
prediction <- model$initial
for (t in seq_len(n)) {
joint <- prediction * relative[t, ]
scale[t] <- sum(joint)
if (!is.finite(scale[t]) || scale[t] <= 0) break
filtered[t, ] <- joint / scale[t]
# Each column of the transition matrix gives one destination.
prediction <- drop(filtered[t, ] %*% model$transition)
}
if (all(is.finite(scale) & scale > 0)) {
log_scale <- log(scale) + shift
}
For the initial zero the largest conditional log probability is $-1$. The shifted row sum is $0.6+0.4e^{-3}$, and multiplying it by $e^{-1}$ restores the probability 0.228054 of observing that zero. In each iteration prediction contains one probability per state before the count arrives. Subtracting shift[t] from every conditional log probability multiplies each term of $c_t$ by the same factor. That factor cancels in joint / scale[t]. To recover $\log c_t$, the code adds shift[t] to the logarithm of the stored row sum. Thus scale[t] stores a sum after the common exponential shift, whereas log_scale[t] in the returned forward result represents the logarithm of the original predictive probability or density. These are different quantities.
Calculations on the log scale
Prediction and normalization can also be carried out entirely in logarithms. At the first occasion use $\log\pi_k$ as the log prediction. At subsequent occasions the terms to be summed for destination $k$ have logarithms $\log f_{t-1}(i)+\log a_{ik}$. The function logsumexp() of Section 1.3 computes the logarithm of a sum from the logarithms of its terms. Add the conditional log probability or density to the log prediction to obtain $u_t(k)$. Then $\log c_t=\operatorname{logsumexp}_k u_t(k)$, and subtracting $\log c_t$ from each $u_t(k)$ gives $\log f_t(k)$. The log branch uses these steps with the same matrix of conditional log probabilities or densities.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
log_filter <- matrix(-Inf, n, K)
log_scale <- numeric(n)
log_transition <- log(model$transition)
for (t in seq_len(n)) {
if (t == 1L) {
log_prediction <- log(model$initial)
} else {
log_prediction <- vapply(seq_len(K), function(k)
logsumexp(log_filter[t - 1L, ] + log_transition[, k]), 0.0)
}
joint <- log_prediction + emission[t, ]
log_scale[t] <- logsumexp(joint)
if (!is.finite(log_scale[t]))
stop(sprintf("Zero predictive probability at time %d", t))
log_filter[t, ] <- joint - log_scale[t]
}
Each row of log_filter now describes the state conditional on the counts through that row. To recover the joint probability for one cell, use $\alpha_t(k)=f_t(k)L_t$. On the log scale this means adding the sum of the first $t$ entries of log_scale to log_filter[t, k] before exponentiating.
The two branches evaluate y as one sequence. For comparison, split_ll starts a second sequence at its last count. The displays give one-step predictions and compare the intact sequence likelihood with enumeration.
1
2
3
4
5
6
scaled <- hmm_forward(y, tiny)
logged <- hmm_forward(y, tiny, "log")
split_ll <- hmm_forward(y[1:2], tiny)$loglik + hmm_forward(y[3], tiny)$loglik
print(data.frame(time = seq_along(y), predictive = exp(logged$log_scale),
filtered_state_1 = logged$filtering[, 1],
cumulative_loglik = cumsum(logged$log_scale)))
1
2
3
4
time predictive filtered_state_1 cumulative_loglik
1 1 0.22805392 0.9678749 -1.478173
2 2 0.30422377 0.9479683 -2.668165
3 3 0.09161148 0.5180080 -5.058364
1
2
print(c(enumerated = exact$loglik, scaled = scaled$loglik,
log = logged$loglik, two_sequences = split_ll))
1
2
enumerated scaled log two_sequences
-5.058364 -5.058364 -5.058364 -4.831556
Given the counts available before each occasion, the probabilities of observing 0, then 1, then 3 are 0.228054, 0.304224 and 0.091611, respectively. Using the unrounded values, their logarithms sum to $-5.058364$ to the precision shown, matching enumeration. State 1 has filtering probabilities 0.96787, 0.94797 and 0.51801. The last count leaves the two states almost equally probable.
A sequence boundary changes the prediction even when every observation has positive probability. Suppose one person contributed the counts 0 and 1, and a second, independently sampled person contributed the count 3. The first person’s sequence ends after the second count. For the new person, hmm_forward(y[3], tiny) uses the initial probabilities 0.6 and 0.4. Averaging the two Poisson probabilities of a 3 with those initial probabilities gives about 0.114935. Within the original sequence the probability of the same count was 0.091611, because the prediction used the first person’s history. Adding the two people’s log likelihoods gives the two_sequences value of $-4.831556$. The sampling design determines which product describes the observations.
Returning to the intact sequence, each normalized entry is paired below with its joint probability at the same time and state.
1
2
3
4
for (k in seq_along(tiny$initial)) print(data.frame(
time = seq_along(y), state = k,
forward_joint = exp(logged$log_filter[, k] + cumsum(logged$log_scale)),
normalized = logged$filtering[, k], predictive_scale = exp(logged$log_scale)))
1
2
3
4
5
6
7
8
time state forward_joint normalized predictive_scale
1 1 1 0.220727665 0.9678749 0.22805392
2 2 1 0.065769490 0.9479683 0.30422377
3 3 1 0.003292433 0.5180080 0.09161148
time state forward_joint normalized predictive_scale
1 1 2 0.007326256 0.03212510 0.22805392
2 2 2 0.003609933 0.05203175 0.30422377
3 3 2 0.003063518 0.48199203 0.09161148
In the first state table, observing the zero and being in state 1 has probability 0.220727665. Conditioning on the zero gives 0.9678749. At the last occasion the two joint entries sum to $0.003292433+0.003063518=0.006355951$, the likelihood obtained by multiplying the predictive probabilities. What if a predictive probability is zero? Consider one binary response equal to 1 under a model with the following initial and conditional response probabilities.
1
2
impossible <- hmm_model(c(1, 0), diag(2), matrix(c(0, 1), 1, 2), "indicators")
print(tryCatch(hmm_forward(matrix(1, 1), impossible), error = conditionMessage))
1
[1] "Zero predictive probability at time 1"
State 1 is certain initially, but the conditional probability of response 1 in that state is zero. In state 2 the conditional probability of response 1 is one, but its initial probability is zero. The two terms are $1\times0$ and $0\times1$. The scaled branch encounters a zero row sum and retries in logarithms. Both log terms are $-\infty$, so the function reports the time at which conditioning became impossible. In this zero-probability example the failure is structural. In general, the same implementation also stops on non-finite predictive values, which can arise from numerical failure and need separate diagnosis.
The cost of enumeration
How many calculations does grouping paths by their current state save? With $K$ states there are $K^T$ possible paths of length $T$. The forward update uses $K$ terms for each of $K$ destinations at each of $T-1$ transitions, or $(T-1)K^2$ terms. This count covers the transition sums and excludes initialization, response evaluations and normalization. To see how the counts grow, take successively longer prefixes of the 250 observed counts in series$observed and use their generating model truth. Time enumeration only through length 16.
1
2
3
4
5
6
7
8
9
10
timings <- lapply(c(3L, 8L, 16L, 250L), function(n) {
input <- series$observed[seq_len(n)]
forward <- system.time(value <- hmm_forward(input, truth))["elapsed"]
enumeration <- if (n <= 16L) {
system.time(enumerated <- enumerate_hmm(input, truth))["elapsed"]
} else NA_real_
data.frame(times = n, possible_paths = 2^n, transition_terms = 4 * (n - 1L),
forward_seconds = unname(forward), enumeration_seconds = unname(enumeration))
})
print(do.call(rbind, timings))
1
2
3
4
5
times possible_paths transition_terms forward_seconds enumeration_seconds
1 3 8.000000e+00 8 0 0.000
2 8 2.560000e+02 28 0 0.000
3 16 6.553600e+04 60 0 0.019
4 250 1.809251e+75 996 0 NA
At length 16 there are 65,536 paths and only 60 terms in the forward transition sums. Enumeration took 0.019 seconds in this run. The zeros in forward_seconds at all four lengths mean that those elapsed times were below the timer’s resolution. At length 250 the path count is about $1.81\times10^{75}$, and NA marks the unmeasured enumeration time. The forward calculation needs 996 transition terms for the full series. With the number of states fixed, its work grows linearly with the number of observations. A scaled forward likelihood is also available in LaMa.
13.3 Backward recursion and posterior state and transition probabilities
At the second interview, the responses collected so far can be used to infer a respondent’s current state. Once the third interview is available, how should its responses change that earlier inference? Consider the same question for the counts $y=(0,1,3)$ under the fixed parameters of tiny. For a possible state $k$ at time $t$, let $B_t(k)=P(Y_{t+1:T}=y_{t+1:T}\mid S_t=k)$. This backward quantity measures how probable the remaining counts would be if the chain were now in state $k$. At the last occasion the remaining sequence is empty, so $B_T(k)=1$ for every state. One step earlier, each possible next state $l$ supplies a transition, a conditional response probability at the next occasion and the probability of the observations still to come. Summing over these alternatives gives
With continuous observations the same recursion gives the conditional joint density of the remaining responses evaluated at their observed values. In either case the row of $A$ is fixed by the state whose future is being evaluated.
For each occasion $u$, the forward calculation gives $c_u$, the probability of count $y_u$ given the counts before it. The product of these probabilities from $u=t+1$ through $T$ is the probability of the remaining observations given the observed history through $t$. Dividing $B_t(k)$ by that product gives a scaled backward quantity $r_t(k)$ whenever the observed sequence has positive probability. Its terminal value is still one. The factors from $t+2$ onward are already included in the scaling of $r_{t+1}(l)$, leaving just one division in the update,
\[r_t(k)=\sum_{l=1}^K a_{kl}\,\frac{b_l(y_{t+1})}{c_{t+1}}\,r_{t+1}(l).\]For a continuous response the numerator and denominator of the ratio are densities evaluated at the same response value. In the scaled calculation of hmm_posterior(), use the forward result scaled and the model tiny to work from the final row toward the first. The ratio is a scaled conditional likelihood contribution from future responses, not a probability distribution over the current states; its row need not sum to one. The supplied forward result must come from the same response sequence and model.
1
2
3
4
5
6
7
8
f <- scaled
model <- tiny
n <- nrow(f$filtering)
K <- ncol(f$filtering)
beta <- matrix(1,n,K)
if (n>1L) for(t in seq.int(n-1L,1L))
beta[t,] <- drop(model$transition%*%
(f$relative_emission[t+1L,]*beta[t+1L,]))/f$scale[t+1L]
Both relative_emission[t+1L,] and the row sum scale[t+1L] contain the same multiplier from shifting the conditional log probabilities or densities. Dividing the shifted conditional response probability by that row sum restores $b_l(y_{t+1})/c_{t+1}$. The local array beta represents $r_t(k)$. hmm_posterior() returns log(beta) in its backward component, which therefore contains $\log r_t(k)$, not $B_t(k)$ or a smoothed state probability.
With a log-space forward result, hmm_posterior() instead calls hmm_backward(), which adds the log transition, next conditional log probability or density and next log backward value for each arrival state. It combines those terms with logsumexp() and subtracts the log predictive probability or density for the next observation, forward$log_scale[t + 1L].
How much weight should the remaining observations give each state? The filtering probability $f_t(k)$ already conditions on the counts through $t$. Given $S_t=k$, those earlier observations supply no further information about the future counts. Bayes’ rule therefore makes the smoothed probability $\gamma_t(k)=P(S_t=k\mid Y_{1:T}=y_{1:T})$ proportional to $f_t(k)B_t(k)$. Replacing $B_t(k)$ by $r_t(k)$ divides the product $f_t(k)B_t(k)$ for every state by the same positive number. Normalizing those products gives $\gamma_t(k)=f_t(k)r_t(k)/\sum_i f_t(i)r_t(i)$. Each row of the calculation corresponds to one occasion.
1
2
3
product <- f$filtering*beta
totals <- rowSums(product)
gamma <- product/totals
In exact arithmetic the row totals are one, since the filtering distribution averages the state-specific probabilities of the future to their predictive probability. A scaled backward value can exceed one. For a state with positive filtering probability, this raises its smoothed probability above its filtering probability because the later counts are more probable starting from that state than they were given only the observed history.
Posterior transition probabilities
The posterior probability of a transition is indexed by its departure and destination states. Let $\xi_t(k,l)$ be the probability that $S_t=k$ and $S_{t+1}=l$ given the complete sequence. Start with the filtering probability for the departure state $k$. Moving to $l$ supplies the factor $a_{kl}$, observing the next count supplies $b_l(y_{t+1})$, and the remaining counts supply the backward quantity for $l$. Scaling the last two factors gives the unnormalized pair probabilities $w_t(k,l)$, which are normalized over both states,
\[w_t(k,l)=f_t(k)a_{kl}\frac{b_l(y_{t+1})}{c_{t+1}}r_{t+1}(l), \qquad \xi_t(k,l)=\frac{w_t(k,l)}{\sum_{i=1}^K\sum_{j=1}^K w_t(i,j)}.\]In the implementation, right combines the evidence from the next observation and all later ones for each arrival state. Its first row corresponds to the observations from time 2 onward.
1
2
3
4
5
6
xi <- array(0,c(n-1L,K,K))
if (n>1L) {
right <- f$relative_emission[-1L,,drop=FALSE]*beta[-1L,,drop=FALSE]/f$scale[-1L]
for (j in seq_len(K)) for (k in seq_len(K))
xi[,j,k] <- f$filtering[-n,j]*model$transition[j,k]*right[,k]/totals[-n]
}
The code uses j for the departure state and k for the arrival state. Summing $w_t$ over arrival states first gives $f_t(k)r_t(k)$ in the equation’s notation. Summing over departures then gives totals[t], the normalization used for smoothing at time $t$. Each time slice contains one joint distribution over pairs.
For the three counts, hmm_posterior() from code/lib/hmm.R returns both smoothed state probabilities and the joint probabilities connecting consecutive occasions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
hmm_posterior <- function(y, model, forward = NULL) {
f <- if (is.null(forward)) hmm_forward(y,model,"scaled") else forward
if (!is.null(f$scale)) {
n <- nrow(f$filtering)
K <- ncol(f$filtering)
beta <- matrix(1,n,K)
if (n>1L) for(t in seq.int(n-1L,1L))
beta[t,] <- drop(model$transition%*%(f$relative_emission[t+1L,]*beta[t+1L,]))/f$scale[t+1L]
product <- f$filtering*beta
totals <- rowSums(product)
if (all(is.finite(beta)) && all(is.finite(totals) & totals>0)) {
gamma <- product/totals
xi <- array(0,c(n-1L,K,K))
if (n>1L) {
right <- f$relative_emission[-1L,,drop=FALSE]*beta[-1L,,drop=FALSE]/f$scale[-1L]
for (j in seq_len(K)) for (k in seq_len(K))
xi[,j,k] <- f$filtering[-n,j]*model$transition[j,k]*right[,k]/totals[-n]
}
return(list(forward=f,backward=log(beta),gamma=gamma,xi=xi))
}
}
if (!is.null(f$scale)) f <- hmm_forward(y,model,"log")
back <- hmm_backward(f, model$transition)
n <- nrow(back)
K <- ncol(back)
gamma <- matrix(0, n, K)
for (t in seq_len(n)) gamma[t, ] <- normalize_logweights(f$log_filter[t, ] + back[t, ])
xi <- array(0, c(n - 1L, K, K))
for (t in seq_len(n - 1L)) {
# Row j is the departure state and column k the arrival state.
pair <- outer(f$log_filter[t, ], f$log_emission[t + 1L, ] + back[t + 1L, ], "+") +
log(model$transition)
xi[t, , ] <- normalize_logweights(c(pair))
}
list(forward = f, backward = back, gamma = gamma, xi = xi)
}
In the scaled branch, f$filtering contains $f_t(k)$, f$scale the shifted predictive probabilities and f$relative_emission the shifted conditional probabilities of hmm_forward(); the common shifts cancel, so beta[t, ] is $r_t(k)$, computed backward from $r_T(k)=1$. The rows of product are proportional to $f_t(k)r_t(k)$, and normalizing them gives $\gamma_t(k)$ in gamma. Entry $(t,j,k)$ of xi is $f_t(j)a_{jk}b_k(y_{t+1})r_{t+1}(k)$ divided by the scaled predictive probability at $t+1$ and by the row total, $\xi_t(j,k)$. If any of these values is not finite, the function repeats the calculation on the log scale with hmm_backward(), which returns $\log r_t(k)$, and normalizes the log terms with normalize_logweights() (Section 1.4).
1
2
3
post <- hmm_posterior(y, tiny)
print(data.frame(time = seq_along(y), filtered = scaled$filtering[, 1],
smoothed = post$gamma[, 1]))
1
2
3
4
time filtered smoothed
1 1 0.9678749 0.9796182
2 2 0.9479683 0.9118804
3 3 0.5180080 0.5180080
With only the counts 0 and 1 in hand, state 1 receives probability 0.94797 for the second occasion. How did the final count of 3 lower it to 0.91188? Conditional on state 1 at the second occasion, the probability of a final count of 3 is $0.8b_1(3)+0.2b_2(3)\approx0.088124$, slightly below its predictive probability of 0.091611. Multiplying the filtering probability by their ratio gives $0.94797(0.088124/0.091611)\approx0.9119$. At the third occasion there are no further counts, so both probabilities are 0.51801.
The state probabilities summarize one occasion at a time. The transition array below records probabilities by both departure and destination state for each interval.
1
print(post$xi)
1
2
3
4
5
6
7
8
9
10
11
, , 1
[,1] [,2]
[1,] 0.9006700 0.01121043
[2,] 0.5075609 0.01044706
, , 2
[,1] [,2]
[1,] 0.07894818 0.009171396
[2,] 0.40431951 0.077672518
The array post$xi[t,i,j] indexes time, departure state and arrival state, in that order. The printed panel headed , , 1 fixes the arrival state at 1. To recover the four possibilities for the first transition, read the first row of each panel. In departure and arrival order $(1,1),(1,2),(2,1),(2,2)$, their probabilities are 0.90067, 0.07895, 0.01121 and 0.00917. Summing by departure gives $0.90067+0.07895=0.97962$ for starting in state 1 and $0.01121+0.00917=0.02038$ for starting in state 2. Summing by arrival gives $0.90067+0.01121=0.91188$ for reaching state 1 and $0.07895+0.00917=0.08812$ for reaching state 2. The following calculation checks both identities at full precision for each interval.
1
2
3
for(t in seq_len(length(y)-1L)) print(data.frame(time=t,state=seq_along(tiny$initial),
row_margin=rowSums(post$xi[t,,]),smoothed_now=post$gamma[t,],
column_margin=colSums(post$xi[t,,]),smoothed_next=post$gamma[t+1L,]))
1
2
3
4
5
6
time state row_margin smoothed_now column_margin smoothed_next
1 1 1 0.97961817 0.97961817 0.91188042 0.91188042
2 1 2 0.02038183 0.02038183 0.08811958 0.08811958
time state row_margin smoothed_now column_margin smoothed_next
1 2 1 0.91188042 0.91188042 0.518008 0.518008
2 2 2 0.08811958 0.08811958 0.481992 0.481992
1
2
3
for (t in seq_len(length(y) - 1L)) stopifnot(
max(abs(rowSums(post$xi[t, , ]) - post$gamma[t, ])) < 1e-10,
max(abs(colSums(post$xi[t, , ]) - post$gamma[t + 1L, ])) < 1e-10)
These sums illustrate $\sum_l\xi_t(k,l)=\gamma_t(k)$ and $\sum_k\xi_t(k,l)=\gamma_{t+1}(l)$. Each identity follows because the states summed over exhaust the possibilities for that occasion. Both comparisons pass the absolute tolerance of $10^{-10}$. Reversing the time indices would compare probabilities for different occasions.
Filtering and smoothing for HMM2
Figure 13.1 compares filtering and smoothing for the 250 observations of HMM2. The calculation uses series$observed at its generating parameters truth and measures the absolute change in the probability of state 1 at each time.
1
2
3
4
smooth <- hmm_posterior(series$observed, truth)
revision <- abs(smooth$gamma[, 1] - smooth$forward$filtering[, 1])
print(c(largest_revision = max(revision), at = which.max(revision),
changed = sum((smooth$gamma[, 1] > .5) != (smooth$forward$filtering[, 1] > .5))))
1
2
largest_revision at changed
0.6158426 193.0000000 8.0000000
Figure 13.1. Probability of the lower-rate state at each of 250 occasions. The dashed blue line uses counts through that occasion. The solid orange line uses all 250 counts.
The largest vertical separation is about 0.6158 at time 193, where subsequent counts lower the probability of state 1. At eight occasions the two calculations give different answers to the question “Is state 1 more probable than state 2?” The code counts an occasion when exactly one of the two probabilities is greater than 0.5. This comparison uses the observed counts and model parameters alone. For a respondent, the analogous distinction is between an assessment made at an interview and an assessment of that same occasion once later interviews are available. In depmixS4, request posterior(fit, type = "smoothing") for the smoothed state probabilities; the default Viterbi output has a different meaning. Joint transition probabilities are supplied by forwardbackward().
13.4 Baum-Welch estimation as EM
A respondent can change states between interviews, but the response record does not identify which transitions occurred. What would be counted if the states were known? For one sequence of length $T$, let $z_{tk}$ equal one when $S_t=k$ and zero otherwise. The product $z_{ti}z_{t+1,k}$ then counts a transition from $i$ to $k$ at time $t$. With initial probabilities $\pi_k$, transition probabilities $a_{ik}$ and conditional response probabilities $b_k(y_t)$, the complete-data log likelihood is
\[\ell_c(\theta)= \sum_k z_{1k}\log\pi_k+ \sum_{t=1}^{T-1}\sum_{i,k}z_{ti}z_{t+1,k}\log a_{ik}+ \sum_{t=1}^{T}\sum_k z_{tk}\log b_k(y_t).\]Independent sequences contribute separate copies of this sum. In the E step, condition on each entire observed sequence at the current parameter values. The conditional means of the two indicators for state and state pair are $\gamma_t(k)$ and $\xi_t(i,k)$, respectively. Substitution gives an expected complete-data log likelihood to maximize over the new parameters, with these probabilities fixed. Repeating this calculation is the Baum-Welch algorithm.
Its progress is measured by the observed-data log likelihood after each update. A small change can justify stopping the iteration. To assess the attained solution, compare starts, since the stopping test alone cannot classify a stationary point or establish a global maximum.
In the E-step expectation, a zero expected count contributes zero to a term of the form $n\log p$, including when $p=0$. A positive expected count with $p=0$ instead gives minus infinity. The expectation uses the current parameters, while maximization varies the candidate parameters.
Updating the initial, transition and response parameters
For the initial distribution, each respondent contributes exactly one draw. Write $n_{1k}$ for the sum of the first-occasion smoothed probabilities of state $k$ over $N$ independent sequences. The initial term to maximize is $\sum_k n_{1k}\log\pi_k$. With a multiplier for $\sum_k\pi_k=1$, the first-order equations make $n_{1k}/\pi_k$ constant for states with $n_{1k}>0$. That constant is $\sum_k n_{1k}=N$. The update is therefore $n_{1k}/N$.
To follow the calculation for y, the three counts $(0,1,3)$, use the EM functions already loaded from code/lib/hmm.R. With one count response here, the following statements set up the E step at the parameters of tiny and update its initial distribution.
1
2
3
4
5
6
7
8
9
10
11
12
13
model <- hmm_em_start(tiny)
K <- length(tiny$initial)
data <- hmm_response_data(matrix(y), "poisson")
seq_lengths <- length(y)
n_seq <- length(seq_lengths)
seq_end <- cumsum(seq_lengths)
seq_begin <- c(1, seq_end[-n_seq] + 1)
init_matrix <- function(p) matrix(1, n_seq, 1L) %*% p
dens <- hmm_densities(data, model)
fb_out <- hmm_forward_backward(init_matrix(model$init), model$transition, dens, seq_lengths)
pars <- colMeans(fb_out$gamma[seq_begin, , drop = FALSE])
pars[pars < 1e-6] <- 0
model$init <- pars / sum(pars)
The EM functions store response parameters within each state. hmm_em_start(tiny) preserves the transition matrix, stores the initial probabilities in init, and converts each Poisson mean to a log intercept in response[[state]][[response]]. With no response covariates, this intercept is the log of the expected count in that state at any occasion; exponentiating it recovers the state mean. The function hmm_response_data() stores each response column in data[[response]]$y.
The array returned by hmm_densities() is indexed by occasion, response and state and contains ordinary probabilities or densities. By contrast, hmm_emission() returns a matrix of conditional log probabilities or densities indexed by occasion and state. The forward-backward calculation multiplies the response contributions within each occasion. The four functions that set up and evaluate these quantities are in code/lib/hmm.R.
1
2
3
4
5
6
7
8
9
10
hmm_em_start <- function(model) {
K <- length(model$initial)
response <- lapply(seq_len(K), function(i) switch(model$family,
poisson = list(c("(Intercept)" = log(model$parameter[i]))),
normal = list(c("(Intercept)" = model$parameter[i, 1], sd = model$parameter[i, 2])),
indicators = lapply(seq_len(nrow(model$parameter)), function(j)
c("0" = 1 - model$parameter[j, i], "1" = model$parameter[j, i]))))
list(init = model$initial, transition = model$transition, response = response,
family = switch(model$family, indicators = "categorical", model$family))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
hmm_response_data <- function(y, family) {
y <- as.matrix(y)
lapply(seq_len(ncol(y)), function(k) {
v <- y[, k]
if (family == "categorical") {
levels <- levels(factor(v))
indicator <- matrix(vapply(levels, function(l) as.numeric(v == as.numeric(l)),
numeric(length(v))), nrow = length(v), dimnames = list(NULL, levels))
indicator[is.na(v), ] <- NA
list(y = indicator)
} else list(y = matrix(v, ncol = 1L))
})
}
1
2
3
4
5
6
7
hmm_densities <- function(data, model) {
K <- length(model$response)
dens <- array(NA_real_, c(nrow(data[[1]]$y), length(data), K))
for (i in seq_len(K)) for (k in seq_along(data))
dens[, k, i] <- hmm_response_densities(data[[k]], model$response[[i]][[k]], model$family)
dens
}
1
2
3
4
5
6
7
hmm_response_densities <- function(d, par, family) {
X <- matrix(1, nrow(d$y), 1L)
switch(family,
poisson = dpois(x = d$y, lambda = poisson()$linkinv(X %*% par[1L]), log = FALSE),
normal = dnorm(x = d$y, mean = X %*% par[1L], sd = par[[2L]], log = FALSE),
categorical = rowSums(d$y * (X %*% par)))
}
For a Poisson response, hmm_em_start() stores $\log\lambda_k$ as an intercept; for a normal response, the mean and standard deviation; for binary indicators, the probabilities of 0 and 1 in each state. The function hmm_response_data() makes one matrix per response, an indicator matrix with one column per observed category for categorical responses. Entry $(t,j,k)$ of the array from hmm_densities() is $b_k$ for response $j$ at occasion $t$, computed by hmm_response_densities(): the Poisson probability with mean $e^{\text{intercept}}$, the normal density, or the probability of the observed category. The local helper init_matrix() repeats the common initial probability vector in one row per sequence, as required by hmm_forward_backward().
Here seq_begin selects the first row of each sequence. For these three counts its only entry is 1, so the new initial probabilities are 0.97962 and 0.02038. The implementation sets any initial probability below $10^{-6}$ to zero and rescales the vector to sum to one. With many respondents the average uses many first occasions. With one series and fixed transition and response parameters the likelihood is linear in the initial probabilities and may attain its maximum with all the initial probability on a single state. Setting small positive values to zero is an additional numerical rule, not the exact maximizing update just derived. Renormalizing after this change need not preserve the EM likelihood-increase property.
A transition row involves a different count. For each departure state $i$, let $C_{ik}$ be the sum of $\xi_t(i,k)$ over all intervals within sequences. Its row total $D_i=\sum_k C_{ik}$ equals the sum of $\gamma_t(i)$ over occasions with a successor. Maximizing $\sum_k C_{ik}\log a_{ik}$ subject to the row summing to one gives $a_{ik}^{\rm new}=C_{ik}/D_i$ for $D_i>0$. The final row of each sequence, indexed by seq_end, supplies no departure.
In post$xi[t,i,k] the departure index comes first. The array produced by hmm_forward_backward() stores the same probability in fb_out$xi[t,k,i] and assigns NA to each sequence’s final row. Thus pairs[t,k,i] below is $\xi_t(i,k)$, and the code sums over eligible times with the destination k and departure i fixed.
1
2
3
4
5
6
7
8
trans_sum <- matrix(0, K, K)
departures <- fb_out$gamma[-seq_end, , drop = FALSE]; pairs <- fb_out$xi[-seq_end, , , drop = FALSE]
for (i in seq_len(K)) {
d_i <- sum(departures[, i])
trans_sum[i, ] <- if (d_i == 0) model$transition[i, ] else
vapply(seq_len(K), function(k) sum(pairs[, k, i]) / d_i, 0)
}
model$transition <- trans_sum
For state 1 the expected numbers of transitions to states 1 and 2 are 1.40823 and 0.48327. Dividing by their sum gives the new row $(0.74451,0.25549)$. For state 2 the counts are 0.02166 and 0.08684, giving $(0.19961,0.80039)$ with the unrounded counts. In a panel of 200 people interviewed three times, the 600 response rows supply 200 starts and 400 intervals. Each person’s last interview contributes to the response model, and the next person’s first interview begins a new sequence. These are conditional expected counts of transitions, not counts obtained by assigning each interview to a single state.
The backward arrays from hmm_posterior() and hmm_forward_backward() also use different scales. In hmm_forward_backward(), alpha is the filtering probability, scale_t is $1/c_t$, and beta is $r_t(k)/c_t$; it obtains gamma as alpha * beta / scale_t. Thus its beta cannot be substituted directly for the array in Section 13.3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
hmm_forward_backward <- function(init, A, B, seq_lengths) {
B[is.na(B) & !is.nan(B)] <- 1 # a missing response contributes a factor one
dims <- dim(B); B <- if (dims[2] > 1) apply(B, c(1, 3), prod) else array(B, dims[c(1, 3)])
n_t <- nrow(B)
stopifnot(length(seq_lengths) >= 1L, all(is.finite(seq_lengths)),
all(seq_lengths > 0), all(seq_lengths == floor(seq_lengths)), sum(seq_lengths) == n_t)
ns <- ncol(B)
seq_end <- cumsum(seq_lengths)
seq_begin <- seq_end - seq_lengths + 1 # first time of each sequence
alpha <- beta <- matrix(0, n_t, ns)
scale_t <- numeric(n_t)
xi <- array(0, c(n_t, ns, ns))
for (case_i in seq_along(seq_lengths)) {
t1 <- seq_begin[case_i]
alpha[t1, ] <- init[case_i, ] * B[t1, ]
s <- 0
for (i in seq_len(ns)) s <- s + alpha[t1, i]
scale_t[t1] <- 1 / s
alpha[t1, ] <- alpha[t1, ] * scale_t[t1]
if (seq_lengths[case_i] > 1) for (t in (t1 + 1):seq_end[case_i]) {
acc <- numeric(ns)
for (i in seq_len(ns)) acc <- acc + A[i, ] * alpha[t - 1, i]
alpha[t, ] <- acc * B[t, ]
s <- 0
for (j in seq_len(ns)) s <- s + alpha[t, j]
scale_t[t] <- 1 / s
alpha[t, ] <- alpha[t, ] * scale_t[t]
}
t_end <- seq_end[case_i]; beta[t_end, ] <- scale_t[t_end]
if (t_end > t1) {
for (t in t_end:(t1 + 1)) {
acc <- numeric(ns)
for (j in seq_len(ns)) acc <- acc + A[, j] * B[t, j] * beta[t, j]
beta[t - 1, ] <- acc * scale_t[t - 1]
}
for (t in (t1 + 1):seq_end[case_i]) for (i in seq_len(ns))
xi[t - 1, , i] <- alpha[t - 1, i] * A[i, ] * B[t, ] * beta[t, ]
}
}
xi[seq_end, , ] <- NA
list(alpha = alpha, beta = beta, gamma = alpha * beta / scale_t, xi = xi, scale_t = scale_t,
log_lik = -sum(log(scale_t)))
}
A missing response contributes a factor one, and the product over responses gives $b_k(y_t)$ in B. For each sequence the forward loop multiplies the previous filtering probabilities by the transition matrix and by B and stores the reciprocal row sums in scale_t; the backward loop starts from scale_t at the last occasion and multiplies by scale_t at each earlier one, which gives beta the scale stated above. The pair probabilities in xi are stored with the destination index before the departure index, and each sequence’s last row is NA. The log likelihood is $\sum_t\log c_t$, minus the sum of the logs of scale_t. Its ordinary probability products also lack the logarithmic fallback used by hmm_forward().
Which occasions contribute to a Poisson rate? For state $k$, the expected response term involving $\lambda_k$ is $\sum_t\gamma_t(k)[y_t\log\lambda_k-\lambda_k]$. Setting its derivative to zero gives the weighted count divided by the expected occupancy, $\lambda_k^{\rm new}=\sum_t\gamma_t(k)y_t/\sum_t\gamma_t(k)$. This denominator includes the final occasion. The update is made by hmm_fit_response().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
hmm_fit_response <- function(d, par, w, family) {
y <- d$y
n <- nrow(y)
switch(family,
poisson = {
start <- par
start[is.na(start)] <- 0
x <- matrix(1, n, 1L, dimnames = list(NULL, "(Intercept)"))
c("(Intercept)" = unname(hmm_glm_poisson(x, y, w, start)))
},
normal = {
missing_rows <- is.na(rowSums(y))
fit <- hmm_lm_weighted(as.matrix(matrix(1, n, 1L)[!missing_rows, ]), as.matrix(y[!missing_rows, ]), w[!missing_rows])
c("(Intercept)" = unname(fit$coefficients),
sd = sqrt(sum(fit$residuals^2 * w[!missing_rows] / sum(w[!missing_rows]))))
},
categorical = {
observed <- !is.na(rowSums(y)); w_obs <- w[observed]; w_sum <- sum(w_obs)
y_obs <- y[observed, , drop = FALSE]
pars <- vapply(seq_len(ncol(y_obs)), function(j) sum(y_obs[, j] * w_obs) / w_sum, 0); names(pars) <- colnames(y_obs)
small <- pars < 1e-6 # set to zero unless all of them are small
if (!all(small)) pars[small] <- 0
pars / sum(pars)
})
}
For a Poisson response, hmm_glm_poisson() fits the intercept-only Poisson regression with weights $\gamma_t(k)$, whose estimate is $\log\lambda_k^{\rm new}$. For a normal response, hmm_lm_weighted() gives the weighted mean, and the standard deviation is the square root of the weighted average squared residual. For categorical responses, each category probability is the weighted share of that category; values below $10^{-6}$ are set to zero unless all are, and the probabilities are rescaled to sum to one.
1
2
3
4
5
6
family <- model$family
for (i in seq_len(K)) for (k in seq_along(data)) if (sum(fb_out$gamma[, i]) > 0) {
model$response[[i]][[k]] <- hmm_fit_response(data[[k]], model$response[[i]][[k]],
fb_out$gamma[, i], family)
dens[, k, i] <- hmm_response_densities(data[[k]], model$response[[i]][[k]], family)
}
The function hmm_fit_response() passes an intercept column, the counts, their smoothed state probabilities as case weights and the current log rate to hmm_glm_poisson(). Its iteratively reweighted least-squares calculation starts state 2 at $\eta=\log 4$. Given the current mean $\mu=\exp(\eta)$, it fits the working response $\eta+(y_t-\mu)/\mu$ with weights $\gamma_t(k)\mu$, then recalculates the mean. Exponentiating the returned intercept puts the estimate on the count scale. Each response fit receives the column of smoothed probabilities for its state, including the final row. These case weights are conditional probabilities of state membership, not survey sampling weights.
With missing counts, both sums in the rate update must use the observed occasions for that response. A positive denominator is required; a zero weighted count would place the maximizing Poisson mean at zero, outside the strictly positive rates allowed by hmm_model().
Run one full update from tiny with random initialization turned off. The index runs over 0:maxit. A last index of zero permits one update, and the default last index of 500 permits up to 501. The function is hmm_em() in code/lib/hmm.R, shown in two parts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
hmm_em <- function(y, K, family = c("poisson", "normal", "categorical"), seq_lengths = NROW(y),
start = NULL, maxit = 500L, tol = 1e-8, shuffle_start = TRUE) {
family <- match.arg(family)
data <- hmm_response_data(y, family)
n_seq <- length(seq_lengths); seq_end <- cumsum(seq_lengths)
seq_begin <- seq_end - seq_lengths + 1
# The starting model: the default one unless given.
model <- if (is.null(start)) hmm_default_model(data, K, family) else start
model$family <- family
init_matrix <- function(p) matrix(1, n_seq, 1L) %*% p
dens <- hmm_densities(data, model)
if (shuffle_start) {
gamma <- hmm_dirichlet_draws(sum(seq_lengths), alpha = rep(.01, K))
for (i in seq_len(K)) for (k in seq_along(data)) {
model$response[[i]][[k]] <- hmm_fit_response(data[[k]], model$response[[i]][[k]],
gamma[, i], family)
dens[, k, i] <- hmm_response_densities(data[[k]], model$response[[i]][[k]], family)
}
}
fb_out <- hmm_forward_backward(init_matrix(model$init), model$transition, dens, seq_lengths)
LL <- fb_out$log_lik
if (is.nan(LL)) stop("Starting values not feasible; please provide them.")
ll_old <- LL + 1
history <- LL
converge <- decreased <- FALSE
Without start, hmm_default_model() supplies the starting model, and with shuffle_start the response parameters are first refitted to state probabilities drawn from a Dirichlet distribution with parameters 0.01 by hmm_dirichlet_draws().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
for (j in 0:maxit) {
iterations <- j
pars <- colMeans(fb_out$gamma[seq_begin, , drop = FALSE])
pars[pars < 1e-6] <- 0
model$init <- pars / sum(pars)
trans_sum <- matrix(0, K, K)
departures <- fb_out$gamma[-seq_end, , drop = FALSE]; pairs <- fb_out$xi[-seq_end, , , drop = FALSE]
for (i in seq_len(K)) {
d_i <- sum(departures[, i])
trans_sum[i, ] <- if (d_i == 0) model$transition[i, ] else
vapply(seq_len(K), function(k) sum(pairs[, k, i]) / d_i, 0)
}
model$transition <- trans_sum
# (a state with no departures keeps its previous row)
for (i in seq_len(K)) for (k in seq_along(data)) if (sum(fb_out$gamma[, i]) > 0) {
model$response[[i]][[k]] <- hmm_fit_response(data[[k]], model$response[[i]][[k]],
fb_out$gamma[, i], family)
dens[, k, i] <- hmm_response_densities(data[[k]], model$response[[i]][[k]], family)
}
fb_out <- hmm_forward_backward(init_matrix(model$init), model$transition, dens, seq_lengths)
LL <- fb_out$log_lik
history <- c(history, LL)
if (LL >= ll_old) {
converge <- (LL - ll_old) / abs(ll_old) < tol
if (converge) break
} else {
if (j > 0 && tol < (ll_old - LL)) { decreased <- TRUE; break }
if (j > 0 && abs(LL - ll_old) / abs(ll_old) < tol) {
decreased <- converge <- TRUE
break
}
}
ll_old <- LL
}
reason <- if (converge && !decreased) "relative change below tolerance" else if (converge)
"decrease within tolerance" else if (decreased) "likelihood decreased" else "iteration limit"
# Free parameters: K - 1 initial, K(K - 1) transition, and the response parameters.
df <- (K - 1) + K * (K - 1) + K * sum(vapply(data, function(d) switch(family,
poisson = 1, normal = 2, categorical = ncol(d$y) - 1), 0))
list(model = model, loglik = LL, iterations = iterations, converged = converge,
reason = reason, history = history, posterior = fb_out$gamma, df = df, nobs = sum(seq_lengths),
AIC = -2 * LL + 2 * df, BIC = -2 * LL + log(sum(seq_lengths)) * df)
}
Each iteration applies the three updates above: the initial probabilities from the first occasions, the transition rows $C_{ik}/D_i$, and the response parameters by hmm_fit_response(), followed by a new forward-backward pass. The iterations stop when the log likelihood increases by less than tol relative to its previous value, or when it decreases by more than tol. The parameter count df adds $K-1$ initial probabilities, $K(K-1)$ transition probabilities and the response parameters of each state.
1
2
3
4
5
6
7
one_update <- hmm_em(matrix(y), 2L, "poisson", start = hmm_em_start(tiny), maxit = 0L,
shuffle_start = FALSE)
new_rates <- exp(vapply(one_update$model$response, function(r) unname(r[[1]][1]), 0.0))
print(list(expected_initial = post$gamma[1, ],
expected_transitions = apply(post$xi, 2:3, sum),
new_initial = one_update$model$init, new_transition = one_update$model$transition,
new_rates = new_rates, before = one_update$history[1], after = one_update$loglik))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$expected_initial
[1] 0.97961817 0.02038183
$expected_transitions
[,1] [,2]
[1,] 1.40823090 0.48326770
[2,] 0.02165749 0.08684391
$new_initial
[1] 0.97961817 0.02038183
$new_transition
[,1] [,2]
[1,] 0.7445054 0.2554946
[2,] 0.1996056 0.8003944
$new_rates
[1] 1.023406 2.597989
$before
[1] -5.058364
$after
[1] -4.32225
Using the updated initial probabilities, transition rows and rates raises the observed-data log likelihood from $-5.058364$ to $-4.322250$. To check the response update, compare the weighted count with total occupancy, and contrast that denominator with expected departures.
1
2
3
4
print(data.frame(state=seq_along(tiny$initial),occupancy=colSums(post$gamma),
expected_departures=colSums(post$gamma[-length(y),,drop=FALSE]),
weighted_count=drop(crossprod(post$gamma,y)),
weighted_mean=drop(crossprod(post$gamma,y))/colSums(post$gamma),new_rate=new_rates))
1
2
3
state occupancy expected_departures weighted_count weighted_mean new_rate
1 1 2.4095066 1.8914986 2.465904 1.023406 1.023406
2 2 0.5904934 0.1085014 1.534096 2.597989 2.597989
For state 2 the weighted count is 1.534096 and the expected occupancy is 0.5904934, so the rate becomes 2.597989. Only 0.1085014 of its occupancy provides a departure.
The EM loop and its stopping test
The EM routine hmm_em() repeats such updates in its own loop. A state with zero expected departures retains its former transition row. A state with zero total occupancy retains its former response parameters. After updating, the routine recomputes the forward and backward quantities with the new parameters and appends the observed-data log likelihood to history. At fixed candidate parameters, hmm_em_loglik(matrix(y), one_update$model) returns the updated log likelihood using the same scaled forward and backward recursions. The history begins at the actual starting log likelihood, so diff(one_update$history) gives the gain in the worked update.
For the first stopping test only, ll_old is initialized to the starting log likelihood plus one. For the worked step the log likelihood gained 0.73611, but it fell short of that first comparison value. The fit stopped at its requested iteration limit.
From update two onward ll_old contains the actual preceding log likelihood. For a nonnegative change the test is (LL - ll_old) / abs(ll_old) < tol, with tol = 1e-8 by default. After index zero, an absolute loss exceeding the tolerance stops the fit as a decrease. A remaining loss small enough to pass the relative test is reported as a decrease within tolerance. After a decrease the returned parameters are the decreased-likelihood update, and a zero preceding log likelihood would make the relative-change denominator zero.
Updates for other response families
The same initial and transition updates apply with other response families. The observed Nile series distributed with R records annual river flow at Aswan from 1871 to 1970 in units of $10^8$ cubic meters. The R dataset documentation describes the source. For a normal response model for these measurements, $Y_t\mid S_t=k\sim N(\mu_k,\sigma_k^2)$. The state mean $\mu_k$ is the expected measurement at an occasion in state $k$. The variance $\sigma_k^2$ describes variation around that mean within the state, so increasing it at fixed $\mu_k$ spreads the conditional response distribution. The standard deviation $\sigma_k$ has the same units as the response, while the variance has squared units.
For the annual Nile measurements let $w_t=\gamma_t(k)$ and $W=\sum_t w_t$ over observed measurements. In the normal log likelihood the weighted residual sum of squares is minimized at $\bar y_w=\sum_t w_t y_t/W$. Differentiating in the variance gives $\sum_t w_t(y_t-\bar y_w)^2/W$. The function hmm_fit_response() stores its square root. This update requires positive total weight among observed measurements; a zero weighted variance does not give an admissible positive standard deviation.
In hmm_model(), row k of parameter stores the mean in column 1 and the standard deviation in column 2. The EM form stores them as "(Intercept)" and sd in response[[k]][[1]].
For a binary panel item, let $H$ be the weighted sum of ones and $W$ the sum of weights over people and occasions with an observed answer to that item. Maximizing $H\log p+(W-H)\log(1-p)$ gives $p=H/W$ for $W>0$.
For an item, hmm_fit_response() normalizes the category probabilities after setting values below $10^{-6}$ to zero, and hmm_em_model() extracts the probability named "1". The categorical cutoff again modifies the exact update, and extracting the category named “1” requires that this category was retained explicitly in the response data.
Fits from different starts
How sensitive is the fitted count model to its start? Use the 250 observed counts in series$observed. With seed 1304, the random start draws a vector of state probabilities independently for each occasion from a symmetric Dirichlet distribution with concentration 0.01 per state. These randomly generated weights take the place of the smoothed state probabilities in the first response fits. The initial distribution and each transition row start uniform.
For two fixed alternatives, start both states with equal initial probabilities and set the rates to the sample quartiles, 1 and 5. For $s=0.4$ and $0.97$ use $sI+(1-s)\mathbf{1}\mathbf{1}^\top/2$, where $I$ is the two-state identity matrix and $\mathbf{1}$ is a column of ones. The stay probabilities are 0.7 and 0.985.
The actual likelihood increments show progress, and sorting the final rates aligns the states across the three fits. The Dirichlet distribution generates starting values here; it is not a prior distribution used to estimate the model parameters. Sorting rates suffices for this display, but comparing complete models requires applying the same permutation to every state-indexed quantity. The fitted lists are converted by hmm_em_model().
1
2
3
4
5
6
7
8
9
10
hmm_em_model <- function(fit) {
m <- fit$model
parameter <- switch(m$family,
poisson = exp(vapply(m$response, function(r) unname(r[[1]][1]), 0.0)),
normal = t(vapply(m$response, function(r) unname(r[[1]]), numeric(2))),
categorical = matrix(vapply(m$response, function(r) vapply(r, function(p)
unname(p[["1"]]), 0.0), numeric(length(m$response[[1]]))), ncol = length(m$response)))
hmm_model(m$init, m$transition, parameter,
switch(m$family, categorical = "indicators", m$family))
}
It returns the model in the form of hmm_model(), exponentiating the Poisson intercepts and taking the probability of 1 for each indicator.
1
2
3
set.seed(1304)
bw <- hmm_em(matrix(series$observed), 2L, "poisson")
bw_model <- hmm_em_model(bw)
The first fit is bw. Differences between consecutive history entries give the increments. Table 13.1 summarizes selected columns of start_summary, rounded for display.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fits <- c(list(bw), lapply(c(.4, .97), function(s) {
model <- hmm_model(c(.5, .5), s * diag(2) + (1 - s) * matrix(.5, 2, 2),
pmax(.1, as.numeric(quantile(series$observed, c(.25, .75)))))
hmm_em(matrix(series$observed), 2L, "poisson", start = hmm_em_start(model),
shuffle_start = FALSE)
}))
start_summary <- do.call(rbind, lapply(1:3, function(i) {
f <- fits[[i]]
rates <- sort(hmm_em_model(f)$parameter)
gaps <- diff(f$history)
data.frame(start = i, start_rate1 = if (i == 1) NA else quantile(series$observed, .25),
start_rate2 = if (i == 1) NA else quantile(series$observed, .75),
start_stay = c(NA, .7, .985)[i], steps = length(gaps), last_gain = tail(gaps, 1),
min_gain = min(gaps), rate1 = rates[1], rate2 = rates[2], loglik = f$loglik,
converged = f$converged, stop = f$reason)
}))
print(start_summary)
Table 13.1. EM fits of the two-state Poisson model to the HMM2 counts from three starts.
| Start | Updates | Smallest log likelihood gain | Lower rate | Higher rate | Log likelihood |
|---|---|---|---|---|---|
| Random | 21 | 4.51e-06 | 1.84626 | 7.96550 | -502.36866 |
| Fixed, stay 0.7 | 21 | 3.33e-06 | 1.84626 | 7.96550 | -502.36866 |
| Fixed, stay 0.985 | 14 | 2.17e-06 | 1.84626 | 7.96550 | -502.36866 |
All three histories increase at every update. The starts reach log likelihood $-502.36866$ and rates near 1.84626 and 7.96550 at the precision shown. The more persistent fixed start takes 14 updates, compared with 21 for the other two. In bw_model the higher rate is printed first. Its state has initial probability about $2.7\times10^{-6}$ and stay probability 0.91667. The lower-rate state has stay probability 0.96866. The initial probability concerns the first count in this particular series, while a stay probability concerns what happens after entering a state. The random-start fit stops on the relative gain at index 20, its twenty-first update.
The latent transition panel
The same routine also fits the repeated survey, in which each respondent contributes three rows with six binary answers per row. Stack the observed matrices in person order and pass the vector of person-specific sequence lengths to hmm_em(). The 200 first occasions occupy rows 1, 4 and so on through 598. Rows 3, 6 and so on through 600 end the sequences, so the likelihood includes only within-person transitions. Seed 1314 supplies a fresh set of random starting state probabilities under the same initialization rule. The two components of the output describe the preceding count fit and the three-state panel fit.
1
2
3
4
5
6
7
8
9
10
occasion_matrix <- do.call(rbind, occasions)
set.seed(1314)
latent_transition_fit <- hmm_em(occasion_matrix, 3L, "categorical",
seq_lengths = rep(3L, length(occasions)))
print(list(Poisson = list(model = bw_model, loglik = bw$loglik,
iterations = bw$iterations,
stop = bw$reason),
indicators = list(model = hmm_em_model(latent_transition_fit),
loglik = latent_transition_fit$loglik, iterations = latent_transition_fit$iterations,
stop = latent_transition_fit$reason)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
$Poisson
$Poisson$model
$Poisson$model$initial
[1] 2.686553e-06 9.999973e-01
$Poisson$model$transition
[,1] [,2]
[1,] 0.91667438 0.08332562
[2,] 0.03133892 0.96866108
$Poisson$model$family
[1] "poisson"
$Poisson$model$parameter
[1] 7.965498 1.846255
$Poisson$loglik
[1] -502.3687
$Poisson$iterations
[1] 20
$Poisson$stop
[1] "relative change below tolerance"
$indicators
$indicators$model
$indicators$model$initial
[1] 0.2788482 0.2889217 0.4322301
$indicators$model$transition
[,1] [,2] [,3]
[1,] 0.9032615449 7.735251e-11 0.09673845
[2,] 0.0487143176 7.874431e-01 0.16384256
[3,] 0.0001893826 8.814702e-02 0.91166360
$indicators$model$family
[1] "indicators"
$indicators$model$parameter
[,1] [,2] [,3]
[1,] 0.1536134 0.8573995 0.6295136
[2,] 0.1870563 0.9103278 0.5944511
[3,] 0.2053336 0.7037348 0.6270221
[4,] 0.1495080 0.8287570 0.2660978
[5,] 0.1545403 0.8918828 0.1593084
[6,] 0.2570198 0.7600375 0.3010482
$indicators$loglik
[1] -2155.032
$indicators$iterations
[1] 174
$indicators$stop
[1] "relative change below tolerance"
The panel fit stops at index 174 after 175 updates, with log likelihood $-2155.032$. Each column contains one state’s item probabilities. Fitted state 1 has low probabilities on all six items, state 2 has high probabilities throughout, and state 3 has higher probabilities on the first three items than on the last three. These profiles put fitted states 1, 3 and 2 in the order of generating states 1, 2 and 3. In that order the initial estimates are 0.279, 0.432 and 0.289, against 0.3, 0.4 and 0.3. The same permutation applies to departure rows and arrival columns. The estimated $1\to3$ probability is the printed row 1, column 2 entry, about $7.7\times10^{-11}$. For $2\to1$ it is row 3, column 1, about $1.9\times10^{-4}$. Both generating probabilities are 0.075. The fitted values describe rare transitions under the estimated model. Assessing their precision requires information beyond these point estimates.
Here the initial proportions are free. Requiring a stationary initial distribution would impose $\pi A=\pi$, so changing a transition row could also change the initial-state term of the expected log likelihood. The M step would then have to account for the transition rows jointly.
The supplied hmm_em() and hmm_forward_backward() are adapted from depmixS4 (code/NOTICE.md), in which hidden Markov models can also be fitted by EM.
13.5 Direct likelihood optimization with transformed transition probabilities
Can the two-state model be fitted to the 250 counts by optimizing the observed-data likelihood directly? Each transition row must sum to one. Take staying in the departure state $i$ as the reference and assign the other destinations coordinates $\eta_{ij}=\log(a_{ij}/a_{ii})$ for $j\ne i$. These are baseline-category logits with a different reference category in each row. With the other coordinates in row $i$ fixed, a one-unit increase in $\eta_{ij}$ multiplies the ratio $a_{ij}/a_{ii}$ by $e$. Recovering the probabilities renormalizes all destinations in that row.
Fill the off-diagonal entries one column at a time. For two states the coordinate for moving from 2 to 1 therefore comes before the coordinate for moving from 1 to 2. For the initial distribution use state 1 as the common reference, with $\zeta_k=\log(\pi_k/\pi_1)$ for $k>1$, and for each Poisson mean use $\rho_k=\log\lambda_k$.
In exact arithmetic, finite coordinates give strictly positive probabilities and rates. Direct exponentiation can nevertheless overflow or underflow in floating-point arithmetic.
With one sequence and fixed transition and response parameters, let $L_k$ denote its probability given initial state $k$. The likelihood $\sum_k\pi_k L_k$ is maximized by assigning all initial probability to the state with the largest $L_k$ when it is unique. In the two-state model this requires sending $\zeta_2$ toward minus infinity to put all initial probability on state 1, $(1,0)$, or toward plus infinity to put it all on state 2, $(0,1)$. If several states tie for the largest value, every distribution supported on those states also maximizes the likelihood.
The usual quadratic likelihood approximation for standard errors assumes that small changes in every free parameter direction remain allowed and that the relevant information matrix is nonsingular. A zero initial or transition probability violates the first condition; indistinguishable states can violate the second.
To recover the transition probabilities, place a one on the diagonal of each row, exponentiate its off-diagonal coordinates and divide by the row sum. The initial probabilities are obtained by normalizing $(1,e^{\zeta_2},\ldots,e^{\zeta_K})$, and the means by setting $\lambda_k=e^{\rho_k}$. Here $K$ is the number of states. In code/lib/hmm.R the $m=K(K-1)$ transition coordinates come first, followed by $K-1$ initial coordinates and $K$ log rates. The following functions map a trial vector to the model and evaluate its negative log likelihood. The order of these coordinates is part of the function interface, not a statistical ordering of the states. The supplied direct likelihood routines implement only one fully observed Poisson sequence and one through four states.
1
2
3
4
5
6
hmm_direct_model <- function(par, K) {
m <- K * (K - 1L)
delta <- c(1, exp(par[m + seq_len(K - 1L)]))
list(delta = delta / sum(delta), Gamma = hmm_transition_matrix(par[seq_len(m)]),
lambda = exp(par[m + K - 1L + seq_len(K)]))
}
Inside hmm_transition_matrix(), Gamma[j, i] places each exponentiated value in departure row j of destination column i. The next function evaluates the observed-data criterion at the model returned by this map.
1
2
3
4
5
6
hmm_direct_nll <- function(par, y, K) {
p <- hmm_direct_model(par, K)
emis_probs <- matrix(1, length(y), K)
for (j in seq_len(K)) emis_probs[, j] <- dpois(y, p$lambda[j])
-hmm_forward_direct(p$delta, p$Gamma, emis_probs)
}
The list from hmm_direct_model() uses delta for the initial vector $\pi$, Gamma for the departure-by-arrival matrix $A$, and lambda for the Poisson means. These are the same natural-scale quantities stored as initial, transition and parameter by hmm_model(); the different field names do not change the model.
Row $t$ of emis_probs contains the Poisson probabilities of the observed count $y_t$ under each state. The first row is multiplied by the initial probabilities. At subsequent occasions hmm_forward_direct() predicts the next state distribution from the preceding filtering probabilities and multiplies it by the new conditional response row. The resulting row sums to the predictive probability $c_t$ of the current count. Dividing its entries by $c_t$ gives the filtering probabilities at time $t$. The value returned to the minimizer is $-\sum_t\log c_t$. This implementation uses the Poisson probabilities directly. At equal initial probabilities and means 1.5 and 7, for example, the first count of 5 has predictive probability $c_1=0.5b_1(5)+0.5b_2(5)\approx0.0709183$ before either transition row is used.
Unlike the logarithmic recursion, this routine has no fallback for a row whose probabilities underflow. The analytic-gradient routine below uses the more stable posterior calculation, so extreme inputs require checking that both routines evaluate the same finite likelihood.
The score from posterior expected counts
The derivative of this negative log likelihood follows from the derivative of the observed-data log likelihood. Let $p_u(y,s)$ be the joint probability of the counts and a state path $s$ at a coordinate vector $u$. Differentiating the finite sum over paths gives the observed-data score vector, that is, the gradient of its log likelihood
\[\nabla_u\log p_u(y) =\frac{\sum_s \nabla_u p_u(y,s)}{p_u(y)} =\sum_s \frac{p_u(y,s)}{p_u(y)}\,\nabla_u\log p_u(y,s).\]The conditional expectation on the right replaces the complete-data counts by their posterior expectations. Write $n_{ij}=\sum_{t<T}\xi_t(i,j)$ and $n_{i\cdot}=\sum_j n_{ij}$. For a departure from $i$ followed by an arrival in $l$, the derivative of $\log a_{il}$ with respect to $\eta_{ij}$ is $\mathbf{1}_{\lbrace l=j\rbrace }-a_{ij}$. Summing over expected transitions gives the corresponding component of the score vector $n_{ij}-n_{i\cdot}a_{ij}$.
The component for $\log(\pi_2/\pi_1)$ is $\gamma_1(2)-\pi_2$. For $\rho_k$ the Poisson log probability has derivative $y_t-\lambda_k$ whenever the state is $k$, giving $\sum_t\gamma_t(k)(y_t-\lambda_k)$.
The score calculation in code/lib/hmm.R follows the same column order as the parameter vector. In exact arithmetic, at finite logit and log-rate coordinates the paths in this Poisson calculation have positive joint probabilities. The posterior expectations in this identity are evaluated at the same coordinate vector as the derivative.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
hmm_direct_nll_gradient <- function(par, y, K) {
p <- hmm_direct_model(par, K)
post <- hmm_posterior(y, hmm_model(p$delta, p$Gamma, p$lambda, "poisson"))
counts <- apply(post$xi, 2:3, sum)
departures <- rowSums(counts)
# Score components for transition log ratios, in destination-column order.
transition <- unlist(lapply(seq_len(K), function(j) {
i <- setdiff(seq_len(K), j)
counts[i, j] - departures[i] * p$Gamma[i, j]
}))
initial <- (post$gamma[1L, ] - p$delta)[-1L]
rates <- colSums(post$gamma * outer(y, p$lambda, "-"))
-c(transition, initial, rates)
}
At off-diagonal probabilities 0.2, equal initial probabilities and rates 1.5 and 7, hmm_direct_nll_gradient() evaluates all five derivatives for series$observed. Negating its negative log likelihood gradient gives the score vector.
1
2
3
4
start_par <- c(qlogis(c(.2, .2)), 0, log(c(1.5, 7)))
start_natural <- hmm_direct_model(start_par, 2L)
start <- hmm_model(start_natural$delta, start_natural$Gamma, start_natural$lambda)
nll <- function(u) hmm_direct_nll(u, series$observed, 2L)
1
2
nll_gradient_at_start <- hmm_direct_nll_gradient(start_par, series$observed, 2L)
print(c(loglik_score = -nll_gradient_at_start))
1
2
loglik_score1 loglik_score2 loglik_score3 loglik_score4 loglik_score5
-3.1090260 -22.4157681 0.2159749 32.2290203 41.6526606
The first value concerns departures from state 2. At the starting parameters its expected number of transitions to state 1 is about 12.4951 across 78.0205 expected departures, giving $12.4951-0.2(78.0205)\approx-3.1090$. The second value is for departures from state 1. To check signs and coordinate order, compare the two gradients of the negative log likelihood at this same point.
1
2
3
4
print(sapply(10^-(2:7), function(h) c(step = h,
relative_difference = max(abs(num_grad(nll, start_par, step = h)$gradient -
nll_gradient_at_start)) /
max(abs(nll_gradient_at_start)))))
1
2
3
4
5
6
[,1] [,2] [,3] [,4]
step 0.0100000000 1.000000e-03 1.000000e-04 1.000000e-05
relative_difference 0.0001551782 1.551792e-06 1.556432e-08 7.778632e-10
[,5] [,6]
step 1.000000e-06 1.000000e-07
relative_difference 6.403835e-09 7.479234e-08
For each coordinate, num_grad() (Section 3.1) uses step $h$. The reported discrepancy is the largest absolute component error divided by the largest absolute component of the gradient obtained from the posterior expected counts, about 41.65. It falls from $1.55\times10^{-4}$ at $h=10^{-2}$ to $7.78\times10^{-10}$ at $10^{-5}$. At $10^{-6}$ and $10^{-7}$ it rises to about $6.4\times10^{-9}$ and $7.5\times10^{-8}$, a pattern consistent with rounding in the subtraction of nearly equal negative log likelihood values.
Direct and EM fits from the same start
Both fitting methods start from the point used for the score check. The quasi-Newton routine factored_secant_minimize() takes the scalar function nll and computes its own finite-difference gradients. It is translated from the minimizer of nlm() and appears below in five parts, which together form the function in code/lib/factored_secant.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
factored_secant_minimize <- function(f, p, typical_size = rep_len(1, length(p)), typical_f = 1, n_digits = 12,
grad_tol = 1e-6, step_tol = 1e-6,
max_step = max(1000 * sqrt(sum(scaled_p^2)), 1000), maxit = 100) {
n <- length(p)
dot <- function(a, b) {
total <- 0
for (i in seq_along(a)) total <- total + a[i] * b[i]
total
}
hypot <- function(a, b) Mod(complex(real = a, imaginary = b))
evaluations <- 0L
eval_f <- function(x) {
if (any(!is.finite(x))) stop("non-finite value supplied by 'nlm'")
evaluations <<- evaluations + 1L
value <- f(x)
if (!is.null(attr(value, "gradient"))) stop("analytic gradients are not handled here")
value <- as.numeric(value)
stopifnot(length(value) == 1L)
if (!is.finite(value)) {
warning(if (identical(value, -Inf)) "-Inf replaced by maximally negative value" else
"NA/NaN or Inf replaced by maximum positive value")
value <- if (identical(value, -Inf)) -.Machine$double.xmax else .Machine$double.xmax
}
value
}
# Checks of the controls
typical_size[typical_size == 0] <- 1
typical_size <- abs(typical_size)
scale_x <- 1 / typical_size; scaled_p <- p / typical_size # p in typical units (default max_step)
if (max_step <= 0) {
total <- 0
for (i in seq_len(n)) total <- total + p[i] * p[i] * scale_x[i] * scale_x[i]
max_step <- 1000 * max(sqrt(total), 1)
}
typical_f <- if (typical_f == 0) 1 else abs(typical_f)
mach_eps <- .Machine$double.eps
noise <- max(10^(-n_digits), mach_eps)
forward <- function(x, fx) {
g <- numeric(n)
for (j in seq_len(n)) {
step <- sqrt(noise) * max(abs(x[j]), 1 / scale_x[j])
xt <- x
xt[j] <- x[j] + step
g[j] <- (eval_f(xt) - fx) / step
}
g
}
central <- function(x) {
g <- numeric(n)
for (i in seq_len(n)) {
step <- noise^(1 / 3) * max(abs(x[i]), 1 / scale_x[i])
xt <- x
xt[i] <- x[i] + step
f_up <- eval_f(xt)
xt[i] <- x[i] - step
f_down <- eval_f(xt)
g[i] <- (f_up - f_down) / (step * 2)
}
g
}
The first part prepares the evaluations. eval_f() counts them and replaces a nonfinite value by the largest representable number, or $-\infty$ by the most negative one, with a warning. With $\delta=\max(10^{-d},\epsilon)$, where $d$ is n_digits, and $t_j$ the typical size of coordinate $j$, forward() uses steps $\sqrt\delta\max(\vert x_j\vert ,t_j)$ and central() steps $\delta^{1/3}\max(\vert x_j\vert ,t_j)$ on each side.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
stop_code <- function(x_new, f_new, g_new, x, n_iter, search_code, near_maximum_step) {
if (search_code == 1L) return(3L)
d <- max(abs(f_new), typical_f)
max_rel_grad <- 0
for (i in seq_len(n)) {
rel_grad <- abs(g_new[i]) * max(abs(x_new[i]), 1 / scale_x[i]) / d
if (max_rel_grad < rel_grad) max_rel_grad <- rel_grad
}
code <- 1L
if (max_rel_grad > grad_tol) {
if (n_iter == 0L) return(0L)
max_rel_step <- 0
for (i in seq_len(n)) {
rel_step <- abs(x_new[i] - x[i]) / max(abs(x_new[i]), 1 / scale_x[i])
if (max_rel_step < rel_step) max_rel_step <- rel_step
}
code <- 2L
if (max_rel_step > step_tol) {
code <- 4L
if (n_iter < maxit) {
if (!near_maximum_step) {
n_max_steps <<- 0L
return(0L)
}
n_max_steps <<- n_max_steps + 1L
if (n_max_steps < 5L) return(0L)
code <- 5L
}
}
}
code
}
# Solve L L' p = b with L the lower triangle of a.
solve_factor <- function(a, b) {
b[1] <- b[1] / a[1, 1]
if (n >= 2) for (j in 2:n) {
temp <- -b[j - 1]
if (temp != 0) for (i in j:n) b[i] <- b[i] + temp * a[i, j - 1]
b[j] <- b[j] / a[j, j]
}
b[n] <- b[n] / a[n, n]
if (n >= 2) for (jj in 2:n) {
j <- n - jj + 1
b[j] <- b[j] - dot(a[(j + 1):n, j], b[(j + 1):n])
b[j] <- b[j] / a[j, j]
}
b
}
The stopping codes are 1 when the largest relative gradient component $\vert g_i\vert \max(\vert x_i\vert ,t_i)/\max(\vert f\vert ,f_{\rm typ})$ is at most grad_tol, 2 when the largest relative step $\vert \Delta x_i\vert /\max(\vert x_i\vert ,t_i)$ is at most step_tol, 3 when the line search fails, 4 at the iteration limit and 5 after five consecutive steps of the maximum length. The function solve_factor() solves $LL^\top p=b$ for the lower triangular factor $L$ stored in the lower triangle of a.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
line_search <- function(x, fx, g, p) {
total <- 0
for (i in seq_len(n)) total <- total + scale_x[i] * scale_x[i] * p[i] * p[i]
p_norm <- sqrt(total)
if (p_norm > max_step) {
p <- (max_step / p_norm) * p
p_norm <- max_step
}
slope <- dot(g, p)
rel_len <- 0
for (i in seq_len(n)) {
temp <- abs(p[i]) / max(abs(x[i]), 1 / scale_x[i])
if (rel_len < temp) rel_len <- temp
}
lambda_min <- step_tol / rel_len
lambda <- 1
first_try <- TRUE
f_prev <- 0
lambda_prev <- 0
repeat {
x_new <- x + lambda * p
f_new <- eval_f(x_new)
if (f_new <= fx + slope * 1e-4 * lambda) {
return(list(x_new = x_new, f_new = f_new, search_code = 0L,
near_maximum_step = lambda == 1 && p_norm > max_step * .99))
}
if (lambda < lambda_min) return(list(x_new = x_new, f_new = f_new, search_code = 1L, near_maximum_step = FALSE))
if (f_new >= .Machine$double.xmax) {
lambda <- lambda * .1
first_try <- TRUE
} else {
if (first_try) {
lambda_try <- -lambda * slope / ((f_new - fx - slope) * 2)
first_try <- FALSE
} else {
t1 <- f_new - fx - lambda * slope
t2 <- f_prev - fx - lambda_prev * slope
t3 <- 1 / (lambda - lambda_prev)
a3 <- 3 * t3 * (t1 / (lambda * lambda) - t2 / (lambda_prev * lambda_prev))
b <- t3 * (t2 * lambda / (lambda_prev * lambda_prev) - t1 * lambda_prev / (lambda * lambda))
disc <- b * b - a3 * slope
lambda_try <- if (disc > b * b) (-b + (if (a3 < 0) -sqrt(disc) else sqrt(disc))) / a3 else
(-b + (if (a3 < 0) sqrt(disc) else -sqrt(disc))) / a3
if (lambda_try > lambda * .5) lambda_try <- lambda * .5
}
lambda_prev <- lambda
f_prev <- f_new
lambda <- if (lambda_try < lambda * .1) lambda * .1 else lambda_try
}
}
}
The line search first shortens a direction longer than max_step in scaled units. It accepts $x+\lambda p$ when $f(x+\lambda p)\leq f(x)+10^{-4}\lambda g^\top p$. The first reduction of $\lambda$ minimizes the quadratic through $f(x)$, the slope $g^\top p$ and the trial value; later reductions minimize the cubic through the last two trials, limited to between 0.1 and 0.5 of the current $\lambda$. A failed evaluation divides $\lambda$ by ten, and $\lambda$ below step_tol divided by the largest relative component of $p$ ends the search with failure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
rotate <- function(a, i, c1, c2) {
den <- hypot(c1, c2)
c <- c1 / den
s <- c2 / den
for (col in i:n) {
y <- a[i, col]
z <- a[i + 1, col]
a[i, col] <- c * y - s * z
a[i + 1, col] <- s * y + c * z
}
a
}
swap <- function(a, i) {
for (col in i:n) {
tmp <- a[i, col]
a[i, col] <- a[i + 1, col]
a[i + 1, col] <- tmp
}
a
}
qr_update <- function(a, u, v) {
k <- n
while (k > 1 && u[k] == 0) k <- k - 1
if (k > 1) {
ii <- k
while (ii > 1) {
i <- ii - 1
if (u[i] == 0) {
a <- swap(a, i)
u[i] <- u[ii]
} else {
a <- rotate(a, i, u[i], -u[ii])
u[i] <- hypot(u[i], u[ii])
}
ii <- i
}
}
for (j in seq_len(n)) a[1, j] <- a[1, j] + u[1] * v[j]
for (i in seq_len(k - 1)) {
if (a[i, i] == 0) a <- swap(a, i) else a <- rotate(a, i, a[i, i], -a[i + 1, i])
}
a
}
secant <- function(a, x, g, x_new, g_new, n_iter, central_used) {
s <- x_new - x
y <- g_new - g
sy <- dot(s, y)
if (sy < sqrt(mach_eps) * dg_norm2(s) * dg_norm2(y)) return(a)
u <- numeric(n)
for (i in seq_len(n)) u[i] <- dot(a[i:n, i], s[i:n])
uu <- dot(u, u)
ratio <- sqrt(sy / uu)
if (n_iter == 1L) {
for (j in seq_len(n)) {
u[j] <- ratio * u[j]
for (i in j:n) a[i, j] <- a[i, j] * ratio
}
uu <- sy
ratio <- 1
}
w <- numeric(n)
for (i in seq_len(n)) w[i] <- dot(a[i, seq_len(i)], u[seq_len(i)])
rel_tol <- if (central_used) noise else sqrt(noise)
skip <- TRUE
for (i in seq_len(n)) {
skip <- abs(y[i] - w[i]) < rel_tol * max(abs(g[i]), abs(g_new[i]))
if (!skip) break
}
if (skip) return(a)
w <- y - ratio * w
ratio <- ratio / sy
u <- u * ratio
if (n >= 2) for (i in 2:n) for (j in seq_len(i - 1)) {
a[j, i] <- a[i, j]
a[i, j] <- 0
}
a <- qr_update(a, u, w)
if (n >= 2) for (i in 2:n) for (j in seq_len(i - 1)) a[i, j] <- a[j, i]
a
}
The fourth part updates the model Hessian $H=LL^\top$ by the BFGS formula $H+yy^\top/(s^\top y)-Hss^\top H/(s^\top Hs)$, with $s$ the step and $y$ the change in gradient, working on the factor: qr_update() applies Givens rotations (rotate(), swap()) to obtain the new factor from the rank-one change computed with $u=L^\top s$. At the first iteration the factor is first rescaled so that $u^\top u=s^\top y$. The update is skipped when $s^\top y<\sqrt\epsilon\Vert s\Vert \Vert y\Vert $ or when $y$ differs from $Hs$ by less than the gradient noise in every component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
x <- as.double(p)
fx <- eval_f(x)
g <- forward(x, fx)
central_used <- FALSE
n_max_steps <- 0L
n_iter <- 0L
code <- stop_code(x, fx, g, x, 0L, -1L, FALSE)
a <- diag(scale_x, n)
x_new <- x
f_new <- fx
g_new <- g
if (code == 0L) repeat {
n_iter <- n_iter + 1L
repeat {
step <- solve_factor(a, -g)
search <- line_search(x, fx, g, step)
if (search$search_code == 1L && !central_used) {
central_used <- TRUE
g <- central(x)
next
}
break
}
x_new <- search$x_new
f_new <- search$f_new
g_new <- if (central_used) central(x_new) else forward(x_new, f_new)
code <- stop_code(x_new, f_new, g_new, x, n_iter, search$search_code, search$near_maximum_step)
if (code != 0L) break
a <- secant(a, x, g, x_new, g_new, n_iter, central_used)
fx <- f_new
x <- x_new
g <- g_new
}
if (code == 3L) {
x_new <- x
f_new <- fx
g_new <- g
}
list(minimum = f_new, estimate = x_new, gradient = g_new, code = code, iterations = n_iter,
evaluations = evaluations)
}
The iteration starts with the factor diag(scale_x) and forward-difference gradients. Each iteration solves $LL^\top p=-g$ and searches along $p$; after the first failed search the routine changes to central differences for the rest of the fit and retries the step. With code 3 the previous point is returned. EM receives the same parameters on the probability and rate scales through hmm_em_start() with random initialization turned off. The comparison reports observed-data log likelihoods and estimates in probability and rate units.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ml <- factored_secant_minimize(nll, start_par)
ml_model <- hmm_direct_model(ml$estimate, 2L)
em_same_start <- hmm_em(matrix(series$observed), 2L, "poisson",
start = hmm_em_start(start),
shuffle_start = FALSE)
em_same_model <- hmm_em_model(em_same_start)
print(data.frame(method = c("direct", "EM"),
loglik = c(-ml$minimum, em_same_start$loglik),
iterations = c(ml$iterations, em_same_start$iterations),
likelihood_evaluations = c(ml$evaluations, em_same_start$iterations + 2L),
stop = c(paste("code", ml$code), em_same_start$reason),
initial1 = c(ml_model$delta[1], em_same_model$initial[1]),
initial2 = c(ml_model$delta[2], em_same_model$initial[2]),
stay1 = c(ml_model$Gamma[1, 1], em_same_model$transition[1, 1]),
stay2 = c(ml_model$Gamma[2, 2], em_same_model$transition[2, 2]),
rate1 = c(ml_model$lambda[1], em_same_model$parameter[1]),
rate2 = c(ml_model$lambda[2], em_same_model$parameter[2])))
1
2
3
4
5
6
7
8
9
method loglik iterations likelihood_evaluations
1 direct -502.3687 41 255
2 EM -502.3687 13 15
stop initial1 initial2 stay1 stay2
1 code 1 0.9999994 5.958568e-07 0.9686611 0.9166716
2 relative change below tolerance 0.9999970 2.977048e-06 0.9686610 0.9166743
rate1 rate2
1 1.846254 7.965492
2 1.846255 7.965498
The direct optimizer used 255 negative log likelihood evaluations over 41 iterations. EM returned index 13 after 14 updates. Its 15 evaluations count the initial forward-backward pass and one pass after each update. Both methods give $-502.3687$ to four decimal places. For the direct fit the stay probabilities are 0.96866 and 0.91667, and the rates are 1.846254 and 7.965492.
The two evaluation counts measure different work: an EM iteration includes response-parameter fitting as well as a forward-backward pass, while the optimizer also evaluates the likelihood to form numerical derivatives. Their counts alone do not compare elapsed time.
Two returned quantities explain the direct optimizer’s stopping code of 1: the fitted initial log ratio and the gradient.
1
2
print(c(initial_log_ratio = ml$estimate[3],
max_abs_gradient_component = max(abs(ml$gradient))))
1
2
initial_log_ratio max_abs_gradient_component
-1.433326e+01 1.915119e-04
The third coordinate, $-14.33326$, gives $\pi_2=e^{\zeta_2}/(1+e^{\zeta_2})\approx5.96\times10^{-7}$ for the higher-rate state. EM stopped on the relative change in its log likelihood with $\pi_2$ about $2.98\times10^{-6}$.
For the direct optimizer, the largest absolute component of the returned numerical gradient is $1.915119\times10^{-4}$ on the unscaled negative log likelihood. With default parameter and function scales of one, the stopping test takes the maximum of $\vert g_j\vert \max(1,\vert u_j\vert )/\max(1,\vert \mathrm{nll}(u)\vert )$ over coordinates, where $g_j$ is the numerical derivative. It is about $9.14\times10^{-7}$ here, satisfying the $10^{-6}$ tolerance before the limit of 100 iterations. Code 1 records satisfaction of the scaled-gradient stopping test. A small derivative in a logit coordinate can reflect the small change in probability produced by that coordinate.
Nearly absorbing states and indistinguishable response distributions
How much can the counts reveal about a transition if the states have the same response distribution? Suppose $b_1(y)=b_2(y)=b(y)$ for every count. Each path then has the same product of conditional response probabilities, so paths differ only in their probabilities under the initial and transition distributions. Hence
\[p(y_{1:T})=\left[\prod_{t=1}^{T} b(y_t)\right] \sum_{s_{1:T}}\pi_{s_1}\prod_{t=2}^{T}a_{s_{t-1},s_t} =\prod_{t=1}^{T} b(y_t).\]The sum is one because it ranges over all possible paths. Every transition matrix and every initial distribution give this likelihood; the response distribution identifies neither of them in this example. The same argument applies to a repeated survey if both states assign the same probability to every possible response pattern at each interview. When the state-dependent response distributions are merely similar, changing a transition row can still have little effect on the observable counts.
An absorbing state has a diagonal transition probability of one and cannot be left after entry. A state is nearly absorbing when this probability is close to one, so it tends to persist after entry. In the direct fit the high-rate state has probability 0.91667 of persisting once entered. The much smaller number in its initial distribution is the probability that the series begins there.
As the initial probability approaches zero, $d\pi_2/d\zeta_2=\pi_2(1-\pi_2)$ is small, so a sizeable change in the initial log ratio can move very little probability. The slope of $\log(\pi_1 L_1+\pi_2 L_2)$ in that coordinate approaches zero as $\pi_2$ vanishes when $L_1>0$. A transition row can also approach a boundary in these coordinates, although every finite transition log ratio leaves the corresponding off-diagonal probability positive.
To compare fitted states, attach each rate to its initial probability and to the corresponding row and column of the transition matrix. A consistent permutation of those labels pairs each original path with a relabeled path having the same joint probability with the counts. Summing over the paths therefore preserves the probability of every observation sequence. Taking the ratio of probabilities for successive prefixes preserves the one-step predictive distribution wherever the conditioning history has positive probability. Here state 2 is the higher-rate state in both fits. Its estimated rates are 7.965492 and 7.965498, and its stay probabilities are 0.9166716 and 0.9166743. Even with this close agreement, both fits assign a small positive probability to starting there. To estimate the model in which the series must start in state 1, one would impose $\pi_2=0$ and fit the remaining parameters under that restriction. State labels remain arbitrary; ordering distinct fitted rates is a comparison convention and does not make the latent states an ordinal measurement scale.
The supplied direct likelihood is adapted from tpm() and forward() of LaMa, and factored_secant_minimize() is translated from the minimizer of nlm() in stats (code/NOTICE.md); the two packages provide the scaled forward likelihood and the numerical minimization.
13.6 Viterbi decoding and stationary distributions
If one state history had to be reported for a respondent, which history would have the greatest support from all the responses? For fixed model parameters and a count sequence $y_{1:T}$ of positive probability, the posterior probability of each path equals its joint probability with the counts divided by $p(y_{1:T})$. That denominator is the same for every path. The path can therefore be chosen by maximizing the joint probability, or equivalently its logarithm. Let $D_t(k)$ be the largest log joint probability of the first $t$ counts and any path ending in state $k$ at time $t$. At the first occasion, $D_1(k)=\log\pi_k+\log b_k(y_1)$. Suppose the preceding state was $i$. Every history reaching $i$ gains the same two terms when it moves to $k$ and produces $y_t$. It therefore suffices to extend a history attaining $D_{t-1}(i)$. Comparing the possible predecessors gives
\[D_t(k)=\log b_k(y_t)+\max_{1\le i\le K}\{D_{t-1}(i)+\log a_{ik}\}.\]The forward recursion adds the probabilities of all arrivals. The Viterbi recursion selects the largest for each destination. A zero probability contributes $-\infty$ on the log scale.
The final log joint probabilities identify the best ending state. Saving the maximizing predecessor at each step makes it possible to recover the earlier states. The function viterbi() implements this recursion and returns the selected path.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
viterbi <- function(y, model) {
emission <- hmm_emission(y, model)
n <- nrow(emission)
K <- ncol(emission)
stopifnot(n > 0)
score <- matrix(-Inf, n, K)
predecessor <- matrix(NA_integer_, n, K)
score[1, ] <- log(model$initial) + emission[1, ]
if (n > 1L) for (t in 2:n) for (k in seq_len(K)) {
value <- score[t - 1L, ] + log(model$transition[, k])
# which.max takes the smallest predecessor index on an exact tie.
j <- predecessor[t, k] <- which.max(value)
score[t, k] <- value[j] + emission[t, k]
}
if (all(score[n, ] == -Inf)) stop("No possible state path")
path <- integer(n)
path[n] <- which.max(score[n, ])
if (n > 1L) for (t in seq.int(n, 2L)) path[t - 1L] <- predecessor[t, path[t]]
list(path = path, log_joint = max(score[n, ]), predecessor = predecessor, score = score)
}
In viterbi(), emission[t, k] contains the log conditional response probability. For each entry it saves the maximizing predecessor’s index. The first row has no predecessors. Starting at the largest final entry and following its predecessors recovers the path. On an exact tie, which.max() chooses the smallest index, both within a predecessor comparison and at the final choice. The array named score stores the maximizing log joint probabilities $D_t(k)$. It is unrelated to the log likelihood derivative called the score vector in 13.5. A tie means that the returned path is one of several maximizers.
The returned log_joint is the log probability of the selected path jointly with the counts. Subtracting their log likelihood would give the log posterior probability of the selected path. If every final log joint probability is minus infinity, the function stops. This represents an impossible sequence when the inputs are exact; numerical failure in conditional probability or density evaluation must be distinguished from that case.
Viterbi and marginal decoding for three counts
Under tiny, the counts $y=(0,1,3)$ have Poisson means 1 and 4 conditional on state. For three counts, enumerating all eight paths checks the recursion. The function decode() compares the Viterbi path with the sequence obtained by selecting the most probable state separately at each occasion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
decode <- function(sequence, model) {
e <- enumerate_hmm(sequence, model)
p <- hmm_posterior(sequence, model)
most <- viterbi(sequence, model)
matched <- function(path) which(rowSums(sweep(e$paths, 2, path, "!=")) == 0)
marginal <- max.col(p$gamma, ties.method = "first")
print(most$predecessor)
print(data.frame(time = seq_along(sequence), response = sequence,
smoothed_state_1_probability = p$gamma[, 1],
marginal_mode = marginal, viterbi = most$path))
print(c(marginal_modes_posterior_probability = e$posterior[matched(marginal)],
viterbi_posterior_probability = e$posterior[matched(most$path)]))
stopifnot(abs(max(e$posterior) - e$posterior[matched(most$path)]) < 1e-12)
}
The rows of p$gamma give the smoothed state probabilities conditional on all three counts. In decode(), the largest entry in each row supplies the marginal choice, and matched() locates both that sequence and the Viterbi path in the enumeration. The two printed probabilities come from e$posterior. Each is the probability that all three states match the indicated path, given the counts.
1
decode(y, tiny)
1
2
3
4
5
6
7
8
9
10
[,1] [,2]
[1,] NA NA
[2,] 1 1
[3,] 1 1
time response smoothed_state_1_probability marginal_mode viterbi
1 1 0 0.9796182 1 1
2 2 1 0.9118804 1 1
3 3 3 0.5180080 1 1
marginal_modes_posterior_probability viterbi_posterior_probability
0.5013211 0.5013211
With counts $(0,1,3)$, even the last count leaves state 1 slightly more probable than state 2. Both rules select $(1,1,1)$, with posterior probability 0.50132. Changing only the counts separates the two rules.
1
decode(c(3, 2, 0), tiny)
1
2
3
4
5
6
7
8
9
10
[,1] [,2]
[1,] NA NA
[2,] 1 2
[3,] 1 2
time response smoothed_state_1_probability marginal_mode viterbi
1 1 3 0.4344884 2 1
2 2 2 0.7212197 1 1
3 3 0 0.9621183 1 1
marginal_modes_posterior_probability viterbi_posterior_probability
0.3158510 0.3965023
For $(3,2,0)$, the probabilities of state 1 are 0.43449, 0.72122 and 0.96212. The four paths starting in state 2 together have posterior probability $1-0.43449=0.56551$. The most probable individual path starts in state 1. To trace it in the printed matrix, start in column 1 of row 3. Its entry points to column 1 of row 2, whose entry gives state 1 at time 1. Figure 13.2 shows where the two decisions diverge.
Figure 13.2. Decoding the counts 3, 2 and 0. At left, black circles give the smoothed probability of state 1 at each occasion. The dotted line marks one half. At right, blue circles mark the marginal modes and orange triangles mark the Viterbi path.
Which decision suits a particular use? For reported states $d_1,\ldots,d_T$, the expected number correctly assigned given the counts is $\sum_t\gamma_t(d_t)$. Each term can be maximized separately. This gives $(2,1,1)$ here. It is the best path starting in state 2 and has posterior probability 0.31585 of matching the entire latent state sequence. Choosing $(1,1,1)$ raises that probability to 0.39650. In a model with forbidden transitions, two consecutive marginal choices can even require a move with probability zero. Selecting each marginal mode is often called local decoding; choosing the most probable complete path is global decoding. The first maximizes the conditional expected number of correct occasion-specific assignments, whereas the second maximizes the conditional probability of correctly identifying the whole path. Neither turns the selected states into observed facts.
Equilibrium proportions and posterior occupancy
Set the responses aside and ask what proportions of the population the transition rule would preserve. Write $\delta_k$ for the proposed proportion in state $k$. After one transition the share in state $k$ is $\sum_i\delta_i a_{ik}$, the sum of arrivals from every state, including those that stayed. A stationary distribution has these same proportions before and after the transition. With $\delta$ a column vector, the condition is $\delta^\top A=\delta^\top$. Introduce the $K\times K$ identity matrix $I$ and the column $\mathbf 1$ of $K$ ones. The required nonnegative entries satisfy
\[(A^\top-I)\delta=0,\qquad \mathbf 1^\top\delta=1.\]The first equations alone admit the zero vector and leave the scale undetermined. The last equation supplies the total probability. The function stationary_distribution() solves the combined equations when they determine a unique probability vector.
1
2
3
4
5
6
7
8
9
10
11
stationary_distribution <- function(A, tolerance = 1e-12) {
K <- ncol(A)
stopifnot(is.matrix(A), nrow(A) == K, K > 0, all(is.finite(A)),
all(A >= 0), max(abs(rowSums(A) - 1)) <= tolerance)
equations <- rbind(t(A) - diag(K), rep(1, K))
if (qr(equations, tol = tolerance)$rank < K)
return(list(unique = FALSE, probabilities = NULL))
p <- drop(qr.solve(equations, c(rep(0, K), 1), tol = tolerance))
stopifnot(min(p) >= -tolerance, max(abs(drop(p %*% A) - p)) <= tolerance)
list(unique = TRUE, probabilities = pmax(0, p) / sum(pmax(0, p)))
}
The function stacks the equations and checks whether the columns have full rank before solving. For a unique solution it checks the probability balance and allows for rounding near zero. This is a numerical rank test at the stated tolerance. A nearly reducible matrix can be classified as rank deficient even when its stationary distribution is mathematically unique.
In a finite irreducible chain, each state can reach every other state, and the stationary distribution is unique and positive in every state. If some power of $A$ has all entries positive, the chain is regular and its distribution converges to that stationary vector from every start. Even with a unique stationary vector, the state probabilities can oscillate. A chain that alternates between two states has stationary probabilities of one half each, yet a population starting entirely in state 1 returns there every second step.
Use bw_model from the random-start EM fit to HMM2 and the 250 counts in series$observed. The posterior occupancy proportion for each state is the expected fraction of these 250 occasions spent in that state, conditional on the observed counts and fitted parameters. For each state, colMeans() averages its column of smoothed probabilities, so an uncertain occasion contributes fractionally to both states. The output for bw_model lists the higher Poisson rate first. The last two calls distinguish states that can be left from absorbing states.
1
2
3
4
5
print(list(fitted_initial = bw_model$initial,
fitted_stationary = stationary_distribution(bw_model$transition),
posterior_occupancy = colMeans(hmm_posterior(series$observed, bw_model)$gamma),
two_absorbing = stationary_distribution(diag(2L)),
one_absorbing = stationary_distribution(matrix(c(1, 0, .4, .6), 2, byrow = TRUE))))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$fitted_initial
[1] 2.686553e-06 9.999973e-01
$fitted_stationary
$fitted_stationary$unique
[1] TRUE
$fitted_stationary$probabilities
[1] 0.2733096 0.7266904
$posterior_occupancy
[1] 0.2722141 0.7277859
$two_absorbing
$two_absorbing$unique
[1] FALSE
$two_absorbing$probabilities
NULL
$one_absorbing
$one_absorbing$unique
[1] TRUE
$one_absorbing$probabilities
[1] 1 0
To describe the fitted results with the lower-rate state first, reverse the output order. The fitted initial probabilities are 0.9999973 and about $2.7\times10^{-6}$. They describe the starting occasion. The stationary proportions are 0.72669 and 0.27331. Subtracting the fitted stay probabilities from one gives about 0.03134 going from low to high and 0.08333 going back. The stationary proportions balance the two flows, since $0.72669(0.03134)\approx0.27331(0.08333)$. The smoothed occupancy proportions are 0.72779 and 0.27221. A finite series begins at a particular time and its counts provide evidence about the states visited. Its expected occupancy can therefore differ from the equilibrium proportions even when the fitted transition matrix is regular.
With two absorbing states, every initial split persists because the transition matrix is the identity. The equations leave the split undetermined, so the function reports unique = FALSE. In the final example, a chain starting in state 2 remains there for $m$ transitions with probability $0.6^m$. This tends to zero, and once the chain reaches state 1 it stays. The only stationary distribution is $(1,0)$. More generally, a finite chain with exactly one closed communicating class has a unique stationary distribution. Once entered, this set cannot be left, and its members can all reach one another. Transient states receive zero stationary probability, and the states in that class share the probability according to their irreducible transition matrix.
Viterbi decoding and stationary probabilities are available in LaMa.
13.7 Numbers of states, different attained likelihoods, and checks with simulated and observed series
Does a third state describe a pattern that two states miss? Using the same observations, fit models with one, two and three states to each series. With one state there is a single state-dependent response distribution and no choice of state path. With two or three states, start EM ten times.
Each series contributes one initial-state factor. For $K$ states the initial probabilities have $K-1$ free entries. Each of the $K$ transition rows also has $K-1$. Add one mean per state for Poisson response distributions, or a mean and a standard deviation per state for normal response distributions.
For the finite fits returned here, let $\ell$ be the attained log likelihood, $p$ the nominal number of free parameters and $T$ the number of occasions. The Akaike information criterion (AIC) is $-2\ell+2p$, and the Bayesian information criterion (BIC) is $-2\ell+p\log T$. For each criterion, a smaller value is preferred: the improvement in fit is weighed against the parameter penalty. Here $T=250$ for HMM2 and $T=100$ for each annual series. These are comparisons within each response series.
Why does the BIC calculation use the length of the series? Dependence is included in the forward likelihood. These examples compare state counts within a single long series using the same parameter-count convention. The length-based penalty corresponds to information accumulating with the number of occasions under regular long-series conditions. It is a conventional comparison here; the freely estimated initial distribution enters only once, so its information does not grow like that of the transition and response parameters. For a panel with a fixed number of interviews per independent respondent, the independent sample size is instead the number of respondents.
Let $D$ count the occasions spent in state $k$ from entry until the first departure, including the entry occasion. For an integer $d\ge 1$, staying at least $d$ occasions requires $d-1$ consecutive self-transitions. For a constant stay probability $a_{kk}<1$ this gives
\[P(D\ge d\mid\text{entry into }k)=a_{kk}^{d-1},\qquad E(D\mid\text{entry into }k)=\sum_{d=1}^{\infty}a_{kk}^{d-1}=\frac{1}{1-a_{kk}}.\]An absorbing state has infinite duration. This geometric duration is conditional on entering the state and counts the entry occasion. It is a model expectation, not the average length of observed or decoded runs, which can be cut short by the observation window.
Fitting one to three states
The function fit_counts() fits the three candidate state counts and records their fitted models, information criteria, expected durations and decoded paths.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fit_counts <- function(y, family, seed) {
set.seed(seed)
lapply(1:3, function(K) {
fits <- lapply(seq_len(if (K == 1L) 1L else 10L),
function(r) hmm_em(matrix(y), K, family))
loglik <- vapply(fits, function(f) f$loglik, 0.0)
best <- fits[[which.max(loglik)]]
model <- hmm_em_model(best)
list(K = K, loglik = loglik, iterations = vapply(fits, function(f) f$iterations, 0L),
converged = vapply(fits, function(f) f$converged, TRUE), best = best, model = model,
IC = c(free_parameters = best$df, loglik = best$loglik,
AIC = best$AIC, BIC = best$BIC),
expected_dwell = 1 / (1 - diag(model$transition)), decoded = viterbi(y, model)$path)
})
}
The function fit_counts() selects the largest attained log likelihood using which.max() on the full vector of returns. It records convergence separately. The table of end points counts how many starts reached each log likelihood after rounding to three decimal places. The unrounded values determine which fit supplies the parameters and information criteria. The selection does not first exclude fits that failed the stopping test. A failed or non-finite run therefore needs an explicit disposition before its result can enter a model comparison.
Use the 250 counts in series$observed and the two annual series distributed with R. The discoveries series contains annual counts for 1860–1959 of inventions and scientific discoveries classified as “great” in the source compilation. The R dataset documentation identifies that compilation. The Nile series is the annual flow record introduced in Section 13.4; its description notes an apparent change near 1898. Each annual series has one observation per year, so its expected dwell times are in years. The calls set a separate seed for each series. The print loop gives three collections in the order of the calls. The displays below take up these collections in turn, beginning with HMM2. These are separate model comparisons: likelihoods and information criteria from different response series or measurement units are not ranked together.
1
2
3
4
5
6
7
8
9
10
series_counts <- fit_counts(series$observed, "poisson", 1371)
discoveries_fit <- fit_counts(as.numeric(datasets::discoveries), "poisson", 1372)
nile_fit <- fit_counts(as.numeric(datasets::Nile), "normal", 1373)
for (collection in list(HMM2 = series_counts, discoveries = discoveries_fit,
Nile = nile_fit)) {
print(lapply(collection, function(f) list(states = f$K,
end_points = table(round(f$loglik, 3)), iterations = f$iterations,
converged = sum(f$converged), IC = f$IC, expected_dwell = f$expected_dwell,
emission_parameters = f$model$parameter, transition = f$model$transition)))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
[[1]]
[[1]]$states
[1] 1
[[1]]$end_points
-693.645
1
[[1]]$iterations
[1] 1
[[1]]$converged
[1] 1
[[1]]$IC
free_parameters loglik AIC BIC
1.0000 -693.6451 1389.2902 1392.8117
[[1]]$expected_dwell
[1] Inf
[[1]]$emission_parameters
[1] 3.512
[[1]]$transition
[,1]
[1,] 1
[[2]]
[[2]]$states
[1] 2
[[2]]$end_points
-502.369
10
[[2]]$iterations
[1] 20 19 19 24 20 21 19 20 20 21
[[2]]$converged
[1] 10
[[2]]$IC
free_parameters loglik AIC BIC
5.0000 -502.3687 1014.7373 1032.3446
[[2]]$expected_dwell
[1] 31.90934 12.00116
[[2]]$emission_parameters
[1] 1.846256 7.965499
[[2]]$transition
[,1] [,2]
[1,] 0.96866121 0.03133879
[2,] 0.08332531 0.91667469
[[3]]
[[3]]$states
[1] 3
[[3]]$end_points
-496.695
10
[[3]]$iterations
[1] 116 132 98 98 129 102 150 109 123 131
[[3]]$converged
[1] 10
[[3]]$IC
free_parameters loglik AIC BIC
11.0000 -496.6953 1015.3905 1054.1266
[[3]]$expected_dwell
[1] 18.518478 1.000005 18.992049
[[3]]$emission_parameters
[1] 1.767120 6.271567 8.089454
[[3]]$transition
[,1] [,2] [,3]
[1,] 9.459999e-01 0.035709943 1.829018e-02
[2,] 9.999802e-01 0.000004864 1.495395e-05
[3,] 1.544539e-13 0.052653612 9.473464e-01
The three Poisson fits use 1, 5 and 11 nominal free parameters and attain log likelihoods of $-693.6451$, $-502.3687$ and $-496.6953$. All ten fits met the stopping rule at the same rounded likelihood for each larger state count. AIC is 1389.29, 1014.74 and 1015.39 in order of state count. BIC is 1392.81, 1032.34 and 1054.13. Both criteria favor two states among these fitted candidates. AIC separates the two- and three-state fits by only $1015.39-1014.74=0.65$. These parameter counts do not establish identification when states have identical response distributions or relevant probabilities are zero.
What did the additional state capture? In the two-state fit the expected durations are 31.91 occasions at the lower rate and 12.00 at the higher rate. In the three-state fit, the middle rate is 6.27 and its stay probability is only 0.000004864. Its expected duration of 1.000005 occasions means the fitted chain almost always leaves that state at the very next observation.
Observed annual series
For an observed series, state persistence can be estimated even when no generating path is known. The second collection from the same print loop describes discoveries.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
[[1]]
[[1]]$states
[1] 1
[[1]]$end_points
-216.846
1
[[1]]$iterations
[1] 1
[[1]]$converged
[1] 1
[[1]]$IC
free_parameters loglik AIC BIC
1.0000 -216.8457 435.6913 438.2965
[[1]]$expected_dwell
[1] Inf
[[1]]$emission_parameters
[1] 3.1
[[1]]$transition
[,1]
[1,] 1
[[2]]
[[2]]$states
[1] 2
[[2]]$end_points
-206.179
10
[[2]]$iterations
[1] 44 47 41 43 44 43 43 48 46 50
[[2]]$converged
[1] 10
[[2]]$IC
free_parameters loglik AIC BIC
5.0000 -206.1790 422.3580 435.3838
[[2]]$expected_dwell
[1] 16.993428 3.621173
[[2]]$emission_parameters
[1] 2.438918 5.684310
[[2]]$transition
[,1] [,2]
[1,] 0.9411537 0.05884628
[2,] 0.2761536 0.72384641
[[3]]
[[3]]$states
[1] 3
[[3]]$end_points
-202.827
10
[[3]]$iterations
[1] 129 128 159 146 104 167 104 114 115 146
[[3]]$converged
[1] 10
[[3]]$IC
free_parameters loglik AIC BIC
11.0000 -202.8274 427.6548 456.3117
[[3]]$expected_dwell
[1] 1.555977e+01 3.934779e+00 6.585696e+06
[[3]]$emission_parameters
[1] 2.991392 6.440119 1.765599
[[3]]$transition
[,1] [,2] [,3]
[1,] 9.357317e-01 4.841930e-02 1.584900e-02
[2,] 2.541439e-01 7.458561e-01 3.091319e-15
[3,] 1.518443e-07 2.631661e-23 9.999998e-01
The three Poisson log likelihoods are $-216.8457$, $-206.1790$ and $-202.8274$. With two states, the fitted means are 2.439 and 5.684 discoveries per year. An episode at the lower rate lasts 16.99 years on average under the model, compared with 3.62 years at the higher rate. The three-state fit assigns its third state a rate of 1.766 and a stay probability of 0.9999998.
For discoveries the AIC values are 435.69, 422.36 and 427.65, and BIC gives 438.30, 435.38 and 456.31. Both criteria favor two states among these fitted candidates.
The third collection describes Nile. Each row of its emission-parameter matrix gives a state’s mean and standard deviation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
[[1]]
[[1]]$states
[1] 1
[[1]]$end_points
-654.516
1
[[1]]$iterations
[1] 1
[[1]]$converged
[1] 1
[[1]]$IC
free_parameters loglik AIC BIC
2.0000 -654.5157 1313.0315 1318.2418
[[1]]$expected_dwell
[1] Inf
[[1]]$emission_parameters
[,1] [,2]
[1,] 919.35 168.3792
[[1]]$transition
[,1]
[1,] 1
[[2]]
[[2]]$states
[1] 2
[[2]]$end_points
-629.804
10
[[2]]$iterations
[1] 21 23 20 23 20 30 29 24 21 27
[[2]]$converged
[1] 10
[[2]]$IC
free_parameters loglik AIC BIC
7.0000 -629.8045 1273.6089 1291.8451
[[2]]$expected_dwell
[1] 2.78387e+01 3.62485e+08
[[2]]$emission_parameters
[,1] [,2]
[1,] 1097.1525 133.7480
[2,] 850.7565 124.4464
[[2]]$transition
[,1] [,2]
[1,] 9.640788e-01 0.03592121
[2,] 2.758734e-09 1.00000000
[[3]]
[[3]]$states
[1] 3
[[3]]$end_points
-627.848 -627.617
1 9
[[3]]$iterations
[1] 127 61 116 112 148 115 125 119 120 129
[[3]]$converged
[1] 10
[[3]]$IC
free_parameters loglik AIC BIC
14.0000 -627.6168 1283.2336 1319.7060
[[3]]$expected_dwell
[1] 2.206259 28.037662 4.608694
[[3]]$emission_parameters
[,1] [,2]
[1,] 792.8709 64.29071
[2,] 1097.3231 132.98439
[3,] 878.8834 136.18908
[[3]]$transition
[,1] [,2] [,3]
[1,] 0.54674399 4.768759e-106 4.532560e-01
[2,] 0.03566631 9.643337e-01 1.401004e-28
[3,] 0.21698122 4.779105e-124 7.830188e-01
Normal response distributions give log likelihoods of $-654.5157$, $-629.8045$ and $-627.6168$. In the two-state fit the high-flow state has mean 1097.2 and standard deviation 133.7 in the reported flow units. Its expected duration is 27.8 years. The low-flow state has mean 850.8 and standard deviation 124.4. Although its printed diagonal entry rounds to one, its probability of leaving is $2.758734\times10^{-9}$. Its reciprocal, $1/(2.758734\times10^{-9})\approx3.6\times10^8$ years, is the fitted expected duration. This extrapolates the fitted constant transition probability far beyond the 100 observed years, with no observed durations of that length. An exactly absorbing state would require a fit with the exit probability fixed at zero. Assessing the state in 1898 would require its smoothed probabilities or its position on a decoded path.
For Nile AIC gives 1313.03, 1273.61 and 1283.23, and BIC gives 1318.24, 1291.85 and 1319.71. Both criteria favor two states among the fitted candidates in all three series.
The three-state flow model also shows why the initial values matter. Nine starts ended at log likelihood $-627.617$ and one at $-627.848$ after rounding. The better end point includes a state with mean 792.9, standard deviation 64.29 and expected duration 2.21 years. This is the best end point found among these starts.
In an unrestricted model with several normal states, the likelihood has no finite upper bound. To see why, give positive path probability to a history that visits one state only at a chosen observation. Set that state’s mean equal to the observation and decrease its standard deviation toward zero. Its density there grows in proportion to the reciprocal standard deviation. Fix the other parameters at values that give positive densities for all remaining flows. The joint density of this one path and the flows then grows without bound, and the observed-data likelihood includes it in a sum of nonnegative terms.
For a survey, a state describes a response profile and its diagonal transition probability measures persistence over one interview interval. The respondent is the sampling unit. Using a common transition matrix across interviews requires comparable intervals and a time-homogeneous transition assumption. Given the state path, responses at different interviews are conditionally independent, and the six items are independent within each interview given its state. The annual examples use the same structure with counts or flow measurements. A persistent flow state still allows year-to-year variation through its standard deviation. These fitted distributions cannot establish historical causes or rule out residual serial dependence. Such judgments require further evidence about the observations and the model’s predictions.
Recovery and decoding across simulated series
Repeated starts assess sensitivity to initialization for one series. For the two-state Poisson model, how much would the estimates change if another 250 counts were observed? Generate 200 series from truth, the model with rates 2 and 8 and stay probabilities 0.95 and 0.90. Each random-number stream supplies one series and one random-start EM fit. The following calculation shows how the study obtained one record per stream. Only the counts enter the fit and the Viterbi calculation. These are 200 newly generated datasets, with one fit per dataset; they are not 200 starting values for the same data.
A fitted state can have a different index from the corresponding generating state. Align the fitted states by increasing Poisson rate before comparing their parameters or decoded states with the generating model.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(101307)
streams13 <- vector("list", 200)
streams13[[1L]] <- .Random.seed
for (i in 2:200) streams13[[i]] <- parallel::nextRNGStream(streams13[[i-1L]])
study13 <- lapply(seq_along(streams13), function(id) {
assign(".Random.seed", streams13[[id]], envir = .GlobalEnv)
simulation <- simulate_hmm(250L, truth)
fit <- hmm_em(matrix(simulation$observed), 2L, "poisson")
model <- hmm_em_model(fit)
order <- order(model$parameter)
path <- viterbi(simulation$observed, model)$path
list(id = id, observations = simulation$observed, state = simulation$state,
fit = list(model = model, loglik = fit$loglik, iterations = fit$iterations,
converged = fit$converged, reason = fit$reason),
aligned = c(rate1 = model$parameter[order[1]], rate2 = model$parameter[order[2]],
stay1 = model$transition[order[1], order[1]],
stay2 = model$transition[order[2], order[2]]),
decoded_accuracy = mean(match(path, order) == simulation$state))
})
In each record, order contains the fitted indices in order of increasing rate. Use those same indices for the diagonal transition probabilities. If fitted state 2 has the lower rate, match(path, order) turns a decoded 2 into a 1 before comparing it with the generating path. The fraction of the 250 positions that agree is that series’ decoding accuracy.
To summarize the supplied records from the book directory, run source("code/practice/13.7.R"). Its input contains the four aligned estimates, convergence flag, final iteration index and previously calculated accuracy for each series. Here truth changes meaning: the simulation used it as the generating model, while this summary script uses it as the vector of four generating values. The comparison uses the known simulated states and assumes that ordering the distinct rates gives the intended correspondence. It measures agreement at individual occasions in the same series used for estimation, not the probability of recovering an entire path or performance on a newly observed series.
The summary script expects data/derived/ch13/recovery-records.rds, an aggregate of the individual study records. The full chapter script code/ch13.R writes individual records and recovery.csv; code/examples/reader-study-exports.R combines the 200 individual records into the supplied aggregate.
For each parameter, the estimated bias is the mean of the usable estimates minus the generating value. To find the Monte Carlo standard error of the estimated bias, take the sample standard deviation across the usable estimates and divide by the square root of the number retained. This standard error measures uncertainty from a finite number of simulated datasets, not the sampling standard error of an estimate within one dataset. The first calculation is
1
2
3
4
5
6
7
8
9
10
# State-specific estimates are aligned by ordering the fitted Poisson rates.
study <- readRDS("data/derived/ch13/recovery-records.rds")
usable <- vapply(study, function(r) isTRUE(r$fit$converged), logical(1))
truth <- c(rate1 = 2, rate2 = 8, stay1 = .95, stay2 = .9)
estimates <- do.call(rbind, lapply(study[usable], function(r) r$aligned))
recovery <- data.frame(parameter = names(truth), assigned = length(study),
usable = sum(usable),
truth = truth, bias = colMeans(estimates) - truth,
MCSE = apply(estimates, 2L, sd) / sqrt(sum(usable)))
print(recovery, row.names = FALSE)
1
2
3
4
5
parameter assigned usable truth bias MCSE
rate1 200 200 2.00 0.009452564 0.015531649
rate2 200 200 8.00 0.020346591 0.029759267
stay1 200 200 0.95 -0.004423956 0.002582773
stay2 200 200 0.90 -0.008059554 0.003340399
All 200 fits met the recorded stopping rule. The Monte Carlo standard errors therefore use $\sqrt{200}$ as the divisor. The biases and Monte Carlo standard errors are 0.00945 and 0.01553 for the low rate, and 0.02035 and 0.02976 for the high rate. For the stay probabilities they are $-0.00442$ and 0.00258, and $-0.00806$ and 0.00334. The mean high-rate stay estimate thus lies about $0.00806/0.00334=2.4$ Monte Carlo standard errors below 0.90. If some fits were excluded, the denominator would be the square root of the number retained, and the resulting bias summary would describe that selected subset.
Accuracy and iteration counts include every assigned series. Here all 200 records are usable.
1
2
3
4
5
6
# Decoding compares the ordered state sequence with the simulated states.
accuracy <- vapply(study, function(r) r$decoded_accuracy, numeric(1))
iterations <- vapply(study, function(r) r$fit$iterations, integer(1))
counts <- table(cut(iterations, c(-1, 25, 50, 100, 500)))
print(summary(accuracy))
print(counts)
1
2
3
4
5
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.9320 0.9760 0.9840 0.9816 0.9880 1.0000
(-1,25] (25,50] (50,100] (100,500]
195 4 1 0
Accuracy averages 0.9816 across the 200 paths, with median 0.984 and range 0.932 to 1. The table counts final iteration indices. Of the 200 fits, 195 ended at an index of 25 or less, four between 26 and 50, one between 51 and 100 and none between 101 and 500. The actual number of parameter updates is one more than the reported final index.
For a respondent observed on many occasions, the number of possible state histories grows exponentially. The Markov assumption allows histories that reach the same present state to be combined, because they give the same distribution for the next response and state. Repeating that sum makes the finite-state likelihood exact without listing every history. EM estimation for finite-state hidden Markov models is available in depmixS4. The recursion evaluates the specified finite-state likelihood without approximating the sum over paths; floating-point rounding and underflow still require attention.

