HMMPY - Hidden Markov Models in Python
A Python implementation of Hidden Markov Models based on the Rabiner (1989) tutorial.
pip install hmmpyuv pip install hmmpyOr install in development mode:
# pip
pip install -e ".[all]"
# uv
uv pip install -e ".[all]"from hmm import HMM, baum_welch, forward, viterbi
from hmm.algorithms import ComputeMode
# Create an HMM with 2 states
A = [[0.95, 0.05], [0.05, 0.95]] # Transition matrix
B = [[1/6]*6, [1/10]*5 + [1/2]] # Emission matrix
V = [1, 2, 3, 4, 5, 6] # Observation symbols
hmm = HMM(n_states=2, A=A, B=B, V=V)
# Run forward algorithm
log_prob, alpha, c = forward(hmm, [1, 2, 1, 6, 6], mode=ComputeMode.SCALED)
# Decode most likely state sequence
states, delta, psi = viterbi(hmm, [1, 2, 1, 6, 6], mode=ComputeMode.LOG)
# Train on observation sequences
trained_hmm = baum_welch(hmm, [[1, 2, 3], [6, 5, 4]], epochs=20)| Algorithm | Description |
|---|---|
| Forward | Calculate P(Obs |
| Backward | Calculate backward probabilities for posterior decoding |
| Viterbi | Find most likely state sequence |
| Baum-Welch | Train HMM parameters using EM |
| HMMClassifier | Binary classification using two HMMs |
from hmm.viz import (
plot_transition_matrix,
plot_emission_matrix,
plot_state_probabilities,
plot_viterbi_path,
plot_state_diagram,
plot_gaussian_ellipses,
)
# Plot HMM matrices
fig = plot_transition_matrix(hmm)
# Plot state diagram (requires networkx)
fig = plot_state_diagram(hmm)
# Plot Gaussian ellipses for continuous HMMs
fig = plot_gaussian_ellipses(means, covariances)- Online Documentation - Interactive notebooks hosted on GitHub Pages
- Jupyter notebooks in
notebooks/- Examples and explanations
# Run tests
pytest
# Run tests with coverage
pytest --cov=hmm --cov-report=html
# Run linting
ruff check .
# Run linting with auto-fix
ruff check --fix .
# Run type checking
mypy src/hmm/This project was migrated from Python 2 to Python 3. All examples from the Rabiner (1989) tutorial are implemented as Jupyter notebooks that:
- Demonstrate usage of the HMMPY library
- Explain how HMMs work conceptually
- Write out example output to verify correctness
MIT License - see LICENSE file for details.