Skip to content
bio-compPublic

About

Hidden Markov Model in Python

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

HMMPY - Hidden Markov Models in Python

Python Version License: MIT Build Status Code Coverage

A Python implementation of Hidden Markov Models based on the Rabiner (1989) tutorial.

Installation

pip

pip install hmmpy

uv

uv pip install hmmpy

Or install in development mode:

# pip
pip install -e ".[all]"

# uv
uv pip install -e ".[all]"

Quick Start

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)

Features

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

Visualization

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)

Documentation

  • Online Documentation - Interactive notebooks hosted on GitHub Pages
  • Jupyter notebooks in notebooks/ - Examples and explanations

Development

# 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/

Migration Contract

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

License

MIT License - see LICENSE file for details.

About

Hidden Markov Model in Python

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages