Registry / ai-ml / hmmlearn

hmmlearn

JSON →
library0.3.3pypypi✓ verified 21d ago

hmmlearn is a Python library for unsupervised learning of Hidden Markov Models (HMMs) with an API designed to be compatible with scikit-learn. It includes implementations for Gaussian HMMs, Multinomial HMMs, and GMM-HMMs. The current version is 0.3.3, and it receives updates for bug fixes and compatibility, though major feature releases are infrequent.

pip install hmmlearn
INSTALL
IMPORT
SIG · HMMLEARN
H
hmmlearn
ai-mlpythonv0.3.3
Install
9.8s avg
Import
3552ms
Disk
281MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.3.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
build_error
glibc
py 3.103.95 runs
installs and imports cleanly · install 9.8s · import 3.552s · 271MB
281MB installed
● package 281MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

GaussianHMM
from hmmlearn import hmm model = hmm.GaussianHMM(...)
MultinomialHMM
from hmmlearn import hmm model = hmm.MultinomialHMM(...)
GMMHMM
from hmmlearn import hmm model = hmm.GMMHMM(...)

This quickstart demonstrates how to create, train, and use a Gaussian Hidden Markov Model (HMM). It covers generating sample data, fitting the HMM, predicting hidden states, scoring the model, and sampling new sequences from the learned model.

