协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
fit-hidden-markov-model【开发与工程】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, speech phonemes, biological sequences), compute sequence …
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Fit hidden Markov model (HMM) to sequential watch data using Baum-Welch expectation-maximization algorithm, decode most likely hidden state sequence via Viterbi, and pick right number of hidden states through info criteria.
| 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" |
| 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 |
1.1. Set count of hidden states K (or candidate range for model pick in Step 5).
1.2. Pick emission distribution family by data type:
1.3. Set model bits:
A of size K x K: A[i,j] = P(z_t = j | z_{t-1} = i)theta_k for each state k: distribution-specific (e.g., mean and covariance for Gaussian)pi: pi[k] = P(z_1 = k)1.4. Check watch data is formatted right: no missing values in sequence, consistent dim, and enough length vs count of params.
Got: Clearly set HMM shape with K states, picked emission family, and clean watch data of length T >> K^2.
If fail: Data has missing values? Fill in or remove affected segments. T too small vs K? Drop K or get more data.
2.1. Make initial params for each of n_restarts restarts:
2.2. For first restart, use K-means-informed init (usually strongest start). For later restarts, use random perturbations.
2.3. Check all initial params are valid:
Got: n_restarts sets of valid initial params, with at least one data-driven init.
If fail: K-means fails to converge? Use pure random init with more restarts. Covariance matrices singular? Add regularization constant to diagonal.
3.1. E-step (Forward-Backward algorithm):
alpha[t,k] = P(o_1,...,o_t, z_t=k | model) using recursion:
alpha[1,k] = pi[k] * b_k(o_1)alpha[t,k] = sum_j(alpha[t-1,j] * A[j,k]) * b_k(o_t)beta[t,k] = P(o_{t+1},...,o_T | z_t=k, model):
beta[T,k] = 1beta[t,k] = sum_j(A[k,j] * b_j(o_{t+1}) * beta[t+1,j])gamma[t,k] = P(z_t=k | O, model):
gamma[t,k] = alpha[t,k] * beta[t,k] / P(O | model)xi[t,i,j] = P(z_t=i, z_{t+1}=j | O, model).3.2. M-step (Param re-estimation):
A[i,j] = sum_t(xi[t,i,j]) / sum_t(gamma[t,i])mu_k = sum_t(gamma[t,k] * o_t) / sum_t(gamma[t,k])b_k(v) = sum_t(gamma[t,k] * I(o_t=v)) / sum_t(gamma[t,k])pi[k] = gamma[1,k]3.3. Compute log-likelihood: log P(O | model) = log sum_k(alpha[T,k]). Use log-sum-exp trick to block underflow.
3.4. Scaling: Use scaled forward-backward vars to block 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 hit.
3.6. Across all restarts, keep param set with highest final log-likelihood.
Got: Monotonically non-decreasing log-likelihood across iterations, converging within max_iterations. Final params are valid (stochastic matrices, positive-definite covariances).
If fail: Log-likelihood drops? There is bug in E-step or M-step -- check formulas. Convergence very slow? Try better init or bump max_iterations. Covariance becomes singular? Increase regularization.
4.1. Init Viterbi vars:
delta[1,k] = log(pi[k]) + log(b_k(o_1))psi[1,k] = 0 (no predecessor)4.2. Recurse forward for t = 2,...,T:
delta[t,k] = max_j(delta[t-1,j] + log(A[j,k])) + log(b_k(o_t))psi[t,k] = argmax_j(delta[t-1,j] + log(A[j,k]))4.3. End:
z*_T = argmax_k(delta[T,k])max_k(delta[T,k])4.4. Backtrace for t = T-1,...,1:
z*_t = psi[t+1, z*_{t+1}]4.5. Output decoded state sequence z* = (z*_1, ..., z*_T) and its log-prob.
4.6. Compare Viterbi path prob to total sequence prob from forward algorithm to check how dominant the best path is.
Got: Single most-likely state sequence of length T with each entry in {1,...,K}. Viterbi log-prob should be less than or equal to total log-likelihood.
If fail: Viterbi path has log-prob of negative infinity? Some transition or emission prob is zero where it should not be. Add floor values to block log(0).
5.1. For each candidate count of hidden states K in state_range, fit full HMM (Steps 2-4).
5.2. Compute count of free params p:
K * (K - 1) (each row is simplex)d dimensions: K * (d + d*(d+1)/2))K - 15.3. Compute info criteria:
BIC = -2 * log_likelihood + p * log(T)AIC = -2 * log_likelihood + 2 * pAICc = AIC + 2*p*(p+1) / (T - p - 1) (small-sample correction)5.4. Pick model with lowest BIC (preferred for consistency) or AIC (preferred for prediction). Report both.
5.5. Tabulate results: for each K, show log-likelihood, count of params, BIC, AIC, convergence status.
5.6. If best K is at edge of state_range, extend range and re-fit.
Got: Clear min in BIC/AIC spotting best count of hidden states. Picked model should have converged and have interpretable state meanings.
If fail: No clear min exists (monotonically decreasing BIC)? Model may be misspec -- think different emission family. All models have poor log-likelihood? Data may not follow HMM structure.
6.1. Split data into training and check sets (e.g., 80/20 or use many sequences if open).
6.2. Fit model on training data. Compute log-likelihood on held-out data using forward algorithm (do not re-fit params).
6.3. Posterior decoding (swap for Viterbi):
z^_t = argmax_k(gamma[t,k])6.4. Compare Viterbi and posterior decoding:
6.5. Check state interpretability:
A) are reasonable.6.6. Compute held-out log-likelihood per observation and compare across model orders to confirm training-set model pick.
Got: Held-out log-likelihood is reasonably close to training log-likelihood (no big overfit). Viterbi and posterior decoding agree on 90%+ of time steps. States have distinct, interpretable emission distributions.
If fail: Held-out likelihood much worse than training? Model is overfit -- drop K or bump regularization. States not interpretable? Try different inits or different emission family.
P(O) = sum_k(alpha[T,k]) = sum_k(pi[k] * b_k(o_1) * beta[1,k])O(K + d^2) params. Use BIC (not just likelihood) for model pick and check on held-out data.