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 HMM via Baum-Welch EM, decode most likely hidden state sequence via Viterbi, select optimal N hidden states via information criteria.

Use When

In

Required

| Input | Type | Desc |

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

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

| n_hidden_states | integer | N hidden states (or range for selection) |

| emission_type | string | "gaussian", "discrete", "poisson", "multinomial" |

Optional

| Input | Type | Default | Desc |

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

| initial_params | dict | random/heuristic | Init transition matrix, emission params, start probs |

| n_restarts | integer | 10 | Random restarts to mitigate local optima |

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

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

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

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

| regularization | float | 1e-6 | Diagonal constant preventing singularity |

Do

Step 1: Define Hidden States + Obs Model

1.1. Specify N hidden states K (or candidate range Step 5).

1.2. Emission distribution by data type:

1.3. Components:

1.4. Verify data: no missing, consistent dim, length T >> K^2.

→ HMM arch w/ K states, chosen emission family, clean data T >> K^2.

If err: missing → impute or remove. T too small → reduce K or get more data.

Step 2: Initialize Params

2.1. Gen initial each of n_restarts:

2.2. First restart: K-means-informed (strongest). Subsequent: random perturbations.

2.3. Verify valid:

→ n_restarts sets of valid params, ≥1 data-driven.

If err: K-means fails → purely random w/ more restarts. Singular covariance → add regularization to diagonal.

Step 3: Baum-Welch EM

3.1. E-step (Forward-Backward):

3.2. M-step (re-estimate):

3.3. Log-likelihood: log P(O | model) = log sum_k(alpha[T,k]). Log-sum-exp → prevent underflow.

3.4. Scaling: Scaled forward-backward → prevent underflow long sequences. Normalize alpha each step + accumulate log scaling factors.

3.5. Repeat E + M until log-likelihood change < convergence_tol or max_iterations.

3.6. Across restarts → keep params w/ highest final log-likelihood.

→ Monotonically non-decreasing log-likelihood, converge w/in max. Final valid (stochastic matrices, PD covariances).

If err: log-likelihood decreases → bug E/M, verify formulas. Very slow → better init or increase max. Singular covariance → increase regularization.

Step 4: Viterbi Decoding

4.1. Init:

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

4.3. Terminate:

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

4.5. Output decoded sequence z* = (z*_1, ..., z*_T) + log-prob.

4.6. Compare Viterbi path prob to total sequence prob from forward → dominance.

→ Single most-likely sequence length T, each in {1,...,K}. Viterbi log-prob ≤ total log-likelihood.

If err: Viterbi -inf log-prob → transition/emission prob zero where shouldn't. Add floor values preventing log(0).

Step 5: Model Selection (BIC/AIC)

5.1. Each candidate K in state_range → fit full HMM (Steps 2-4).

5.2. Free params p:

5.3. Information criteria:

5.4. Select lowest BIC (consistency) or AIC (prediction). Report both.

5.5. Tabulate each K: log-likelihood, # params, BIC, AIC, convergence.

5.6. Optimal K at boundary → extend range + re-fit.

→ Clear min BIC/AIC → optimal N hidden states. Selected converged + interpretable.

If err: no clear min (monotonically decreasing BIC) → misspecified, try diff emission family. All poor log-likelihood → data may not follow HMM structure.

Step 6: Validate Held-Out + Posterior

6.1. Split training/validation (80/20 or multiple sequences).

6.2. Fit training. Compute held-out log-likelihood via forward (no re-fit).

6.3. Posterior decoding (alt to Viterbi):

6.4. Compare Viterbi + posterior:

6.5. State interpretability:

6.6. Held-out log-likelihood per observation + compare across orders → confirm training selection.

→ Held-out reasonably close to training (no severe overfit). Viterbi + posterior agree 90%+. States distinct + interpretable.

If err: held-out much worse than training → overfit, reduce K or increase regularization. States not interpretable → diff init or emission family.

Check

Traps

→

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.