import numpy as np from hmmlearn import hmm # 1. Generate some sample data # Let's create data that has two underlying 'states' with different means # The HMM will try to discover these. np.random.seed(42) X = np.concatenate([np.random.randn(100, 1) + 0, np.random.randn(100, 1) + 5]) # Mix the data to simulate a sequence, important for HMMs np.random.shuffle(X) # 2. Create and train a Gaussian HMM model # n_components: number of hidden states we want to find # covariance_type: "full", "tied", "diag", "spherical" # n_iter: number of EM iterations to perform model = hmm.GaussianHMM(n_components=2, covariance_type="full", n_iter=100, random_state=42) # The 'fit' method estimates parameters from data using the EM algorithm. # If initial parameters are not set, 'hmmlearn' will use k-means to initialize. model.fit(X) # 3. Predict the hidden states for the observed data hidden_states = model.predict(X) print("Learned Means:\n", model.means_) print("Learned Transition Matrix:\n", model.transmat_) print("First 10 hidden states:\n", hidden_states[:10]) # 4. Score the model (log-likelihood of the data given the model) score = model.score(X) print("\nModel score (log-likelihood):", score) # 5. Generate new samples from the learned model X_new, Z_new = model.sample(n_samples=50) print("\nShape of new samples:", X_new.shape) print("First 5 new samples:\n", X_new[:5].T) print("First 5 new hidden states:\n", Z_new[:5])
Debug
Known issues
breakingThe `MultinomialHMM` class from version 0.2.0 onwards requires integer-valued observations (e.g., `[0, 1, 2, 1]`). Prior to 0.2.0, it could implicitly handle float-like inputs by converting them. Passing non-integer data to `MultinomialHMM` in current versions will raise an error.
fix
Ensure all observations passed to `MultinomialHMM` are integers. If your data is continuous, consider binning it or using `GaussianHMM` or `GMMHMM`.
affects: <0.2.0 -> >=0.2.0
gotchaThe expected input data shape for `MultinomialHMM` can be confusing. For a single sequence of observations, it expects a 1D array of integers `(n_samples,)` if `n_features` is effectively 1, or `(n_samples, n_features)` where each `n_features` element is an integer, rather than a 2D array of floats `(n_samples, n_features)` as is common for `GaussianHMM`.
fix
For `MultinomialHMM`, ensure `X` is an array of integers. For `n_features=1`, `X` should be `(n_samples,)` or `(n_samples, 1)`. If `X` contains multiple categorical features, it should be `(n_samples, n_features)` where each feature column is integers.
affects: >=0.2.0
gotchaHMM fitting with the Expectation-Maximization (EM) algorithm can converge to local optima rather than the global optimum. This can lead to suboptimal model parameters and poor performance.
fix
Run the `fit` method multiple times with different `random_state` values, select the model with the highest `score` (log-likelihood), or increase `n_iter` for more iterations. Consider using initial parameter estimates if domain knowledge is available.
affects: All
gotchaThe `init_params` and `params` arguments in the model's constructor control which parameters are initialized automatically and which are estimated during `fit`. Misunderstanding their usage can lead to errors or parameters not being estimated as expected.
fix
Review the documentation for `init_params` (default: 'ste' for 's'tartprob, 't'ransmat, 'e'missionprob, 'm'eans, 'c'ovars) and `params` (default: 'ste' or 'stmc' depending on the model) for the specific HMM type you are using. Explicitly set these if you wish to fix certain parameters or provide custom initialization.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'hmmlearn'
The hmmlearn library is not installed in the Python environment being used, or the environment where it's installed is not the one active when running the code.
fix
Ensure hmmlearn is installed in your active Python environment. If using pip, run: `pip install hmmlearn`. If using conda, run: `conda install -c conda-forge hmmlearn`.
AttributeError: module 'setuptools_scm' has no attribute 'get_version'
This error typically occurs due to an incompatibility or corruption in the `setuptools_scm` package, which hmmlearn uses for versioning, especially in certain Python 3.8+ environments on Windows.
fix
Uninstall and then reinstall both `hmmlearn` and `setuptools_scm`. A common fix involves: `pip uninstall hmmlearn setuptools_scm` followed by `pip install hmmlearn setuptools_scm` or `conda install -c conda-forge hmmlearn setuptools_scm` if using Anaconda/Miniconda. Restarting the kernel or IDE after reinstallation is often necessary.
ImportError: No module named hmmlearn.hmm
This error occurs when trying to import HMM classes from `hmmlearn.hmm`, which was the structure in older versions or when users mistakenly try to import `sklearn.hmm` (which was deprecated) assuming it moved to `hmmlearn.hmm`. The direct HMM classes are now available under `hmmlearn` itself or specific submodules like `hmmlearn.base`.
fix
Import HMM models directly from `hmmlearn`. For example, instead of `from hmmlearn.hmm import GaussianHMM`, use `from hmmlearn.hmm import GaussianHMM` (for modern hmmlearn versions, `hmm` is a submodule within `hmmlearn`) or `from hmmlearn import hmm` and then `hmm.GaussianHMM`.
ValueError: startprob_ must sum to 1.0
This error indicates that the initial probabilities for the hidden states (startprob_) do not sum to 1, which is a requirement for a valid probability distribution. This can happen due to incorrect manual assignment or issues during initialization/fitting with NaN values in the data.
fix
Ensure that the `startprob_` array (and other probability distributions like `transmat_` and `emissionprob_` for MultinomialHMM, or `weights_` for GMMHMM) is correctly initialized so that its elements sum to 1. When fitting, ensure your input data `X` does not contain NaN values, which can lead to `startprob_` becoming NaN. If manually setting, ensure `model.startprob_ = np.array([0.6, 0.4])` (example for 2 states).
sklearn.exceptions.NotFittedError: This GaussianHMM instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
This error occurs when you attempt to use methods like `predict`, `score`, or `sample` on an HMM model instance before it has been trained using the `fit` method.
fix
Call the `fit(X, lengths)` method on your HMM model with appropriate training data `X` and (optionally) `lengths` of individual sequences, before attempting to use any methods that require a trained model.
Upgrade
Version history
0.3.3latest on PyPI · released Oct 31, 2024
Audit
Dependencies
numpyrequiredCore numerical operations.
scipyrequiredScientific computing operations.
scikit-learnrequiredProvides k-means for initialization and other utilities, and API compatibility.
Agent activity
9 hits · last 30 days
node
8
Resources
hmmlearn — pip install hmmlearn · libregistry