Debian Codegraph @

src/hmmlearn/vhmm.py

raw symbols SCIP
1 import logging
2 import numbers
3
4 import numpy as np
5 from scipy import special
6 from sklearn import cluster
7 from sklearn.utils import check_random_state
8
9 from . import _kl_divergence as _kl, _utils
10 from ._emissions import BaseCategoricalHMM, BaseGaussianHMM
11 from .base import VariationalBaseHMM
12 from .hmm import COVARIANCE_TYPES
13 from .utils import fill_covars
14
15
16 _log = logging.getLogger(__name__)
17
18
19 class VariationalCategoricalHMM(BaseCategoricalHMM, VariationalBaseHMM):
20 """
21 Hidden Markov Model with categorical (discrete) emissions trained
22 using Variational Inference.
23
24 References:
25 * https://cse.buffalo.edu/faculty/mbeal/thesis/
26
27 Attributes
28 ----------
29 n_features : int
30 Number of possible symbols emitted by the model (in the samples).
31
32 monitor_ : ConvergenceMonitor
33 Monitor object used to check the convergence of EM.
34
35 startprob_prior_ : array, shape (n_components, )
36 Prior for the initial state occupation distribution.
37
38 startprob_posterior_ : array, shape (n_components, )
39 Posterior estimate of the state occupation distribution.
40
41 transmat_prior_ : array, shape (n_components, n_components)
42 Prior for the matrix of transition probabilities between states.
43
44 transmat_posterior_ : array, shape (n_components, n_components)
45 Posterior estimate of the transition probabilities between states.
46
47 emissionprob_prior_ : array, shape (n_components, n_features)
48 Prior estimatate of emitting a given symbol when in each state.
49
50 emissionprob_posterior_ : array, shape (n_components, n_features)
51 Posterior estimate of emitting a given symbol when in each state.
52
53 Examples
54 --------
55 >>> from hmmlearn.hmm import VariationalCategoricalHMM
56 >>> VariationalCategoricalHMM(n_components=2) #doctest: +ELLIPSIS
57 VariationalCategoricalHMM(algorithm='viterbi',...
58 """
59
60 def __init__(self, n_components=1,
61 startprob_prior=None, transmat_prior=None,
62 emissionprob_prior=None, n_features=None,
63 algorithm="viterbi", random_state=None,
64 n_iter=100, tol=1e-6, verbose=False,
65 params="ste", init_params="ste",
66 implementation="log"):
67 """
68 Parameters
69 ----------
70 n_components : int
71 Number of states.
72
73 startprob_prior : array, shape (n_components, ), optional
74 Parameters of the Dirichlet prior distribution for
75 :attr:`startprob_`.
76
77 transmat_prior : array, shape (n_components, n_components), optional
78 Parameters of the Dirichlet prior distribution for each row
79 of the transition probabilities :attr:`transmat_`.
80
81 emissionprob_prior : array, shape (n_components, n_features), optional
82 Parameters of the Dirichlet prior distribution for
83 :attr:`emissionprob_`.
84
85 n_features: int, optional
86 The number of categorical symbols in the HMM. Will be inferred
87 from the data if not set.
88
89 algorithm : {"viterbi", "map"}, optional
90 Decoder algorithm.
91
92 - "viterbi": finds the most likely sequence of states, given all
93 emissions.
94 - "map" (also known as smoothing or forward-backward): finds the
95 sequence of the individual most-likely states, given all
96 emissions.
97
98 random_state: RandomState or an int seed, optional
99 A random number generator instance.
100
101 n_iter : int, optional
102 Maximum number of iterations to perform.
103
104 tol : float, optional
105 Convergence threshold. EM will stop if the gain in log-likelihood
106 is below this value.
107
108 verbose : bool, optional
109 Whether per-iteration convergence reports are printed to
110 :data:`sys.stderr`. Convergence can also be diagnosed using the
111 :attr:`monitor_` attribute.
112
113 params, init_params : string, optional
114 The parameters that get updated during (``params``) or initialized
115 before (``init_params``) the training. Can contain any
116 combination of 's' for startprob, 't' for transmat, and 'e' for
117 emissionprob. Defaults to all parameters.
118
119 implementation : string, optional
120 Determines if the forward-backward algorithm is implemented with
121 logarithms ("log"), or using scaling ("scaling"). The default is
122 to use logarithms for backwards compatability.
123 """
124 super().__init__(
125 n_components=n_components, startprob_prior=startprob_prior,
126 transmat_prior=transmat_prior,
127 algorithm=algorithm, random_state=random_state,
128 n_iter=n_iter, tol=tol, verbose=verbose,
129 params=params, init_params=init_params,
130 implementation=implementation
131 )
132 self.emissionprob_prior = emissionprob_prior
133 self.n_features = n_features
134
135 def _init(self, X, lengths):
136 """
137 Initialize model parameters prior to fitting.
138
139 Parameters
140 ----------
141 X : array-like, shape (n_samples, n_features)
142 Feature matrix of individual samples.
143 lengths : array-like of integers, shape (n_sequences, )
144 Lengths of the individual sequences in ``X``. The sum of
145 these should be ``n_samples``.
146 """
147 super()._init(X, lengths)
148 random_state = check_random_state(self.random_state)
149 if self._needs_init("e", "emissionprob_posterior_"):
150 emissionprob_init = 1 / self.n_features
151 if self.emissionprob_prior is not None:
152 emissionprob_init = self.emissionprob_prior
153 self.emissionprob_prior_ = np.full(
154 (self.n_components, self.n_features), emissionprob_init)
155 self.emissionprob_posterior_ = random_state.dirichlet(
156 alpha=[emissionprob_init] * self.n_features,
157 size=self.n_components
158 ) * sum(lengths) / self.n_components
159
160 def _estep_begin(self):
161 super()._estep_begin()
162 # Stored / Computed for efficiency otherwise
163 # it would be done in _compute_subnorm_log_likelihood
164 self.emissionprob_log_subnorm_ = (
165 special.digamma(self.emissionprob_posterior_)
166 - special.digamma(
167 self.emissionprob_posterior_.sum(axis=1)[:, None]))
168
169 def _check(self):
170 """
171 Validate model parameters prior to fitting.
172
173 Raises
174 ------
175 ValueError
176 If any of the parameters are invalid, e.g. if :attr:`startprob_`
177 don't sum to 1.
178 """
179 super()._check()
180
181 self.emissionprob_prior_ = np.atleast_2d(self.emissionprob_prior_)
182 self.emissionprob_posterior_ = \
183 np.atleast_2d(self.emissionprob_posterior_)
184
185 if (self.emissionprob_prior_.shape
186 != self.emissionprob_posterior_.shape):
187 raise ValueError(
188 "emissionprob_prior_ and emissionprob_posterior_must"
189 "have shape (n_components, n_features)")
190 if self.n_features is None:
191 self.n_features = self.emissionprob_posterior_.shape[1]
192 if (self.emissionprob_posterior_.shape
193 != (self.n_components, self.n_features)):
194 raise ValueError(
195 f"emissionprob_ must have shape"
196 f"({self.n_components}, {self.n_features})")
197
198 def _compute_subnorm_log_likelihood(self, X):
199 return self.emissionprob_log_subnorm_[:, X.squeeze(1)].T
200
201 def _do_mstep(self, stats):
202 """
203 Perform the M-step of the VB-EM algorithm.
204
205 Parameters
206 ----------
207 stats : dict
208 Sufficient statistics updated from all available samples.
209 """
210 super()._do_mstep(stats)
211 # emissionprob
212 if "e" in self.params:
213 self.emissionprob_posterior_ = (
214 self.emissionprob_prior_ + stats['obs'])
215 # Provide the normalized probabilities at the posterior median
216 div = self.emissionprob_posterior_.sum(axis=1)[:, None]
217 self.emissionprob_ = self.emissionprob_posterior_ / div
218
219 def _compute_lower_bound(self, log_prob):
220 """Compute the lower bound of the model."""
221 # First, get the contribution from the state transitions
222 # and initial probabilities
223 lower_bound = super()._compute_lower_bound(log_prob)
224
225 # The compute the contributions of the emissionprob
226 emissionprob_lower_bound = 0
227 for i in range(self.n_components):
228 emissionprob_lower_bound -= _kl.kl_dirichlet(
229 self.emissionprob_posterior_[i], self.emissionprob_prior_[i])
230 return lower_bound + emissionprob_lower_bound
231
232
233 class VariationalGaussianHMM(BaseGaussianHMM, VariationalBaseHMM):
234 """
235 Hidden Markov Model with Multivariate Gaussian Emissions trained
236 using Variational Inference.
237
238 References:
239 * https://arxiv.org/abs/1605.08618
240 * https://core.ac.uk/reader/10883750
241 * https://theses.gla.ac.uk/6941/7/2005McGroryPhD.pdf
242
243 Attributes
244 ----------
245 n_features : int
246 Dimensionality of the Gaussian emissions.
247
248 monitor_ : ConvergenceMonitor
249 Monitor object used to check the convergence of EM.
250
251 startprob_prior_ : array, shape (n_components, )
252 Prior for the initial state occupation distribution.
253
254 startprob_posterior_ : array, shape (n_components, )
255 Posterior estimate of the state occupation distribution.
256
257 transmat_prior_ : array, shape (n_components, n_components)
258 Prior for the matrix of transition probabilities between states.
259
260 transmat_posterior_ : array, shape (n_components, n_components)
261 Posterior estimate of the transition probabilities between states.
262
263 means_prior_: array, shape (n_components, n_features)
264 Prior estimates for the mean of each state.
265
266 means_posterior_: array, shape (n_components, n_features)
267 Posterior estimates for the mean of each state.
268
269 beta_prior_: array, shape (n_components, )
270 Prior estimate on the scale of the variance over the means.
271
272 beta_posterior_: array, shape (n_components, )
273 Posterior estimate of the scale of the variance over the means.
274
275 covars_ : array
276 Covariance parameters for each state.
277
278 The shape depends on :attr:`covariance_type`:
279
280 * (n_components, ) if "spherical",
281 * (n_components, n_features) if "diag",
282 * (n_components, n_features, n_features) if "full",
283 * (n_features, n_features) if "tied".
284
285 dof_prior_: int / array
286 The Degrees Of Freedom prior for each state's Wishart distribution.
287 The type depends on :attr:`covariance_type`:
288
289 * array, shape (n_components, ) if "full",
290 * int if "tied".
291
292 dof_prior_: int / array
293 The Prior on the Degrees Of Freedom
294 for each state's Wishart distribution.
295 The type depends on :attr:`covariance_type`:
296
297 * array, shape (n_components, ) if "full",
298 * int if "tied".
299
300 dof_posterior_: int / array
301 The Degrees Of Freedom for each state's Wishart distribution.
302 The type depends on :attr:`covariance_type`:
303
304 * array, shape (n_components, ) if "full",
305 * int if "tied".
306
307 scale_prior_ : array
308 Prior for the Inverse scale parameter for each state's
309 Wishart distribution. The wishart distribution is
310 the conjugate prior for the covariance.
311
312 The shape depends on :attr:`covariance_type`:
313
314 * (n_components, ) if "spherical",
315 * (n_components, n_features) if "diag",
316 * (n_components, n_features, n_features) if "full",
317 * (n_features, n_features) if "tied".
318
319 scale_posterior_ : array
320 Inverse scale parameter for each state's wishart distribution.
321 The wishart distribution is the conjugate prior for the covariance.
322
323 The shape depends on :attr:`covariance_type`:
324
325 * (n_components, ) if "spherical",
326 * (n_components, n_features) if "diag",
327 * (n_components, n_features, n_features) if "full",
328 * (n_features, n_features) if "tied".
329
330 Examples
331 --------
332 >>> from hmmlearn.hmm import VariationalGaussianHMM
333 >>> VariationalGaussianHMM(n_components=2) #doctest: +ELLIPSIS
334 VariationalGaussianHMM(algorithm='viterbi',...
335 """
336
337 def __init__(self, n_components=1, covariance_type="full",
338 startprob_prior=None, transmat_prior=None,
339 means_prior=None, beta_prior=None, dof_prior=None,
340 scale_prior=None, algorithm="viterbi",
341 random_state=None, n_iter=100, tol=1e-6, verbose=False,
342 params="stmc", init_params="stmc",
343 implementation="log"):
344 """
345 Parameters
346 ----------
347 n_components : int
348 Number of states.
349
350 covariance_type : {"spherical", "diag", "full", "tied"}, optional
351 The type of covariance parameters to use:
352
353 * "spherical" --- each state uses a single variance value that
354 applies to all features (default).
355 * "diag" --- each state uses a diagonal covariance matrix.
356 * "full" --- each state uses a full (i.e. unrestricted)
357 covariance matrix.
358 * "tied" --- all states use **the same** full covariance matrix.
359
360 startprob_prior : array, shape (n_components, ), optional
361 Parameters of the Dirichlet prior distribution for
362 :attr:`startprob_`.
363
364 transmat_prior : array, shape (n_components, n_components), optional
365 Parameters of the Dirichlet prior distribution for each row
366 of the transition probabilities :attr:`transmat_`.
367
368 means_prior, beta_prior : array, shape (n_components, ), optional
369 Mean and precision of the Normal prior distribtion for
370 :attr:`means_`.
371
372 scale_prior, dof_prior : array, optional
373 Parameters of the prior distribution for the covariance matrix
374 :attr:`covars_`.
375
376 If :attr:`covariance_type` is "spherical" or "diag" the prior is
377 the inverse gamma distribution, otherwise --- the inverse Wishart
378 distribution.
379
380 The shape of the scale_prior array depends on
381 :attr:`covariance_type`:
382
383 * (n_components, ) if "spherical",
384 * (n_components, n_features) if "diag",
385 * (n_components, n_features, n_features) if "full",
386 * (n_features, n_features) if "tied".
387
388 algorithm : {"viterbi", "map"}, optional
389 Decoder algorithm.
390
391 - "viterbi": finds the most likely sequence of states, given all
392 emissions.
393 - "map" (also known as smoothing or forward-backward): finds the
394 sequence of the individual most-likely states, given all
395 emissions.
396
397 random_state: RandomState or an int seed, optional
398 A random number generator instance.
399
400 n_iter : int, optional
401 Maximum number of iterations to perform.
402
403 tol : float, optional
404 Convergence threshold. EM will stop if the gain in log-likelihood
405 is below this value.
406
407 verbose : bool, optional
408 Whether per-iteration convergence reports are printed to
409 :data:`sys.stderr`. Convergence can also be diagnosed using the
410 :attr:`monitor_` attribute.
411
412 params, init_params : string, optional
413 The parameters that get updated during (``params``) or initialized
414 before (``init_params``) the training. Can contain any combination
415 of 's' for startprob, 't' for transmat, 'm' for means, and 'c' for
416 covars. Defaults to all parameters.
417
418 implementation : string, optional
419 Determines if the forward-backward algorithm is implemented with
420 logarithms ("log"), or using scaling ("scaling"). The default is
421 to use logarithms for backwards compatability.
422 """
423 super().__init__(
424 n_components=n_components, startprob_prior=startprob_prior,
425 transmat_prior=transmat_prior,
426 algorithm=algorithm, random_state=random_state,
427 n_iter=n_iter, tol=tol, verbose=verbose,
428 params=params, init_params=init_params,
429 implementation=implementation
430 )
431 self.covariance_type = covariance_type
432 self.means_prior = means_prior
433 self.beta_prior = beta_prior
434 self.dof_prior = dof_prior
435 self.scale_prior = scale_prior
436
437 @property
438 def covars_(self):
439 """Return covars as a full matrix."""
440 return fill_covars(self._covars_, self.covariance_type,
441 self.n_components, self.n_features)
442
443 @covars_.setter
444 def covars_(self, covars):
445 covars = np.array(covars, copy=True)
446 _utils._validate_covars(covars, self.covariance_type,
447 self.n_components)
448 self._covars_ = covars
449
450 @property
451 def means_(self):
452 """
453 Compat for _BaseGaussianHMM. We return the mean of the
454 approximating distribution, which for us is just `means_posterior_`
455 """
456 return self.means_posterior_
457
458 def _init(self, X, lengths):
459 """
460 Initialize model parameters prior to fitting.
461
462 Parameters
463 ----------
464 X : array-like, shape (n_samples, n_features)
465 Feature matrix of individual samples.
466 lengths : array-like of integers, shape (n_sequences, )
467 Lengths of the individual sequences in ``X``. The sum of
468 these should be ``n_samples``.
469 """
470 super()._init(X, lengths)
471
472 X_mean = X.mean(axis=0)
473 # Kmeans will be used for initializing both the means
474 # and the covariances
475 kmeans = cluster.KMeans(n_clusters=self.n_components,
476 random_state=self.random_state,
477 n_init=10) # sklearn >=1.2 compat.
478 kmeans.fit(X)
479 cluster_counts = np.bincount(kmeans.predict(X))
480
481 if (self._needs_init("m", "means_prior_")
482 or self._needs_init("m", "means_posterior_")
483 or self._needs_init("m", "beta_prior_")
484 or self._needs_init("m", "beta_posterior_")):
485 if self.means_prior is None:
486 self.means_prior_ = np.full(
487 (self.n_components, self.n_features), X_mean)
488 else:
489 self.means_prior_ = self.means_prior
490 # Initialize to the data means
491 self.means_posterior_ = np.copy(kmeans.cluster_centers_)
492
493 if self.beta_prior is None:
494 self.beta_prior_ = np.zeros(self.n_components) + 1
495 else:
496 self.beta_prior_ = self.beta_prior
497
498 # Count of items in each cluster
499 self.beta_posterior_ = np.copy(cluster_counts)
500
501 if (self._needs_init("c", "dof_prior_")
502 or self._needs_init("c", "dof_posterior_")
503 or self._needs_init("c", "scale_prior_")
504 or self._needs_init("c", "scale_posterior_")):
505 if self.covariance_type in ("full", "diag", "spherical"):
506 if self.dof_prior is None:
507 self.dof_prior_ = np.full(
508 (self.n_components,), self.n_features)
509 else:
510 self.dof_prior_ = self.dof_prior
511 self.dof_posterior_ = np.copy(cluster_counts)
512
513 elif self.covariance_type == "tied":
514 if self.dof_prior is None:
515 self.dof_prior_ = self.n_features
516 else:
517 self.dof_prior_ = self.dof_prior
518 self.dof_posterior_ = cluster_counts.sum()
519
520 # Covariance posterior comes from the estimate of the data
521 # We store and update both W_k and scale_posterior_,
522 # as they each are used in the EM-like algorithm
523 cv = np.cov(X.T) + 1E-3 * np.eye(X.shape[1])
524 self.covars_ = \
525 _utils.distribute_covar_matrix_to_match_covariance_type(
526 cv, self.covariance_type, self.n_components).copy()
527
528 if self.covariance_type == "full":
529 if self.scale_prior is None:
530 self.scale_prior_ = np.broadcast_to(
531 np.identity(self.n_features) * 1e-3,
532 (self.n_components, self.n_features, self.n_features)
533 )
534 else:
535 self.scale_prior_ = self.scale_prior
536 self.scale_posterior_ = (
537 self._covars_
538 * np.asarray(self.dof_posterior_)[:, None, None])
539
540 elif self.covariance_type == "tied":
541 if self.scale_prior is None:
542 self.scale_prior_ = np.identity(self.n_features) * 1e-3
543 else:
544 self.scale_prior_ = self.scale_prior
545 self.scale_posterior_ = self._covars_ * self.dof_posterior_
546
547 elif self.covariance_type == "diag":
548 if self.scale_prior is None:
549 self.scale_prior_ = np.full(
550 (self.n_components, self.n_features), 1e-3)
551 else:
552 self.scale_prior_ = self.scale_prior
553 self.scale_posterior_ = np.einsum(
554 "ij,i->ij",self._covars_, self.dof_posterior_)
555
556 elif self.covariance_type == "spherical":
557 if self.scale_prior is None:
558 self.scale_prior_ = np.full((self.n_components, ), 1e-3)
559 else:
560 self.scale_prior_ = self.scale_prior
561 self.scale_posterior_ = (self._covars_.mean(axis=1)
562 * self.dof_posterior_)
563
564 def _get_n_fit_scalars_per_param(self):
565 if self.covariance_type not in COVARIANCE_TYPES:
566 raise ValueError(
567 f"{self.covariance_type} is invalid")
568 nc = self.n_components
569 nf = self.n_features
570 return {
571 "s": nc - 1,
572 "t": nc * (nc - 1),
573 "m": nc * nf + nc,
574 "c": {
575 "full": nc + nc * nf * (nf + 1) // 2,
576 "tied": 1 + nf * (nf + 1) // 2,
577 "diag": nc + nc * nf,
578 "spherical": nc + nc,
579
580 }[self.covariance_type],
581 }
582
583 def _check(self):
584 """
585 Validate model parameters prior to fitting.
586
587 Raises
588 ------
589 ValueError
590 If any of the parameters are invalid, e.g. if :attr:`startprob_`
591 don't sum to 1.
592 """
593
594 if self.covariance_type not in COVARIANCE_TYPES:
595 raise ValueError(
596 f"{self.covariance_type} is invalid")
597
598 means_shape = (self.n_components, self.n_features)
599
600 self.means_prior_ = np.asarray(self.means_prior_, dtype=float)
601 self.means_posterior_ = np.asarray(self.means_posterior_, dtype=float)
602 if self.means_prior_.shape != means_shape:
603 raise ValueError(
604 "means_prior_ have shape (n_components, n_features)")
605 if self.means_posterior_.shape != means_shape:
606 raise ValueError(
607 "means_posterior_ must have shape (n_components, n_features)")
608
609 self.beta_prior_ = np.asarray(self.beta_prior_, dtype=float)
610 self.beta_posterior_ = np.asarray(self.beta_posterior_, dtype=float)
611 if self.beta_prior_.shape != (self.n_components,):
612 raise ValueError(
613 "beta_prior_ have shape (n_components,)")
614
615 if self.beta_posterior_.shape != (self.n_components,):
616 raise ValueError(
617 "beta_posterior_ must have shape (n_components,)")
618
619 if self.covariance_type in ("full", "diag", "spherical"):
620 self.dof_prior_ = np.asarray(self.dof_prior_, dtype=float)
621 self.dof_posterior_ = np.asarray(self.dof_posterior_, dtype=float)
622 if self.dof_prior_.shape != (self.n_components,):
623 raise ValueError(
624 "dof_prior_ have shape (n_components,)")
625
626 if self.dof_posterior_.shape != (self.n_components,):
627 raise ValueError(
628 "dof_posterior_ must have shape (n_components,)")
629
630 elif self.covariance_type == "tied":
631 if not isinstance(self.dof_prior_, numbers.Number):
632 raise ValueError("dof_prior_ should be numeric")
633 if not isinstance(self.dof_posterior_, numbers.Number):
634 raise ValueError("dof_posterior_ should be numeric")
635
636 self.scale_prior_ = np.asarray(self.scale_prior_, dtype=float)
637 self.scale_posterior_ = np.asarray(self.scale_posterior_, dtype=float)
638
639 expected = None
640 if self.covariance_type == "full":
641 expected = (self.n_components, self.n_features, self.n_features)
642 elif self.covariance_type == "tied":
643 expected = (self.n_features, self.n_features)
644 elif self.covariance_type == "diag":
645 expected = (self.n_components, self.n_features)
646 elif self.covariance_type == "spherical":
647 expected = (self.n_components, )
648 # Now check the W's
649 if self.scale_prior_.shape != expected:
650 raise ValueError(f"scale_prior_ must have shape {expected}, "
651 f"found {self.scale_prior_.shape}")
652
653 if self.scale_posterior_.shape != expected:
654 raise ValueError(f"scale_posterior_ must have shape {expected}, "
655 f"found {self.scale_posterior_.shape}")
656
657 def _compute_subnorm_log_likelihood(self, X):
658 # Refer to the Gruhl/Sick paper for the notation
659 # In general, things are neater if we pretend the covariance is
660 # full / tied. Or, we could treat each case separately, and reduce
661 # the number of operations. That's left for the future :-)
662 nf = self.n_features
663
664 term1 = special.digamma(
665 .5 * (self.dof_posterior_ - np.arange(0, nf)[:, None])
666 ).sum(axis=0)
667
668 scale_posterior_ = self.scale_posterior_
669 if self.covariance_type in ("diag", "spherical"):
670 scale_posterior_ = fill_covars(self.scale_posterior_,
671 self.covariance_type, self.n_components, self.n_features)
672 W_k = np.linalg.inv(scale_posterior_)
673 term1 += nf * np.log(2) + _utils.logdet(W_k)
674 term1 /= 2.
675
676 # We ignore the constant that is typically excluded in the literature
677 # term2 = self.n_features * log(2 * M_PI) / 2
678 term2 = 0
679 term3 = nf / self.beta_posterior_
680
681 # (X - Means) * W_k * (X-Means)^T * self.dof_posterior_
682 delta = (X - self.means_posterior_[:, None])
683 # c is the HMM Component
684 # i is the length of the sequence X
685 # j, k are the n_features
686 # output shape is length * number of components
687 if self.covariance_type in ("full", "diag", "spherical"):
688 dots = np.einsum("cij,cjk,cik,c->ic",
689 delta, W_k, delta, self.dof_posterior_)
690 elif self.covariance_type == "tied":
691 dots = np.einsum("cij,jk,cik,->ic",
692 delta, W_k, delta, self.dof_posterior_)
693 last_term = .5 * (dots + term3)
694 lll = term1 - term2 - last_term
695 return lll
696
697 def _do_mstep(self, stats):
698 """
699 Perform the M-step of VB-EM algorithm.
700
701 Parameters
702 ----------
703 stats : dict
704 Sufficient statistics updated from all available samples.
705 """
706 super()._do_mstep(stats)
707
708 if "m" in self.params:
709 self.beta_posterior_ = self.beta_prior_ + stats['post']
710 self.means_posterior_ = np.einsum("i,ij->ij", self.beta_prior_,
711 self.means_prior_)
712 self.means_posterior_ += stats['obs']
713 self.means_posterior_ /= self.beta_posterior_[:, None]
714
715 if "c" in self.params:
716 if self.covariance_type == "full":
717 # Update DOF
718 self.dof_posterior_ = self.dof_prior_ + stats['post']
719 # Update scale
720 self.scale_posterior_ = (
721 self.scale_prior_
722 + stats['obs*obs.T']
723 + np.einsum("c,ci,cj->cij",
724 self.beta_prior_,
725 self.means_prior_,
726 self.means_prior_)
727 - np.einsum("c,ci,cj->cij",
728 self.beta_posterior_,
729 self.means_posterior_,
730 self.means_posterior_))
731 self._covars_ = (self.scale_posterior_
732 / self.dof_posterior_[:, None, None])
733 elif self.covariance_type == "tied":
734 # Update DOF
735 self.dof_posterior_ = self.dof_prior_ + stats['post'].sum()
736 # Update scale
737 self.scale_posterior_ = (
738 self.scale_prior_
739 + stats['obs*obs.T'].sum(axis=0)
740 + np.einsum("c,ci,cj->ij",
741 self.beta_prior_,
742 self.means_prior_,
743 self.means_prior_)
744 - np.einsum("c,ci,cj->ij",
745 self.beta_posterior_,
746 self.means_posterior_,
747 self.means_posterior_))
748 self._covars_ = self.scale_posterior_ / self.dof_posterior_
749 elif self.covariance_type == "diag":
750 # Update DOF
751 self.dof_posterior_ = self.dof_prior_ + stats['post']
752 # Update scale
753 self.scale_posterior_ = (
754 self.scale_prior_
755 + stats['obs**2']
756 + np.einsum("c,ci,ci->ci",
757 self.beta_prior_,
758 self.means_prior_,
759 self.means_prior_)
760 - np.einsum("c,ci,ci->ci",
761 self.beta_posterior_,
762 self.means_posterior_,
763 self.means_posterior_))
764 self._covars_ = (self.scale_posterior_
765 / self.dof_posterior_[:, None])
766 elif self.covariance_type == "spherical":
767 # Update DOF
768 self.dof_posterior_ = self.dof_prior_ + stats['post']
769 # Update scale
770 term2 = (stats['obs**2']
771 + np.einsum("c,ci,ci->ci",
772 self.beta_prior_,
773 self.means_prior_,
774 self.means_prior_)
775 - np.einsum("c,ci,ci->ci",
776 self.beta_posterior_,
777 self.means_posterior_,
778 self.means_posterior_))
779 self.scale_posterior_ = (
780 self.scale_prior_
781 + term2.mean(axis=1))
782 self.scale_posterior_ = self.scale_posterior_
783 self._covars_ = (self.scale_posterior_
784 / self.dof_posterior_)
785
786 def _compute_lower_bound(self, log_prob):
787
788 # First, get the contribution from the state transitions
789 # and initial probabilities
790 lower_bound = super()._compute_lower_bound(log_prob)
791
792 # The compute the contributions of the emissions
793 emissions_lower_bound = 0
794
795 # For ease of implementation, pretend everything is shaped like
796 # full covariance.
797 scale_posterior_ = self.scale_posterior_
798 scale_prior_ = self.scale_prior_
799 if self.covariance_type != "full":
800 scale_posterior_ = fill_covars(self.scale_posterior_,
801 self.covariance_type, self.n_components, self.n_features)
802 scale_prior_ = fill_covars(self.scale_prior_,
803 self.covariance_type, self.n_components, self.n_features)
804
805 W_k = np.linalg.inv(scale_posterior_)
806
807 if self.covariance_type != "tied":
808 dof = self.dof_posterior_
809 else:
810 dof = np.repeat(self.dof_posterior_, self.n_components)
811
812 for i in range(self.n_components):
813 precision = W_k[i] * dof[i]
814 # KL for the normal distributions
815 term1 = np.linalg.inv(self.beta_posterior_[i] * precision)
816 term2 = np.linalg.inv(self.beta_prior_[i] * precision)
817 kln = _kl.kl_multivariate_normal_distribution(
818 self.means_posterior_[i], term1,
819 self.means_prior_[i], term2,
820 )
821 emissions_lower_bound -= kln
822 # KL for the wishart distributions
823 klw = 0.
824 if self.covariance_type in ("full", "diag", "spherical"):
825 klw = _kl.kl_wishart_distribution(
826 self.dof_posterior_[i], scale_posterior_[i],
827 self.dof_prior_[i], scale_prior_[i])
828 elif self.covariance_type == "tied":
829 # Just compute it for the first component
830 if i == 0:
831 klw = _kl.kl_wishart_distribution(
832 self.dof_posterior_, self.scale_posterior_,
833 self.dof_prior_, self.scale_prior_)
834 else:
835 klw = 0
836
837 emissions_lower_bound -= klw
838 return lower_bound + emissions_lower_bound
839
840 def _needs_sufficient_statistics_for_mean(self):
841 return 'm' in self.params or 'c' in self.params
842
843 def _needs_sufficient_statistics_for_covars(self):
844 return 'c' in self.params