Debian Codegraph @

src/hmmlearn/hmm.py

raw symbols SCIP
1 """
2 The :mod:`hmmlearn.hmm` module implements hidden Markov models.
3 """
4
5 import logging
6
7 import numpy as np
8 from scipy import linalg
9 from sklearn import cluster
10 from sklearn.utils import check_random_state
11
12 from . import _emissions, _utils
13 from .base import BaseHMM
14 from .utils import fill_covars, normalize
15
16
17 __all__ = [
18 "GMMHMM", "GaussianHMM", "CategoricalHMM", "MultinomialHMM", "PoissonHMM",
19 ]
20
21
22 _log = logging.getLogger(__name__)
23 COVARIANCE_TYPES = frozenset(("spherical", "diag", "full", "tied"))
24
25
26 class CategoricalHMM(_emissions.BaseCategoricalHMM, BaseHMM):
27 """
28 Hidden Markov Model with categorical (discrete) emissions.
29
30 Attributes
31 ----------
32 n_features : int
33 Number of possible symbols emitted by the model (in the samples).
34
35 monitor_ : ConvergenceMonitor
36 Monitor object used to check the convergence of EM.
37
38 startprob_ : array, shape (n_components, )
39 Initial state occupation distribution.
40
41 transmat_ : array, shape (n_components, n_components)
42 Matrix of transition probabilities between states.
43
44 emissionprob_ : array, shape (n_components, n_features)
45 Probability of emitting a given symbol when in each state.
46
47 Examples
48 --------
49 >>> from hmmlearn.hmm import CategoricalHMM
50 >>> CategoricalHMM(n_components=2) #doctest: +ELLIPSIS
51 CategoricalHMM(algorithm='viterbi',...
52 """
53
54 def __init__(self, n_components=1, startprob_prior=1.0,
55 transmat_prior=1.0, *, emissionprob_prior=1.0,
56 n_features=None, algorithm="viterbi",
57 random_state=None, n_iter=10, tol=1e-2,
58 verbose=False, params="ste", init_params="ste",
59 implementation="log"):
60 """
61 Parameters
62 ----------
63 n_components : int
64 Number of states.
65
66 startprob_prior : array, shape (n_components, ), optional
67 Parameters of the Dirichlet prior distribution for
68 :attr:`startprob_`.
69
70 transmat_prior : array, shape (n_components, n_components), optional
71 Parameters of the Dirichlet prior distribution for each row
72 of the transition probabilities :attr:`transmat_`.
73
74 emissionprob_prior : array, shape (n_components, n_features), optional
75 Parameters of the Dirichlet prior distribution for
76 :attr:`emissionprob_`.
77
78 n_features: int, optional
79 The number of categorical symbols in the HMM. Will be inferred
80 from the data if not set.
81
82 algorithm : {"viterbi", "map"}, optional
83 Decoder algorithm.
84
85 - "viterbi": finds the most likely sequence of states, given all
86 emissions.
87 - "map" (also known as smoothing or forward-backward): finds the
88 sequence of the individual most-likely states, given all
89 emissions.
90
91 random_state: RandomState or an int seed, optional
92 A random number generator instance.
93
94 n_iter : int, optional
95 Maximum number of iterations to perform.
96
97 tol : float, optional
98 Convergence threshold. EM will stop if the gain in log-likelihood
99 is below this value.
100
101 verbose : bool, optional
102 Whether per-iteration convergence reports are printed to
103 :data:`sys.stderr`. Convergence can also be diagnosed using the
104 :attr:`monitor_` attribute.
105
106 params, init_params : string, optional
107 The parameters that get updated during (``params``) or initialized
108 before (``init_params``) the training. Can contain any
109 combination of 's' for startprob, 't' for transmat, and 'e' for
110 emissionprob. Defaults to all parameters.
111
112 implementation : string, optional
113 Determines if the forward-backward algorithm is implemented with
114 logarithms ("log"), or using scaling ("scaling"). The default is
115 to use logarithms for backwards compatability.
116 """
117 BaseHMM.__init__(self, n_components,
118 startprob_prior=startprob_prior,
119 transmat_prior=transmat_prior,
120 algorithm=algorithm,
121 random_state=random_state,
122 n_iter=n_iter, tol=tol, verbose=verbose,
123 params=params, init_params=init_params,
124 implementation=implementation)
125 self.emissionprob_prior = emissionprob_prior
126 self.n_features = n_features
127
128 def _init(self, X, lengths=None):
129 super()._init(X, lengths)
130
131 self.random_state = check_random_state(self.random_state)
132
133 if self._needs_init('e', 'emissionprob_'):
134 self.emissionprob_ = self.random_state.rand(
135 self.n_components, self.n_features)
136 normalize(self.emissionprob_, axis=1)
137
138 def _check(self):
139 super()._check()
140
141 self.emissionprob_ = np.atleast_2d(self.emissionprob_)
142 if self.n_features is None:
143 self.n_features = self.emissionprob_.shape[1]
144 if self.emissionprob_.shape != (self.n_components, self.n_features):
145 raise ValueError(
146 f"emissionprob_ must have shape"
147 f"({self.n_components}, {self.n_features})")
148 self._check_sum_1("emissionprob_")
149
150 def _do_mstep(self, stats):
151 super()._do_mstep(stats)
152 if 'e' in self.params:
153 self.emissionprob_ = np.maximum(
154 self.emissionprob_prior - 1 + stats['obs'], 0)
155 normalize(self.emissionprob_, axis=1)
156
157
158 class GaussianHMM(_emissions.BaseGaussianHMM, BaseHMM):
159 """
160 Hidden Markov Model with Gaussian emissions.
161
162 Attributes
163 ----------
164 n_features : int
165 Dimensionality of the Gaussian emissions.
166
167 monitor_ : ConvergenceMonitor
168 Monitor object used to check the convergence of EM.
169
170 startprob_ : array, shape (n_components, )
171 Initial state occupation distribution.
172
173 transmat_ : array, shape (n_components, n_components)
174 Matrix of transition probabilities between states.
175
176 means_ : array, shape (n_components, n_features)
177 Mean parameters for each state.
178
179 covars_ : array
180 Covariance parameters for each state.
181
182 The shape depends on :attr:`covariance_type`:
183
184 * (n_components, ) if "spherical",
185 * (n_components, n_features) if "diag",
186 * (n_components, n_features, n_features) if "full",
187 * (n_features, n_features) if "tied".
188
189 Examples
190 --------
191 >>> from hmmlearn.hmm import GaussianHMM
192 >>> GaussianHMM(n_components=2) #doctest: +ELLIPSIS
193 GaussianHMM(algorithm='viterbi',...
194 """
195
196 def __init__(self, n_components=1, covariance_type='diag',
197 min_covar=1e-3,
198 startprob_prior=1.0, transmat_prior=1.0,
199 means_prior=0, means_weight=0,
200 covars_prior=1e-2, covars_weight=1,
201 algorithm="viterbi", random_state=None,
202 n_iter=10, tol=1e-2, verbose=False,
203 params="stmc", init_params="stmc",
204 implementation="log"):
205 """
206 Parameters
207 ----------
208 n_components : int
209 Number of states.
210
211 covariance_type : {"spherical", "diag", "full", "tied"}, optional
212 The type of covariance parameters to use:
213
214 * "spherical" --- each state uses a single variance value that
215 applies to all features (default).
216 * "diag" --- each state uses a diagonal covariance matrix.
217 * "full" --- each state uses a full (i.e. unrestricted)
218 covariance matrix.
219 * "tied" --- all states use **the same** full covariance matrix.
220
221 min_covar : float, optional
222 Floor on the diagonal of the covariance matrix to prevent
223 overfitting. Defaults to 1e-3.
224
225 startprob_prior : array, shape (n_components, ), optional
226 Parameters of the Dirichlet prior distribution for
227 :attr:`startprob_`.
228
229 transmat_prior : array, shape (n_components, n_components), optional
230 Parameters of the Dirichlet prior distribution for each row
231 of the transition probabilities :attr:`transmat_`.
232
233 means_prior, means_weight : array, shape (n_components, ), optional
234 Mean and precision of the Normal prior distribtion for
235 :attr:`means_`.
236
237 covars_prior, covars_weight : array, shape (n_components, ), optional
238 Parameters of the prior distribution for the covariance matrix
239 :attr:`covars_`.
240
241 If :attr:`covariance_type` is "spherical" or "diag" the prior is
242 the inverse gamma distribution, otherwise --- the inverse Wishart
243 distribution.
244
245 algorithm : {"viterbi", "map"}, optional
246 Decoder algorithm.
247
248 - "viterbi": finds the most likely sequence of states, given all
249 emissions.
250 - "map" (also known as smoothing or forward-backward): finds the
251 sequence of the individual most-likely states, given all
252 emissions.
253
254 random_state: RandomState or an int seed, optional
255 A random number generator instance.
256
257 n_iter : int, optional
258 Maximum number of iterations to perform.
259
260 tol : float, optional
261 Convergence threshold. EM will stop if the gain in log-likelihood
262 is below this value.
263
264 verbose : bool, optional
265 Whether per-iteration convergence reports are printed to
266 :data:`sys.stderr`. Convergence can also be diagnosed using the
267 :attr:`monitor_` attribute.
268
269 params, init_params : string, optional
270 The parameters that get updated during (``params``) or initialized
271 before (``init_params``) the training. Can contain any combination
272 of 's' for startprob, 't' for transmat, 'm' for means, and 'c' for
273 covars. Defaults to all parameters.
274
275 implementation : string, optional
276 Determines if the forward-backward algorithm is implemented with
277 logarithms ("log"), or using scaling ("scaling"). The default is
278 to use logarithms for backwards compatability.
279 """
280 super().__init__(n_components,
281 startprob_prior=startprob_prior,
282 transmat_prior=transmat_prior, algorithm=algorithm,
283 random_state=random_state, n_iter=n_iter,
284 tol=tol, params=params, verbose=verbose,
285 init_params=init_params,
286 implementation=implementation)
287 self.covariance_type = covariance_type
288 self.min_covar = min_covar
289 self.means_prior = means_prior
290 self.means_weight = means_weight
291 self.covars_prior = covars_prior
292 self.covars_weight = covars_weight
293
294 @property
295 def covars_(self):
296 """Return covars as a full matrix."""
297 return fill_covars(self._covars_, self.covariance_type,
298 self.n_components, self.n_features)
299
300 @covars_.setter
301 def covars_(self, covars):
302 covars = np.array(covars, copy=True)
303 _utils._validate_covars(covars, self.covariance_type,
304 self.n_components)
305 self._covars_ = covars
306
307 def _init(self, X, lengths=None):
308 super()._init(X, lengths)
309
310 if self._needs_init("m", "means_"):
311 kmeans = cluster.KMeans(n_clusters=self.n_components,
312 random_state=self.random_state,
313 n_init=10) # sklearn <1.4 backcompat.
314 kmeans.fit(X)
315 self.means_ = kmeans.cluster_centers_
316 if self._needs_init("c", "covars_"):
317 cv = np.cov(X.T) + self.min_covar * np.eye(X.shape[1])
318 if not cv.shape:
319 cv.shape = (1, 1)
320 self.covars_ = \
321 _utils.distribute_covar_matrix_to_match_covariance_type(
322 cv, self.covariance_type, self.n_components).copy()
323
324 def _check(self):
325 super()._check()
326
327 self.means_ = np.asarray(self.means_)
328 self.n_features = self.means_.shape[1]
329
330 if self.covariance_type not in COVARIANCE_TYPES:
331 raise ValueError(
332 f"covariance_type must be one of {COVARIANCE_TYPES}")
333
334 def _needs_sufficient_statistics_for_mean(self):
335 return 'm' in self.params
336
337 def _needs_sufficient_statistics_for_covars(self):
338 return 'c' in self.params
339
340 def _do_mstep(self, stats):
341 super()._do_mstep(stats)
342
343 means_prior = self.means_prior
344 means_weight = self.means_weight
345
346 # TODO: find a proper reference for estimates for different
347 # covariance models.
348 # Based on Huang, Acero, Hon, "Spoken Language Processing",
349 # p. 443 - 445
350 denom = stats['post'][:, None]
351 if 'm' in self.params:
352 self.means_ = ((means_weight * means_prior + stats['obs'])
353 / (means_weight + denom))
354
355 if 'c' in self.params:
356 covars_prior = self.covars_prior
357 covars_weight = self.covars_weight
358 meandiff = self.means_ - means_prior
359
360 if self.covariance_type in ('spherical', 'diag'):
361 c_n = (means_weight * meandiff**2
362 + stats['obs**2']
363 - 2 * self.means_ * stats['obs']
364 + self.means_**2 * denom)
365 c_d = max(covars_weight - 1, 0) + denom
366 self._covars_ = (covars_prior + c_n) / np.maximum(c_d, 1e-5)
367 if self.covariance_type == 'spherical':
368 self._covars_ = np.tile(self._covars_.mean(1)[:, None],
369 (1, self._covars_.shape[1]))
370 elif self.covariance_type in ('tied', 'full'):
371 c_n = np.empty((self.n_components, self.n_features,
372 self.n_features))
373 for c in range(self.n_components):
374 obsmean = np.outer(stats['obs'][c], self.means_[c])
375 c_n[c] = (means_weight * np.outer(meandiff[c],
376 meandiff[c])
377 + stats['obs*obs.T'][c]
378 - obsmean - obsmean.T
379 + np.outer(self.means_[c], self.means_[c])
380 * stats['post'][c])
381 cvweight = max(covars_weight - self.n_features, 0)
382 if self.covariance_type == 'tied':
383 self._covars_ = ((covars_prior + c_n.sum(axis=0)) /
384 (cvweight + stats['post'].sum()))
385 elif self.covariance_type == 'full':
386 self._covars_ = ((covars_prior + c_n) /
387 (cvweight + stats['post'][:, None, None]))
388
389
390 class GMMHMM(_emissions.BaseGMMHMM):
391 """
392 Hidden Markov Model with Gaussian mixture emissions.
393
394 Attributes
395 ----------
396 monitor_ : ConvergenceMonitor
397 Monitor object used to check the convergence of EM.
398
399 startprob_ : array, shape (n_components, )
400 Initial state occupation distribution.
401
402 transmat_ : array, shape (n_components, n_components)
403 Matrix of transition probabilities between states.
404
405 weights_ : array, shape (n_components, n_mix)
406 Mixture weights for each state.
407
408 means_ : array, shape (n_components, n_mix, n_features)
409 Mean parameters for each mixture component in each state.
410
411 covars_ : array
412 Covariance parameters for each mixture components in each state.
413
414 The shape depends on :attr:`covariance_type`:
415
416 * (n_components, n_mix) if "spherical",
417 * (n_components, n_mix, n_features) if "diag",
418 * (n_components, n_mix, n_features, n_features) if "full"
419 * (n_components, n_features, n_features) if "tied".
420 """
421
422 def __init__(self, n_components=1, n_mix=1,
423 min_covar=1e-3, startprob_prior=1.0, transmat_prior=1.0,
424 weights_prior=1.0, means_prior=0.0, means_weight=0.0,
425 covars_prior=None, covars_weight=None,
426 algorithm="viterbi", covariance_type="diag",
427 random_state=None, n_iter=10, tol=1e-2,
428 verbose=False, params="stmcw",
429 init_params="stmcw",
430 implementation="log"):
431 """
432 Parameters
433 ----------
434 n_components : int
435 Number of states in the model.
436
437 n_mix : int
438 Number of states in the GMM.
439
440 covariance_type : {"sperical", "diag", "full", "tied"}, optional
441 The type of covariance parameters to use:
442
443 * "spherical" --- each state uses a single variance value that
444 applies to all features.
445 * "diag" --- each state uses a diagonal covariance matrix
446 (default).
447 * "full" --- each state uses a full (i.e. unrestricted)
448 covariance matrix.
449 * "tied" --- all mixture components of each state use **the same**
450 full covariance matrix (note that this is not the same as for
451 `GaussianHMM`).
452
453 min_covar : float, optional
454 Floor on the diagonal of the covariance matrix to prevent
455 overfitting. Defaults to 1e-3.
456
457 startprob_prior : array, shape (n_components, ), optional
458 Parameters of the Dirichlet prior distribution for
459 :attr:`startprob_`.
460
461 transmat_prior : array, shape (n_components, n_components), optional
462 Parameters of the Dirichlet prior distribution for each row
463 of the transition probabilities :attr:`transmat_`.
464
465 weights_prior : array, shape (n_mix, ), optional
466 Parameters of the Dirichlet prior distribution for
467 :attr:`weights_`.
468
469 means_prior, means_weight : array, shape (n_mix, ), optional
470 Mean and precision of the Normal prior distribtion for
471 :attr:`means_`.
472
473 covars_prior, covars_weight : array, shape (n_mix, ), optional
474 Parameters of the prior distribution for the covariance matrix
475 :attr:`covars_`.
476
477 If :attr:`covariance_type` is "spherical" or "diag" the prior is
478 the inverse gamma distribution, otherwise --- the inverse Wishart
479 distribution.
480
481 algorithm : {"viterbi", "map"}, optional
482 Decoder algorithm.
483
484 - "viterbi": finds the most likely sequence of states, given all
485 emissions.
486 - "map" (also known as smoothing or forward-backward): finds the
487 sequence of the individual most-likely states, given all
488 emissions.
489
490 random_state: RandomState or an int seed, optional
491 A random number generator instance.
492
493 n_iter : int, optional
494 Maximum number of iterations to perform.
495
496 tol : float, optional
497 Convergence threshold. EM will stop if the gain in log-likelihood
498 is below this value.
499
500 verbose : bool, optional
501 Whether per-iteration convergence reports are printed to
502 :data:`sys.stderr`. Convergence can also be diagnosed using the
503 :attr:`monitor_` attribute.
504
505 params, init_params : string, optional
506 The parameters that get updated during (``params``) or initialized
507 before (``init_params``) the training. Can contain any combination
508 of 's' for startprob, 't' for transmat, 'm' for means, 'c'
509 for covars, and 'w' for GMM mixing weights. Defaults to all
510 parameters.
511
512 implementation : string, optional
513 Determines if the forward-backward algorithm is implemented with
514 logarithms ("log"), or using scaling ("scaling"). The default is
515 to use logarithms for backwards compatability.
516 """
517 BaseHMM.__init__(self, n_components,
518 startprob_prior=startprob_prior,
519 transmat_prior=transmat_prior,
520 algorithm=algorithm, random_state=random_state,
521 n_iter=n_iter, tol=tol, verbose=verbose,
522 params=params, init_params=init_params,
523 implementation=implementation)
524 self.covariance_type = covariance_type
525 self.min_covar = min_covar
526 self.n_mix = n_mix
527 self.weights_prior = weights_prior
528 self.means_prior = means_prior
529 self.means_weight = means_weight
530 self.covars_prior = covars_prior
531 self.covars_weight = covars_weight
532
533 def _init(self, X, lengths=None):
534 super()._init(X, lengths=None)
535 nc = self.n_components
536 nf = self.n_features
537 nm = self.n_mix
538
539 def compute_cv():
540 return np.cov(X.T) + self.min_covar * np.eye(nf)
541
542 # Default values for covariance prior parameters
543 self._init_covar_priors()
544 self._fix_priors_shape()
545
546 main_kmeans = cluster.KMeans(n_clusters=nc,
547 random_state=self.random_state,
548 n_init=10) # sklearn >=1.2 compat.
549 cv = None # covariance matrix
550 labels = main_kmeans.fit_predict(X)
551 main_centroid = np.mean(main_kmeans.cluster_centers_, axis=0)
552 means = []
553 for label in range(nc):
554 kmeans = cluster.KMeans(n_clusters=nm,
555 random_state=self.random_state,
556 n_init=10) # sklearn >=1.2 compat.
557 X_cluster = X[np.where(labels == label)]
558 if X_cluster.shape[0] >= nm:
559 kmeans.fit(X_cluster)
560 means.append(kmeans.cluster_centers_)
561 else:
562 if cv is None:
563 cv = compute_cv()
564 m_cluster = np.random.multivariate_normal(main_centroid,
565 cov=cv,
566 size=nm)
567 means.append(m_cluster)
568
569 if self._needs_init("w", "weights_"):
570 self.weights_ = np.full((nc, nm), 1 / nm)
571
572 if self._needs_init("m", "means_"):
573 self.means_ = np.stack(means)
574
575 if self._needs_init("c", "covars_"):
576 if cv is None:
577 cv = compute_cv()
578 if not cv.shape:
579 cv.shape = (1, 1)
580 if self.covariance_type == 'tied':
581 self.covars_ = np.zeros((nc, nf, nf))
582 self.covars_[:] = cv
583 elif self.covariance_type == 'full':
584 self.covars_ = np.zeros((nc, nm, nf, nf))
585 self.covars_[:] = cv
586 elif self.covariance_type == 'diag':
587 self.covars_ = np.zeros((nc, nm, nf))
588 self.covars_[:] = np.diag(cv)
589 elif self.covariance_type == 'spherical':
590 self.covars_ = np.zeros((nc, nm))
591 self.covars_[:] = cv.mean()
592
593 def _init_covar_priors(self):
594 if self.covariance_type == "full":
595 if self.covars_prior is None:
596 self.covars_prior = 0.0
597 if self.covars_weight is None:
598 self.covars_weight = -(1.0 + self.n_features + 1.0)
599 elif self.covariance_type == "tied":
600 if self.covars_prior is None:
601 self.covars_prior = 0.0
602 if self.covars_weight is None:
603 self.covars_weight = -(self.n_mix + self.n_features + 1.0)
604 elif self.covariance_type == "diag":
605 if self.covars_prior is None:
606 self.covars_prior = -1.5
607 if self.covars_weight is None:
608 self.covars_weight = 0.0
609 elif self.covariance_type == "spherical":
610 if self.covars_prior is None:
611 self.covars_prior = -(self.n_mix + 2.0) / 2.0
612 if self.covars_weight is None:
613 self.covars_weight = 0.0
614
615 def _fix_priors_shape(self):
616 nc = self.n_components
617 nf = self.n_features
618 nm = self.n_mix
619
620 # If priors are numbers, this function will make them into a
621 # matrix of proper shape
622 self.weights_prior = np.broadcast_to(
623 self.weights_prior, (nc, nm)).copy()
624 self.means_prior = np.broadcast_to(
625 self.means_prior, (nc, nm, nf)).copy()
626 self.means_weight = np.broadcast_to(
627 self.means_weight, (nc, nm)).copy()
628
629 if self.covariance_type == "full":
630 self.covars_prior = np.broadcast_to(
631 self.covars_prior, (nc, nm, nf, nf)).copy()
632 self.covars_weight = np.broadcast_to(
633 self.covars_weight, (nc, nm)).copy()
634 elif self.covariance_type == "tied":
635 self.covars_prior = np.broadcast_to(
636 self.covars_prior, (nc, nf, nf)).copy()
637 self.covars_weight = np.broadcast_to(
638 self.covars_weight, nc).copy()
639 elif self.covariance_type == "diag":
640 self.covars_prior = np.broadcast_to(
641 self.covars_prior, (nc, nm, nf)).copy()
642 self.covars_weight = np.broadcast_to(
643 self.covars_weight, (nc, nm, nf)).copy()
644 elif self.covariance_type == "spherical":
645 self.covars_prior = np.broadcast_to(
646 self.covars_prior, (nc, nm)).copy()
647 self.covars_weight = np.broadcast_to(
648 self.covars_weight, (nc, nm)).copy()
649
650 def _check(self):
651 super()._check()
652 if not hasattr(self, "n_features"):
653 self.n_features = self.means_.shape[2]
654 nc = self.n_components
655 nf = self.n_features
656 nm = self.n_mix
657
658 self._init_covar_priors()
659 self._fix_priors_shape()
660
661 # Checking covariance type
662 if self.covariance_type not in COVARIANCE_TYPES:
663 raise ValueError(
664 f"covariance_type must be one of {COVARIANCE_TYPES}")
665
666 self.weights_ = np.array(self.weights_)
667 # Checking mixture weights' shape
668 if self.weights_.shape != (nc, nm):
669 raise ValueError(
670 f"weights_ must have shape (n_components, n_mix), "
671 f"actual shape: {self.weights_.shape}")
672
673 # Checking mixture weights' mathematical correctness
674 self._check_sum_1("weights_")
675
676 # Checking means' shape
677 self.means_ = np.array(self.means_)
678 if self.means_.shape != (nc, nm, nf):
679 raise ValueError(
680 f"means_ must have shape (n_components, n_mix, n_features), "
681 f"actual shape: {self.means_.shape}")
682
683 # Checking covariances' shape
684 self.covars_ = np.array(self.covars_)
685 covars_shape = self.covars_.shape
686 needed_shapes = {
687 "spherical": (nc, nm),
688 "tied": (nc, nf, nf),
689 "diag": (nc, nm, nf),
690 "full": (nc, nm, nf, nf),
691 }
692 needed_shape = needed_shapes[self.covariance_type]
693 if covars_shape != needed_shape:
694 raise ValueError(
695 f"{self.covariance_type!r} mixture covars must have shape "
696 f"{needed_shape}, actual shape: {covars_shape}")
697
698 # Checking covariances' mathematical correctness
699 if (self.covariance_type == "spherical" or
700 self.covariance_type == "diag"):
701 if np.any(self.covars_ < 0):
702 raise ValueError(f"{self.covariance_type!r} mixture covars "
703 f"must be non-negative")
704 if np.any(self.covars_ == 0):
705 _log.warning("Degenerate mixture covariance")
706 elif self.covariance_type == "tied":
707 for i, covar in enumerate(self.covars_):
708 if not np.allclose(covar, covar.T):
709 raise ValueError(
710 f"Covariance of state #{i} is not symmetric")
711 min_eigvalsh = linalg.eigvalsh(covar).min()
712 if min_eigvalsh < 0:
713 raise ValueError(
714 f"Covariance of state #{i} is not positive definite")
715 if min_eigvalsh == 0:
716 _log.warning("Covariance of state #%d has a null "
717 "eigenvalue.", i)
718 elif self.covariance_type == "full":
719 for i, mix_covars in enumerate(self.covars_):
720 for j, covar in enumerate(mix_covars):
721 if not np.allclose(covar, covar.T):
722 raise ValueError(
723 f"Covariance of state #{i}, mixture #{j} is not "
724 f"symmetric")
725 min_eigvalsh = linalg.eigvalsh(covar).min()
726 if min_eigvalsh < 0:
727 raise ValueError(
728 f"Covariance of state #{i}, mixture #{j} is not "
729 f"positive definite")
730 if min_eigvalsh == 0:
731 _log.warning("Covariance of state #%d, mixture #%d "
732 "has a null eigenvalue.", i, j)
733
734 def _do_mstep(self, stats):
735 super()._do_mstep(stats)
736 nf = self.n_features
737 nm = self.n_mix
738
739 # Maximizing weights
740 if 'w' in self.params:
741 alphas_minus_one = self.weights_prior - 1
742 w_n = stats['post_mix_sum'] + alphas_minus_one
743 w_d = (stats['post_sum'] + alphas_minus_one.sum(axis=1))[:, None]
744 self.weights_ = w_n / w_d
745
746 # Maximizing means
747 if 'm' in self.params:
748 m_n = stats['m_n']
749 m_d = stats['post_mix_sum'] + self.means_weight
750 # If a componenent has zero weight, then replace nan (0/0?) means
751 # by 0 (0/1). The actual value is irrelevant as the component will
752 # be unused. This needs to be done before maximizing covariances
753 # as nans would otherwise propagate to other components if
754 # covariances are tied.
755 m_d[(self.weights_ == 0) & (m_n == 0).all(axis=-1)] = 1
756 self.means_ = m_n / m_d[:, :, None]
757
758 # Maximizing covariances
759 if 'c' in self.params:
760 lambdas, mus = self.means_weight, self.means_prior
761 centered_means = self.means_ - mus
762
763 def outer_f(x): # Outer product over features.
764 return x[..., :, None] * x[..., None, :]
765
766 if self.covariance_type == 'full':
767 centered_means_dots = outer_f(centered_means)
768
769 psis_t = np.transpose(self.covars_prior, axes=(0, 1, 3, 2))
770 nus = self.covars_weight
771
772 c_n = psis_t + lambdas[:, :, None, None] * centered_means_dots
773 c_n += stats['c_n']
774 c_d = (
775 stats['post_mix_sum'] + 1 + nus + nf + 1
776 )[:, :, None, None]
777
778 elif self.covariance_type == 'diag':
779 alphas = self.covars_prior
780 betas = self.covars_weight
781 centered_means2 = centered_means ** 2
782
783 c_n = lambdas[:, :, None] * centered_means2 + 2 * betas
784 c_n += stats['c_n']
785 c_d = stats['post_mix_sum'][:, :, None] + 1 + 2 * (alphas + 1)
786
787 elif self.covariance_type == 'spherical':
788 centered_means_norm2 = np.einsum( # Faster than (x**2).sum(-1)
789 '...i,...i', centered_means, centered_means)
790
791 alphas = self.covars_prior
792 betas = self.covars_weight
793
794 c_n = lambdas * centered_means_norm2 + 2 * betas
795 c_n += stats['c_n']
796 c_d = nf * (stats['post_mix_sum'] + 1) + 2 * (alphas + 1)
797
798 elif self.covariance_type == 'tied':
799 centered_means_dots = outer_f(centered_means)
800
801 psis_t = np.transpose(self.covars_prior, axes=(0, 2, 1))
802 nus = self.covars_weight
803
804 c_n = np.einsum('ij,ijkl->ikl',
805 lambdas, centered_means_dots) + psis_t
806 c_n += stats['c_n']
807 c_d = (stats['post_sum'] + nm + nus + nf + 1)[:, None, None]
808
809 self.covars_ = c_n / c_d
810
811
812 class MultinomialHMM(_emissions.BaseMultinomialHMM):
813 """
814 Hidden Markov Model with multinomial emissions.
815
816 Attributes
817 ----------
818 n_features : int
819 Number of possible symbols emitted by the model (in the samples).
820
821 monitor_ : ConvergenceMonitor
822 Monitor object used to check the convergence of EM.
823
824 startprob_ : array, shape (n_components, )
825 Initial state occupation distribution.
826
827 transmat_ : array, shape (n_components, n_components)
828 Matrix of transition probabilities between states.
829
830 emissionprob_ : array, shape (n_components, n_features)
831 Probability of emitting a given symbol when in each state.
832
833 Examples
834 --------
835 >>> from hmmlearn.hmm import MultinomialHMM
836 """
837
838 def __init__(self, n_components=1, n_trials=None,
839 startprob_prior=1.0, transmat_prior=1.0,
840 algorithm="viterbi", random_state=None,
841 n_iter=10, tol=1e-2, verbose=False,
842 params="ste", init_params="ste",
843 implementation="log"):
844 """
845 Parameters
846 ----------
847 n_components : int
848 Number of states.
849
850 n_trials : int or array of int
851 Number of trials (when sampling, all samples must have the same
852 :attr:`n_trials`).
853
854 startprob_prior : array, shape (n_components, ), optional
855 Parameters of the Dirichlet prior distribution for
856 :attr:`startprob_`.
857
858 transmat_prior : array, shape (n_components, n_components), optional
859 Parameters of the Dirichlet prior distribution for each row
860 of the transition probabilities :attr:`transmat_`.
861
862 algorithm : {"viterbi", "map"}, optional
863 Decoder algorithm.
864
865 - "viterbi": finds the most likely sequence of states, given all
866 emissions.
867 - "map" (also known as smoothing or forward-backward): finds the
868 sequence of the individual most-likely states, given all
869 emissions.
870
871 random_state: RandomState or an int seed, optional
872 A random number generator instance.
873
874 n_iter : int, optional
875 Maximum number of iterations to perform.
876
877 tol : float, optional
878 Convergence threshold. EM will stop if the gain in log-likelihood
879 is below this value.
880
881 verbose : bool, optional
882 Whether per-iteration convergence reports are printed to
883 :data:`sys.stderr`. Convergence can also be diagnosed using the
884 :attr:`monitor_` attribute.
885
886 params, init_params : string, optional
887 The parameters that get updated during (``params``) or initialized
888 before (``init_params``) the training. Can contain any
889 combination of 's' for startprob, 't' for transmat, and 'e' for
890 emissionprob. Defaults to all parameters.
891
892 implementation : string, optional
893 Determines if the forward-backward algorithm is implemented with
894 logarithms ("log"), or using scaling ("scaling"). The default is
895 to use logarithms for backwards compatability.
896 """
897 BaseHMM.__init__(self, n_components,
898 startprob_prior=startprob_prior,
899 transmat_prior=transmat_prior,
900 algorithm=algorithm,
901 random_state=random_state,
902 n_iter=n_iter, tol=tol, verbose=verbose,
903 params=params, init_params=init_params,
904 implementation=implementation)
905 self.n_trials = n_trials
906
907 _log.warning(
908 "MultinomialHMM has undergone major changes. "
909 "The previous version was implementing a CategoricalHMM "
910 "(a special case of MultinomialHMM). "
911 "This new implementation follows the standard definition for "
912 "a Multinomial distribution (e.g. as in "
913 "https://en.wikipedia.org/wiki/Multinomial_distribution). "
914 "See these issues for details:\n"
915 "https://github.com/hmmlearn/hmmlearn/issues/335\n"
916 "https://github.com/hmmlearn/hmmlearn/issues/340")
917
918 def _init(self, X, lengths=None):
919 super()._init(X, lengths=None)
920 self.random_state = check_random_state(self.random_state)
921 if 'e' in self.init_params:
922 self.emissionprob_ = self.random_state \
923 .rand(self.n_components, self.n_features)
924 normalize(self.emissionprob_, axis=1)
925
926 def _check(self):
927 super()._check()
928 self.emissionprob_ = np.atleast_2d(self.emissionprob_)
929 n_features = getattr(self, "n_features", self.emissionprob_.shape[1])
930 if self.emissionprob_.shape != (self.n_components, n_features):
931 raise ValueError(
932 "emissionprob_ must have shape (n_components, n_features)")
933 else:
934 self.n_features = n_features
935 if self.n_trials is None:
936 raise ValueError("n_trials must be set")
937
938 def _do_mstep(self, stats):
939 super()._do_mstep(stats)
940 if 'e' in self.params:
941 self.emissionprob_ = (
942 stats['obs'] / stats['obs'].sum(axis=1, keepdims=True))
943
944
945 class PoissonHMM(_emissions.BasePoissonHMM):
946 """
947 Hidden Markov Model with Poisson emissions.
948
949 Attributes
950 ----------
951 monitor_ : ConvergenceMonitor
952 Monitor object used to check the convergence of EM.
953
954 startprob_ : array, shape (n_components, )
955 Initial state occupation distribution.
956
957 transmat_ : array, shape (n_components, n_components)
958 Matrix of transition probabilities between states.
959
960 lambdas_ : array, shape (n_components, n_features)
961 The expectation value of the waiting time parameters for each
962 feature in a given state.
963 """
964
965 def __init__(self, n_components=1, startprob_prior=1.0,
966 transmat_prior=1.0, lambdas_prior=0.0,
967 lambdas_weight=0.0,
968 algorithm="viterbi", random_state=None,
969 n_iter=10, tol=1e-2, verbose=False,
970 params="stl", init_params="stl",
971 implementation="log"):
972 """
973 Parameters
974 ----------
975 n_components : int
976 Number of states.
977
978 startprob_prior : array, shape (n_components, ), optional
979 Parameters of the Dirichlet prior distribution for
980 :attr:`startprob_`.
981
982 transmat_prior : array, shape (n_components, n_components), optional
983 Parameters of the Dirichlet prior distribution for each row
984 of the transition probabilities :attr:`transmat_`.
985
986 lambdas_prior, lambdas_weight : array, shape (n_components,), optional
987 The gamma prior on the lambda values using alpha-beta notation,
988 respectivley. If None, will be set based on the method of
989 moments.
990
991 algorithm : {"viterbi", "map"}, optional
992 Decoder algorithm.
993
994 - "viterbi": finds the most likely sequence of states, given all
995 emissions.
996 - "map" (also known as smoothing or forward-backward): finds the
997 sequence of the individual most-likely states, given all
998 emissions.
999
1000 random_state: RandomState or an int seed, optional
1001 A random number generator instance.
1002
1003 n_iter : int, optional
1004 Maximum number of iterations to perform.
1005
1006 tol : float, optional
1007 Convergence threshold. EM will stop if the gain in log-likelihood
1008 is below this value.
1009
1010 verbose : bool, optional
1011 Whether per-iteration convergence reports are printed to
1012 :data:`sys.stderr`. Convergence can also be diagnosed using the
1013 :attr:`monitor_` attribute.
1014
1015 params, init_params : string, optional
1016 The parameters that get updated during (``params``) or initialized
1017 before (``init_params``) the training. Can contain any
1018 combination of 's' for startprob, 't' for transmat, and 'l' for
1019 lambdas. Defaults to all parameters.
1020
1021 implementation : string, optional
1022 Determines if the forward-backward algorithm is implemented with
1023 logarithms ("log"), or using scaling ("scaling"). The default is
1024 to use logarithms for backwards compatability.
1025 """
1026 BaseHMM.__init__(self, n_components,
1027 startprob_prior=startprob_prior,
1028 transmat_prior=transmat_prior,
1029 algorithm=algorithm,
1030 random_state=random_state,
1031 n_iter=n_iter, tol=tol, verbose=verbose,
1032 params=params, init_params=init_params,
1033 implementation=implementation)
1034 self.lambdas_prior = lambdas_prior
1035 self.lambdas_weight = lambdas_weight
1036
1037 def _init(self, X, lengths=None):
1038 super()._init(X, lengths)
1039 self.random_state = check_random_state(self.random_state)
1040
1041 mean_X = X.mean()
1042 var_X = X.var()
1043
1044 if self._needs_init("l", "lambdas_"):
1045 # initialize with method of moments based on X
1046 self.lambdas_ = self.random_state.gamma(
1047 shape=mean_X**2 / var_X,
1048 scale=var_X / mean_X, # numpy uses theta = 1 / beta
1049 size=(self.n_components, self.n_features))
1050
1051 def _check(self):
1052 super()._check()
1053
1054 self.lambdas_ = np.atleast_2d(self.lambdas_)
1055 n_features = getattr(self, "n_features", self.lambdas_.shape[1])
1056 if self.lambdas_.shape != (self.n_components, n_features):
1057 raise ValueError(
1058 "lambdas_ must have shape (n_components, n_features)")
1059 self.n_features = n_features
1060
1061 def _do_mstep(self, stats):
1062 super()._do_mstep(stats)
1063
1064 if 'l' in self.params:
1065 # Based on: Hyvönen & Tolonen, "Bayesian Inference 2019"
1066 # section 3.2
1067 # https://vioshyvo.github.io/Bayesian_inference
1068 alphas, betas = self.lambdas_prior, self.lambdas_weight
1069 n = stats['post'].sum()
1070 y_bar = stats['obs'] / stats['post'][:, None]
1071 # the same as kappa notation (more intuitive) but avoids divide by
1072 # 0, where:
1073 # kappas = betas / (betas + n)
1074 # self.lambdas_ = kappas * (alphas / betas) + (1 - kappas) * y_bar
1075 self.lambdas_ = (alphas + n * y_bar) / (betas + n)