| 1 |
.. _tutorial: |
| 2 |
|
| 3 |
Tutorial |
| 4 |
======== |
| 5 |
|
| 6 |
.. currentmodule:: hmmlearn |
| 7 |
|
| 8 |
``hmmlearn`` implements the Hidden Markov Models (HMMs). |
| 9 |
The HMM is a generative probabilistic model, in which a sequence of observable |
| 10 |
:math:`\mathbf{X}` variables is generated by a sequence of internal hidden |
| 11 |
states :math:`\mathbf{Z}`. The hidden states are not observed directly. |
| 12 |
The transitions between hidden states are assumed to have the form of a |
| 13 |
(first-order) Markov chain. They can be specified by the start probability |
| 14 |
vector :math:`\boldsymbol{\pi}` and a transition probability matrix |
| 15 |
:math:`\mathbf{A}`. The emission probability of an observable can be any |
| 16 |
distribution with parameters :math:`\boldsymbol{\theta}` conditioned on the |
| 17 |
current hidden state. The HMM is completely determined by |
| 18 |
:math:`\boldsymbol{\pi}`, :math:`\mathbf{A}` and :math:`\boldsymbol{\theta}`. |
| 19 |
|
| 20 |
There are three fundamental problems for HMMs: |
| 21 |
|
| 22 |
* Given the model parameters and observed data, estimate the optimal |
| 23 |
sequence of hidden states. |
| 24 |
* Given the model parameters and observed data, calculate the model likelihood. |
| 25 |
* Given just the observed data, estimate the model parameters. |
| 26 |
|
| 27 |
The first and the second problem can be solved by the dynamic programming |
| 28 |
algorithms known as |
| 29 |
the Viterbi algorithm and the Forward-Backward algorithm, respectively. |
| 30 |
The last one can be solved by an iterative Expectation-Maximization (EM) |
| 31 |
algorithm, known as the Baum-Welch algorithm. |
| 32 |
|
| 33 |
.. topic:: References: |
| 34 |
|
| 35 |
- Lawrence R. Rabiner "A tutorial on hidden Markov models and selected |
| 36 |
applications in speech recognition", Proceedings of the IEEE 77.2, |
| 37 |
pp. 257-286, 1989. |
| 38 |
- Jeff A. Bilmes, "A gentle tutorial of the EM algorithm and its application |
| 39 |
to parameter estimation for Gaussian mixture and hidden Markov models.", |
| 40 |
1998. |
| 41 |
- Mark Stamp. "A revealing introduction to hidden Markov models". Tech. rep. |
| 42 |
Department of Computer Science, San Jose State University, 2018. |
| 43 |
url: http://www.cs.sjsu.edu/~stamp/RUA/HMM.pdf. |
| 44 |
|
| 45 |
|
| 46 |
Available models |
| 47 |
---------------- |
| 48 |
|
| 49 |
.. autosummary:: |
| 50 |
:nosignatures: |
| 51 |
|
| 52 |
hmm.CategoricalHMM |
| 53 |
hmm.GaussianHMM |
| 54 |
hmm.GMMHMM |
| 55 |
hmm.MultinomialHMM |
| 56 |
hmm.PoissonHMM |
| 57 |
vhmm.VariationalCategoricalHMM |
| 58 |
vhmm.VariationalGaussianHMM |
| 59 |
|
| 60 |
:ref:`Read on <customizing>` for details on how to implement a HMM with a |
| 61 |
custom emission probability. |
| 62 |
|
| 63 |
Building HMM and generating samples |
| 64 |
----------------------------------- |
| 65 |
|
| 66 |
You can build a HMM instance by passing the parameters described above to the |
| 67 |
constructor. Then, you can generate samples from the HMM by calling |
| 68 |
:meth:`~.BaseHMM.sample`. |
| 69 |
|
| 70 |
>>> import numpy as np |
| 71 |
>>> from hmmlearn import hmm |
| 72 |
>>> np.random.seed(42) |
| 73 |
>>> |
| 74 |
>>> model = hmm.GaussianHMM(n_components=3, covariance_type="full") |
| 75 |
>>> model.startprob_ = np.array([0.6, 0.3, 0.1]) |
| 76 |
>>> model.transmat_ = np.array([[0.7, 0.2, 0.1], |
| 77 |
... [0.3, 0.5, 0.2], |
| 78 |
... [0.3, 0.3, 0.4]]) |
| 79 |
>>> model.means_ = np.array([[0.0, 0.0], [3.0, -3.0], [5.0, 10.0]]) |
| 80 |
>>> model.covars_ = np.tile(np.identity(2), (3, 1, 1)) |
| 81 |
>>> X, Z = model.sample(100) |
| 82 |
|
| 83 |
The transition probability matrix need not to be ergodic. For instance, a |
| 84 |
left-right HMM can be defined as follows: |
| 85 |
|
| 86 |
>>> lr = hmm.GaussianHMM(n_components=3, covariance_type="diag", |
| 87 |
... init_params="cm", params="cmt") |
| 88 |
>>> lr.startprob_ = np.array([1.0, 0.0, 0.0]) |
| 89 |
>>> lr.transmat_ = np.array([[0.5, 0.5, 0.0], |
| 90 |
... [0.0, 0.5, 0.5], |
| 91 |
... [0.0, 0.0, 1.0]]) |
| 92 |
|
| 93 |
If any of the required parameters are missing, :meth:`~.BaseHMM.sample` |
| 94 |
will raise an exception: |
| 95 |
|
| 96 |
>>> model = hmm.GaussianHMM(n_components=3) |
| 97 |
>>> X, Z = model.sample(100) |
| 98 |
Traceback (most recent call last): |
| 99 |
... |
| 100 |
sklearn.exceptions.NotFittedError: This GaussianHMM instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator. |
| 101 |
|
| 102 |
Fixing parameters |
| 103 |
----------------- |
| 104 |
|
| 105 |
Each HMM parameter has a character code which can be used to customize its |
| 106 |
initialization and estimation. The EM algorithm needs a starting point to |
| 107 |
proceed, thus prior to training each parameter is assigned a value |
| 108 |
either random or computed from the data. It is possible to hook into this |
| 109 |
process and provide a starting point explicitly. To do so |
| 110 |
|
| 111 |
1. ensure that the character code for the parameter is missing from |
| 112 |
:attr:`~.BaseHMM.init_params` and then |
| 113 |
2. set the parameter to the desired value. |
| 114 |
|
| 115 |
For example, consider a HMM with an explicitly initialized transition |
| 116 |
probability matrix: |
| 117 |
|
| 118 |
>>> model = hmm.GaussianHMM(n_components=3, n_iter=100, init_params="mcs") |
| 119 |
>>> model.transmat_ = np.array([[0.7, 0.2, 0.1], |
| 120 |
... [0.3, 0.5, 0.2], |
| 121 |
... [0.3, 0.3, 0.4]]) |
| 122 |
|
| 123 |
A similar trick applies to parameter estimation. If you want to fix some |
| 124 |
parameter at a specific value, remove the corresponding character from |
| 125 |
:attr:`~.BaseHMM.params` and set the parameter value before training. |
| 126 |
|
| 127 |
.. topic:: Examples: |
| 128 |
|
| 129 |
* :doc:`/auto_examples/plot_hmm_sampling_and_decoding` |
| 130 |
|
| 131 |
Training HMM parameters and inferring the hidden states |
| 132 |
------------------------------------------------------- |
| 133 |
|
| 134 |
You can train an HMM by calling the :meth:`~.BaseHMM.fit` method. The input |
| 135 |
is a matrix of concatenated sequences of observations (*aka* samples) along with |
| 136 |
the lengths of the sequences (see :ref:`Working with multiple sequences <multiple_sequences>`). |
| 137 |
|
| 138 |
Note, since the EM algorithm is a gradient-based optimization method, it will |
| 139 |
generally get stuck in local optima. You should in general try to run ``fit`` |
| 140 |
with various initializations and select the highest scored model. |
| 141 |
|
| 142 |
The score of the model can be calculated by the :meth:`~.BaseHMM.score` method. |
| 143 |
|
| 144 |
The inferred optimal hidden states can be obtained by calling |
| 145 |
:meth:`~.BaseHMM.predict` method. The ``predict`` method can be |
| 146 |
specified with a decoder algorithm. Currently the Viterbi algorithm |
| 147 |
(``"viterbi"``), and maximum a posteriori estimation (``"map"``) are supported. |
| 148 |
|
| 149 |
This time, the input is a single sequence of observed values. Note, the states |
| 150 |
in ``remodel`` will have a different order than those in the generating model. |
| 151 |
|
| 152 |
>>> remodel = hmm.GaussianHMM(n_components=3, covariance_type="full", n_iter=100) |
| 153 |
>>> remodel.fit(X) |
| 154 |
GaussianHMM(... |
| 155 |
>>> Z2 = remodel.predict(X) |
| 156 |
|
| 157 |
.. topic:: Examples: |
| 158 |
|
| 159 |
* :doc:`/auto_examples/plot_casino` |
| 160 |
|
| 161 |
Monitoring convergence |
| 162 |
---------------------- |
| 163 |
|
| 164 |
The number of EM algorithm iterations is upper bounded by the ``n_iter`` |
| 165 |
parameter. The training proceeds until ``n_iter`` steps were performed or the |
| 166 |
change in score is lower than the specified threshold ``tol``. Note, that |
| 167 |
depending on the data, the EM algorithm may or may not achieve convergence in the |
| 168 |
given number of steps. |
| 169 |
|
| 170 |
You can use the :attr:`~.BaseHMM.monitor_` attribute to diagnose convergence: |
| 171 |
|
| 172 |
>>> remodel.monitor_ |
| 173 |
ConvergenceMonitor( |
| 174 |
history=[...], |
| 175 |
iter=..., |
| 176 |
n_iter=100, |
| 177 |
tol=0.01, |
| 178 |
verbose=False, |
| 179 |
) |
| 180 |
>>> remodel.monitor_.converged |
| 181 |
True |
| 182 |
|
| 183 |
.. _multiple_sequences: |
| 184 |
|
| 185 |
Working with multiple sequences |
| 186 |
------------------------------- |
| 187 |
|
| 188 |
All of the examples so far were using a single sequence of observations. |
| 189 |
The input format in the case of multiple sequences is a bit involved and |
| 190 |
is best understood by example. |
| 191 |
|
| 192 |
Consider two 1D sequences: |
| 193 |
|
| 194 |
>>> X1 = [[0.5], [1.0], [-1.0], [0.42], [0.24]] |
| 195 |
>>> X2 = [[2.4], [4.2], [0.5], [-0.24]] |
| 196 |
|
| 197 |
To pass both sequences to :meth:`~.BaseHMM.fit` or |
| 198 |
:meth:`~.BaseHMM.predict`, first concatenate them into a single array and |
| 199 |
then compute an array of sequence lengths: |
| 200 |
|
| 201 |
>>> X = np.concatenate([X1, X2]) |
| 202 |
>>> lengths = [len(X1), len(X2)] |
| 203 |
|
| 204 |
Finally, just call the desired method with ``X`` and ``lengths``: |
| 205 |
|
| 206 |
>>> hmm.GaussianHMM(n_components=3).fit(X, lengths) |
| 207 |
GaussianHMM(... |
| 208 |
|
| 209 |
Saving and loading HMM |
| 210 |
---------------------- |
| 211 |
|
| 212 |
After training, a HMM can be easily persisted for future use with the standard |
| 213 |
:mod:`pickle` module: |
| 214 |
|
| 215 |
>>> import pickle |
| 216 |
>>> with open("filename.pkl", "wb") as file: pickle.dump(remodel, file) |
| 217 |
>>> with open("filename.pkl", "rb") as file: pickle.load(file) |
| 218 |
GaussianHMM(... |
| 219 |
|
| 220 |
.. _customizing: |
| 221 |
|
| 222 |
Implementing HMMs with custom emission probabilities |
| 223 |
---------------------------------------------------- |
| 224 |
|
| 225 |
If you want to implement a custom emission probability (e.g. Cauchy), you have to |
| 226 |
subclass :class:`~.BaseHMM` and override the following methods |
| 227 |
|
| 228 |
.. currentmodule:: hmmlearn.base |
| 229 |
|
| 230 |
.. autosummary:: |
| 231 |
|
| 232 |
BaseHMM._init |
| 233 |
BaseHMM._check |
| 234 |
BaseHMM._generate_sample_from_state |
| 235 |
BaseHMM._compute_log_likelihood |
| 236 |
BaseHMM._compute_likelihood |
| 237 |
BaseHMM._initialize_sufficient_statistics |
| 238 |
BaseHMM._accumulate_sufficient_statistics |
| 239 |
BaseHMM._do_mstep |
| 240 |
|
| 241 |
Optionally, only one of `~.BaseHMM._compute_likelihood` and |
| 242 |
`~.BaseHMM._compute_log_likelihood` need to be overridden, and the |
| 243 |
base implementation will provide the other. |