Fit hidden markov model

From pjt222/agent-almanac · View interactive version

Fit hidden markov model is an AI agent skill from the GitHub repository pjt222/agent-almanac. Fit hidden Markov models using the Baum-Welch (EM) algorithm with model selection, Viterbi decoding for state sequences, and forward-backward probabilities. Use when observations are generated by unobservable latent states, you need to segment a time series into latent regimes (market regimes, speec

How to use this skill

Skill file

Fit Hidden Markov Model

Fit a hidden Markov model (HMM) to sequential observation data using the Baum-Welch expectation-maximization algorithm, decode the most likely hidden state sequence via Viterbi, and select the optimal number of hidden states through information criteria.

When to Use

Inputs

Required

| Input | Type | Description |

|---|---|---|

| observations | sequence/matrix | Observed data sequence (univariate or multivariate) |

| n_hidden_states | integer | Number of hidden states to fit (or a range for model selection) |

| emission_type | string | Distribution family for emissions: "gaussian", "discrete", "poisson", "multinomial" |

Optional

| Input | Type | Default | Description |

|---|---|---|---|

| initial_params | dict | random/heuristic | Initial transition matrix, emission parameters, and start probabilities |

| n_restarts | integer | 10 | Number of random restarts to mitigate local optima |

| max_iterations | integer | 500 | Maximum EM iterations per restart |

| convergence_tol | float | 1e-6 | Log-likelihood convergence threshold for EM |

| state_range | list of ints | [n_hidden_states] | Range of state counts for model selection |

| covariance_type | string | "full" | For Gaussian emissions: "full", "diagonal", "spherical" |

| regularization | float | 1e-6 | Small constant added to diagonal of covariance matrices to prevent singularity |

Procedure

Step 1: Define Hidden States and Observation Model

1.1. Specify the number of hidden states K (or a candidate range for model selection in Step 5).

1.2. Choose the emission distribution family based on the data type:

1.3. Define the model components:

1.4. Verify observation data is properly formatted: no missing values in the sequence, consistent dimensionality, and sufficient length relative to the number of parameters.

Got: A clearly specified HMM architecture with K states, a chosen emission family, and clean observation data of length T >> K^2.

If fail: If data contains missing values, impute or remove affected segments. If T is too small relative to K, reduce K or acquire more data.

Step 2: Initialize Parameters

2.1. Generate initial parameters for each of the n_restarts restarts:

2.2. For the first restart, use the K-means-informed initialization (generally the strongest start). For subsequent restarts, use random perturbations.

2.3. Verify all initial parameters are valid:

Got: n_restarts sets of valid initial parameters, with at least one data-driven initialization.

If fail: If K-means fails to converge, use purely random initialization with more restarts. If covariance matrices are singular, add the regularization constant to the diagonal.

Step 3: Run Baum-Welch EM for Parameter Estimation

3.1. E-step (Forward-Backward algorithm):

3.2. M-step (Parameter re-estimation):

3.3. Compute log-likelihood: log P(O | model) = log sum_k(alpha[T,k]). Use the log-sum-exp trick to prevent underflow.

3.4. Scaling: Use scaled forward-backward variables to prevent numerical underflow for long sequences. Normalize alpha at each time step and accumulate log scaling factors.

3.5. Repeat E-step and M-step until log-likelihood change is below convergence_tol or max_iterations is reached.

3.6. Across all restarts, keep the parameter set with the highest final log-likelihood.

Got: Monotonically non-decreasing log-likelihood across iterations, converging within max_iterations. Final parameters are valid (stochastic matrices, positive-definite covariances).

If fail: If log-likelihood decreases, there is a bug in the E-step or M-step -- verify formulas. If convergence is very slow, try better initialization or increase max_iterations. If covariance becomes singular, increase regularization.

Step 4: Apply Viterbi Decoding for Most Likely State Sequence

4.1. Initialize Viterbi variables:

4.2. Recurse forward for t = 2,...,T:

4.3. Terminate:

4.4. Backtrace for t = T-1,...,1:

4.5. Output the decoded state sequence z* = (z*_1, ..., z*_T) and its log-probability.

4.6. Compare the Viterbi path probability to the total sequence probability from the forward algorithm to assess how dominant the best path is.

Got: A single most-likely state sequence of length T with each entry in {1,...,K}. The Viterbi log-probability should be less than or equal to the total log-likelihood.

If fail: If the Viterbi path has log-probability of negative infinity, some transition or emission probability is zero where it should not be. Add floor values to prevent log(0).

Step 5: Perform Model Selection (BIC/AIC Across Model Orders)

5.1. For each candidate number of hidden states K in state_range, fit the full HMM (Steps 2-4).

5.2. Compute the number of free parameters p:

5.3. Compute information criteria:

5.4. Select the model with the lowest BIC (preferred for consistency) or AIC (preferred for prediction). Report both.

5.5. Tabulate results: for each K, show log-likelihood, number of parameters, BIC, AIC, and convergence status.

5.6. If the optimal K is at the boundary of state_range, extend the range and re-fit.

Got: A clear minimum in BIC/AIC identifying the optimal number of hidden states. The selected model should have converged and have interpretable state meanings.

If fail: If no clear minimum exists (monotonically decreasing BIC), the model may be misspecified -- consider a different emission family. If all models have poor log-likelihood, the data may not follow an HMM structure.

Step 6: Validate with Held-Out Data and Posterior Decoding

6.1. Split data into training and validation sets (e.g., 80/20 or use multiple sequences if available).

6.2. Fit the model on training data. Compute log-likelihood on held-out data using the forward algorithm (do not re-fit parameters).

6.3. Posterior decoding (alternative to Viterbi):

6.4. Compare Viterbi and posterior decoding:

6.5. Assess state interpretability:

6.6. Compute held-out log-likelihood per observation and compare across model orders to confirm the training-set model selection.

Got: Held-out log-likelihood is reasonably close to training log-likelihood (no severe overfitting). Viterbi and posterior decoding agree on 90%+ of time steps. States have distinct, interpretable emission distributions.

If fail: If held-out likelihood is much worse than training, the model is overfitting -- reduce K or increase regularization. If states are not interpretable, try different initializations or a different emission family.

Validation

Pitfalls

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.