| 1 |
import logging |
| 2 |
import string |
| 3 |
import sys |
| 4 |
from collections import deque |
| 5 |
|
| 6 |
import numpy as np |
| 7 |
from scipy import linalg, special |
| 8 |
from sklearn.base import BaseEstimator |
| 9 |
from sklearn.utils.validation import ( |
| 10 |
check_array, check_is_fitted, check_random_state) |
| 11 |
|
| 12 |
from . import _hmmc, _kl_divergence as _kl, _utils |
| 13 |
from .utils import normalize, log_normalize |
| 14 |
|
| 15 |
|
| 16 |
_log = logging.getLogger(__name__) |
| 17 |
|
| 18 |
DECODER_ALGORITHMS = frozenset(("viterbi", "map")) |
| 19 |
|
| 20 |
|
| 21 |
class ConvergenceMonitor: |
| 22 |
""" |
| 23 |
Monitor and report convergence to :data:`sys.stderr`. |
| 24 |
|
| 25 |
Attributes |
| 26 |
---------- |
| 27 |
history : deque |
| 28 |
The log probability of the data for the last two training |
| 29 |
iterations. If the values are not strictly increasing, the |
| 30 |
model did not converge. |
| 31 |
iter : int |
| 32 |
Number of iterations performed while training the model. |
| 33 |
|
| 34 |
Examples |
| 35 |
-------- |
| 36 |
Use custom convergence criteria by subclassing ``ConvergenceMonitor`` |
| 37 |
and redefining the ``converged`` method. The resulting subclass can |
| 38 |
be used by creating an instance and pointing a model's ``monitor_`` |
| 39 |
attribute to it prior to fitting. |
| 40 |
|
| 41 |
>>> from hmmlearn.base import ConvergenceMonitor |
| 42 |
>>> from hmmlearn import hmm |
| 43 |
>>> |
| 44 |
>>> class ThresholdMonitor(ConvergenceMonitor): |
| 45 |
... @property |
| 46 |
... def converged(self): |
| 47 |
... return (self.iter == self.n_iter or |
| 48 |
... self.history[-1] >= self.tol) |
| 49 |
>>> |
| 50 |
>>> model = hmm.GaussianHMM(n_components=2, tol=5, verbose=True) |
| 51 |
>>> model.monitor_ = ThresholdMonitor(model.monitor_.tol, |
| 52 |
... model.monitor_.n_iter, |
| 53 |
... model.monitor_.verbose) |
| 54 |
""" |
| 55 |
|
| 56 |
_template = "{iter:>10d} {log_prob:>16.8f} {delta:>+16.8f}" |
| 57 |
|
| 58 |
def __init__(self, tol, n_iter, verbose): |
| 59 |
""" |
| 60 |
Parameters |
| 61 |
---------- |
| 62 |
tol : double |
| 63 |
Convergence threshold. EM has converged either if the maximum |
| 64 |
number of iterations is reached or the log probability improvement |
| 65 |
between the two consecutive iterations is less than threshold. |
| 66 |
n_iter : int |
| 67 |
Maximum number of iterations to perform. |
| 68 |
verbose : bool |
| 69 |
Whether per-iteration convergence reports are printed. |
| 70 |
""" |
| 71 |
self.tol = tol |
| 72 |
self.n_iter = n_iter |
| 73 |
self.verbose = verbose |
| 74 |
self.history = deque() |
| 75 |
self.iter = 0 |
| 76 |
|
| 77 |
def __repr__(self): |
| 78 |
class_name = self.__class__.__name__ |
| 79 |
params = sorted(dict(vars(self), history=list(self.history)).items()) |
| 80 |
return ("{}(\n".format(class_name) |
| 81 |
+ "".join(map(" {}={},\n".format, *zip(*params))) |
| 82 |
+ ")") |
| 83 |
|
| 84 |
def _reset(self): |
| 85 |
"""Reset the monitor's state.""" |
| 86 |
self.iter = 0 |
| 87 |
self.history.clear() |
| 88 |
|
| 89 |
def report(self, log_prob): |
| 90 |
""" |
| 91 |
Report convergence to :data:`sys.stderr`. |
| 92 |
|
| 93 |
The output consists of three columns: iteration number, log |
| 94 |
probability of the data at the current iteration and convergence |
| 95 |
rate. At the first iteration convergence rate is unknown and |
| 96 |
is thus denoted by NaN. |
| 97 |
|
| 98 |
Parameters |
| 99 |
---------- |
| 100 |
log_prob : float |
| 101 |
The log probability of the data as computed by EM algorithm |
| 102 |
in the current iteration. |
| 103 |
""" |
| 104 |
if self.verbose: |
| 105 |
delta = log_prob - self.history[-1] if self.history else np.nan |
| 106 |
message = self._template.format( |
| 107 |
iter=self.iter + 1, log_prob=log_prob, delta=delta) |
| 108 |
print(message, file=sys.stderr) |
| 109 |
|
| 110 |
|
| 111 |
precision = np.finfo(float).eps ** (1/2) |
| 112 |
if self.history and (log_prob - self.history[-1]) < -precision: |
| 113 |
delta = log_prob - self.history[-1] |
| 114 |
_log.warning(f"Model is not converging. Current: {log_prob}" |
| 115 |
f" is not greater than {self.history[-1]}." |
| 116 |
f" Delta is {delta}") |
| 117 |
self.history.append(log_prob) |
| 118 |
self.iter += 1 |
| 119 |
|
| 120 |
@property |
| 121 |
def converged(self): |
| 122 |
"""Whether the EM algorithm converged.""" |
| 123 |
|
| 124 |
return (self.iter == self.n_iter or |
| 125 |
(len(self.history) >= 2 and |
| 126 |
self.history[-1] - self.history[-2] < self.tol)) |
| 127 |
|
| 128 |
|
| 129 |
class _AbstractHMM(BaseEstimator): |
| 130 |
""" |
| 131 |
Base class for Hidden Markov Models learned via Expectation-Maximization |
| 132 |
and Variational Bayes. |
| 133 |
""" |
| 134 |
|
| 135 |
def __init__(self, n_components, algorithm, random_state, n_iter, |
| 136 |
tol, verbose, params, init_params, implementation): |
| 137 |
""" |
| 138 |
Parameters |
| 139 |
---------- |
| 140 |
n_components : int |
| 141 |
Number of states in the model. |
| 142 |
algorithm : {"viterbi", "map"}, optional |
| 143 |
Decoder algorithm. |
| 144 |
|
| 145 |
- "viterbi": finds the most likely sequence of states, given all |
| 146 |
emissions. |
| 147 |
- "map" (also known as smoothing or forward-backward): finds the |
| 148 |
sequence of the individual most-likely states, given all |
| 149 |
emissions. |
| 150 |
random_state: RandomState or an int seed, optional |
| 151 |
A random number generator instance. |
| 152 |
n_iter : int, optional |
| 153 |
Maximum number of iterations to perform. |
| 154 |
tol : float, optional |
| 155 |
Convergence threshold. EM will stop if the gain in log-likelihood |
| 156 |
is below this value. |
| 157 |
verbose : bool, optional |
| 158 |
Whether per-iteration convergence reports are printed to |
| 159 |
:data:`sys.stderr`. Convergence can also be diagnosed using the |
| 160 |
:attr:`monitor_` attribute. |
| 161 |
params, init_params : string, optional |
| 162 |
The parameters that get updated during (``params``) or initialized |
| 163 |
before (``init_params``) the training. Can contain any combination |
| 164 |
of 's' for startprob, 't' for transmat, and other characters for |
| 165 |
subclass-specific emission parameters. Defaults to all parameters. |
| 166 |
implementation: string, optional |
| 167 |
Determines if the forward-backward algorithm is implemented with |
| 168 |
logarithms ("log"), or using scaling ("scaling"). The default is |
| 169 |
to use logarithms for backwards compatability. However, the |
| 170 |
scaling implementation is generally faster. |
| 171 |
""" |
| 172 |
|
| 173 |
self.n_components = n_components |
| 174 |
self.params = params |
| 175 |
self.init_params = init_params |
| 176 |
self.algorithm = algorithm |
| 177 |
self.n_iter = n_iter |
| 178 |
self.tol = tol |
| 179 |
self.verbose = verbose |
| 180 |
self.implementation = implementation |
| 181 |
self.random_state = random_state |
| 182 |
|
| 183 |
def score_samples(self, X, lengths=None): |
| 184 |
""" |
| 185 |
Compute the log probability under the model and compute posteriors. |
| 186 |
|
| 187 |
Parameters |
| 188 |
---------- |
| 189 |
X : array-like, shape (n_samples, n_features) |
| 190 |
Feature matrix of individual samples. |
| 191 |
lengths : array-like of integers, shape (n_sequences, ), optional |
| 192 |
Lengths of the individual sequences in ``X``. The sum of |
| 193 |
these should be ``n_samples``. |
| 194 |
|
| 195 |
Returns |
| 196 |
------- |
| 197 |
log_prob : float |
| 198 |
Log likelihood of ``X``. |
| 199 |
posteriors : array, shape (n_samples, n_components) |
| 200 |
State-membership probabilities for each sample in ``X``. |
| 201 |
|
| 202 |
See Also |
| 203 |
-------- |
| 204 |
score : Compute the log probability under the model. |
| 205 |
decode : Find most likely state sequence corresponding to ``X``. |
| 206 |
""" |
| 207 |
return self._score(X, lengths, compute_posteriors=True) |
| 208 |
|
| 209 |
def score(self, X, lengths=None): |
| 210 |
""" |
| 211 |
Compute the log probability under the model. |
| 212 |
|
| 213 |
Parameters |
| 214 |
---------- |
| 215 |
X : array-like, shape (n_samples, n_features) |
| 216 |
Feature matrix of individual samples. |
| 217 |
lengths : array-like of integers, shape (n_sequences, ), optional |
| 218 |
Lengths of the individual sequences in ``X``. The sum of |
| 219 |
these should be ``n_samples``. |
| 220 |
|
| 221 |
Returns |
| 222 |
------- |
| 223 |
log_prob : float |
| 224 |
Log likelihood of ``X``. |
| 225 |
|
| 226 |
See Also |
| 227 |
-------- |
| 228 |
score_samples : Compute the log probability under the model and |
| 229 |
posteriors. |
| 230 |
decode : Find most likely state sequence corresponding to ``X``. |
| 231 |
""" |
| 232 |
return self._score(X, lengths, compute_posteriors=False)[0] |
| 233 |
|
| 234 |
def _score(self, X, lengths=None, *, compute_posteriors): |
| 235 |
""" |
| 236 |
Helper for `score` and `score_samples`. |
| 237 |
|
| 238 |
Compute the log probability under the model, as well as posteriors if |
| 239 |
*compute_posteriors* is True (otherwise, an empty array is returned |
| 240 |
for the latter). |
| 241 |
""" |
| 242 |
check_is_fitted(self, "startprob_") |
| 243 |
self._check() |
| 244 |
|
| 245 |
X = check_array(X) |
| 246 |
impl = { |
| 247 |
"scaling": self._score_scaling, |
| 248 |
"log": self._score_log, |
| 249 |
}[self.implementation] |
| 250 |
return impl( |
| 251 |
X=X, lengths=lengths, compute_posteriors=compute_posteriors) |
| 252 |
|
| 253 |
def _score_log(self, X, lengths=None, *, compute_posteriors): |
| 254 |
""" |
| 255 |
Compute the log probability under the model, as well as posteriors if |
| 256 |
*compute_posteriors* is True (otherwise, an empty array is returned |
| 257 |
for the latter). |
| 258 |
""" |
| 259 |
log_prob = 0 |
| 260 |
sub_posteriors = [np.empty((0, self.n_components))] |
| 261 |
for sub_X in _utils.split_X_lengths(X, lengths): |
| 262 |
log_frameprob = self._compute_log_likelihood(sub_X) |
| 263 |
log_probij, fwdlattice = _hmmc.forward_log( |
| 264 |
self.startprob_, self.transmat_, log_frameprob) |
| 265 |
log_prob += log_probij |
| 266 |
if compute_posteriors: |
| 267 |
bwdlattice = _hmmc.backward_log( |
| 268 |
self.startprob_, self.transmat_, log_frameprob) |
| 269 |
sub_posteriors.append( |
| 270 |
self._compute_posteriors_log(fwdlattice, bwdlattice)) |
| 271 |
return log_prob, np.concatenate(sub_posteriors) |
| 272 |
|
| 273 |
def _score_scaling(self, X, lengths=None, *, compute_posteriors): |
| 274 |
log_prob = 0 |
| 275 |
sub_posteriors = [np.empty((0, self.n_components))] |
| 276 |
for sub_X in _utils.split_X_lengths(X, lengths): |
| 277 |
frameprob = self._compute_likelihood(sub_X) |
| 278 |
log_probij, fwdlattice, scaling_factors = _hmmc.forward_scaling( |
| 279 |
self.startprob_, self.transmat_, frameprob) |
| 280 |
log_prob += log_probij |
| 281 |
if compute_posteriors: |
| 282 |
bwdlattice = _hmmc.backward_scaling( |
| 283 |
self.startprob_, self.transmat_, |
| 284 |
frameprob, scaling_factors) |
| 285 |
sub_posteriors.append( |
| 286 |
self._compute_posteriors_scaling(fwdlattice, bwdlattice)) |
| 287 |
|
| 288 |
return log_prob, np.concatenate(sub_posteriors) |
| 289 |
|
| 290 |
def _decode_viterbi(self, X): |
| 291 |
log_frameprob = self._compute_log_likelihood(X) |
| 292 |
return _hmmc.viterbi(self.startprob_, self.transmat_, log_frameprob) |
| 293 |
|
| 294 |
def _decode_map(self, X): |
| 295 |
_, posteriors = self.score_samples(X) |
| 296 |
log_prob = np.max(posteriors, axis=1).sum() |
| 297 |
state_sequence = np.argmax(posteriors, axis=1) |
| 298 |
return log_prob, state_sequence |
| 299 |
|
| 300 |
def decode(self, X, lengths=None, algorithm=None): |
| 301 |
""" |
| 302 |
Find most likely state sequence corresponding to ``X``. |
| 303 |
|
| 304 |
Parameters |
| 305 |
---------- |
| 306 |
X : array-like, shape (n_samples, n_features) |
| 307 |
Feature matrix of individual samples. |
| 308 |
lengths : array-like of integers, shape (n_sequences, ), optional |
| 309 |
Lengths of the individual sequences in ``X``. The sum of |
| 310 |
these should be ``n_samples``. |
| 311 |
algorithm : {"viterbi", "map"}, optional |
| 312 |
Decoder algorithm. |
| 313 |
|
| 314 |
- "viterbi": finds the most likely sequence of states, given all |
| 315 |
emissions. |
| 316 |
- "map" (also known as smoothing or forward-backward): finds the |
| 317 |
sequence of the individual most-likely states, given all |
| 318 |
emissions. |
| 319 |
If not given, :attr:`decoder` is used. |
| 320 |
|
| 321 |
Returns |
| 322 |
------- |
| 323 |
log_prob : float |
| 324 |
Log probability of the produced state sequence. |
| 325 |
state_sequence : array, shape (n_samples, ) |
| 326 |
Labels for each sample from ``X`` obtained via a given |
| 327 |
decoder ``algorithm``. |
| 328 |
|
| 329 |
See Also |
| 330 |
-------- |
| 331 |
score_samples : Compute the log probability under the model and |
| 332 |
posteriors. |
| 333 |
score : Compute the log probability under the model. |
| 334 |
""" |
| 335 |
check_is_fitted(self, "startprob_") |
| 336 |
self._check() |
| 337 |
|
| 338 |
algorithm = algorithm or self.algorithm |
| 339 |
if algorithm not in DECODER_ALGORITHMS: |
| 340 |
raise ValueError(f"Unknown decoder {algorithm!r}") |
| 341 |
|
| 342 |
decoder = { |
| 343 |
"viterbi": self._decode_viterbi, |
| 344 |
"map": self._decode_map |
| 345 |
}[algorithm] |
| 346 |
|
| 347 |
X = check_array(X) |
| 348 |
log_prob = 0 |
| 349 |
sub_state_sequences = [] |
| 350 |
for sub_X in _utils.split_X_lengths(X, lengths): |
| 351 |
|
| 352 |
sub_log_prob, sub_state_sequence = decoder(sub_X) |
| 353 |
log_prob += sub_log_prob |
| 354 |
sub_state_sequences.append(sub_state_sequence) |
| 355 |
|
| 356 |
return log_prob, np.concatenate(sub_state_sequences) |
| 357 |
|
| 358 |
def predict(self, X, lengths=None): |
| 359 |
""" |
| 360 |
Find most likely state sequence corresponding to ``X``. |
| 361 |
|
| 362 |
Parameters |
| 363 |
---------- |
| 364 |
X : array-like, shape (n_samples, n_features) |
| 365 |
Feature matrix of individual samples. |
| 366 |
lengths : array-like of integers, shape (n_sequences, ), optional |
| 367 |
Lengths of the individual sequences in ``X``. The sum of |
| 368 |
these should be ``n_samples``. |
| 369 |
|
| 370 |
Returns |
| 371 |
------- |
| 372 |
state_sequence : array, shape (n_samples, ) |
| 373 |
Labels for each sample from ``X``. |
| 374 |
""" |
| 375 |
_, state_sequence = self.decode(X, lengths) |
| 376 |
return state_sequence |
| 377 |
|
| 378 |
def predict_proba(self, X, lengths=None): |
| 379 |
""" |
| 380 |
Compute the posterior probability for each state in the model. |
| 381 |
|
| 382 |
Parameters |
| 383 |
---------- |
| 384 |
X : array-like, shape (n_samples, n_features) |
| 385 |
Feature matrix of individual samples. |
| 386 |
lengths : array-like of integers, shape (n_sequences, ), optional |
| 387 |
Lengths of the individual sequences in ``X``. The sum of |
| 388 |
these should be ``n_samples``. |
| 389 |
|
| 390 |
Returns |
| 391 |
------- |
| 392 |
posteriors : array, shape (n_samples, n_components) |
| 393 |
State-membership probabilities for each sample from ``X``. |
| 394 |
""" |
| 395 |
_, posteriors = self.score_samples(X, lengths) |
| 396 |
return posteriors |
| 397 |
|
| 398 |
def sample(self, n_samples=1, random_state=None, currstate=None): |
| 399 |
""" |
| 400 |
Generate random samples from the model. |
| 401 |
|
| 402 |
Parameters |
| 403 |
---------- |
| 404 |
n_samples : int |
| 405 |
Number of samples to generate. |
| 406 |
random_state : RandomState or an int seed |
| 407 |
A random number generator instance. If ``None``, the object's |
| 408 |
``random_state`` is used. |
| 409 |
currstate : int |
| 410 |
Current state, as the initial state of the samples. |
| 411 |
|
| 412 |
Returns |
| 413 |
------- |
| 414 |
X : array, shape (n_samples, n_features) |
| 415 |
Feature matrix. |
| 416 |
state_sequence : array, shape (n_samples, ) |
| 417 |
State sequence produced by the model. |
| 418 |
|
| 419 |
Examples |
| 420 |
-------- |
| 421 |
:: |
| 422 |
|
| 423 |
# generate samples continuously |
| 424 |
_, Z = model.sample(n_samples=10) |
| 425 |
X, Z = model.sample(n_samples=10, currstate=Z[-1]) |
| 426 |
""" |
| 427 |
check_is_fitted(self, "startprob_") |
| 428 |
self._check() |
| 429 |
|
| 430 |
if random_state is None: |
| 431 |
random_state = self.random_state |
| 432 |
random_state = check_random_state(random_state) |
| 433 |
|
| 434 |
transmat_cdf = np.cumsum(self.transmat_, axis=1) |
| 435 |
|
| 436 |
if currstate is None: |
| 437 |
startprob_cdf = np.cumsum(self.startprob_) |
| 438 |
currstate = (startprob_cdf > random_state.rand()).argmax() |
| 439 |
|
| 440 |
state_sequence = [currstate] |
| 441 |
X = [self._generate_sample_from_state( |
| 442 |
currstate, random_state=random_state)] |
| 443 |
|
| 444 |
for t in range(n_samples - 1): |
| 445 |
currstate = ( |
| 446 |
(transmat_cdf[currstate] > random_state.rand()).argmax()) |
| 447 |
state_sequence.append(currstate) |
| 448 |
X.append(self._generate_sample_from_state( |
| 449 |
currstate, random_state=random_state)) |
| 450 |
|
| 451 |
return np.atleast_2d(X), np.array(state_sequence, dtype=int) |
| 452 |
|
| 453 |
def fit(self, X, lengths=None): |
| 454 |
""" |
| 455 |
Estimate model parameters. |
| 456 |
|
| 457 |
An initialization step is performed before entering the |
| 458 |
EM algorithm. If you want to avoid this step for a subset of |
| 459 |
the parameters, pass proper ``init_params`` keyword argument |
| 460 |
to estimator's constructor. |
| 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 |
Returns |
| 471 |
------- |
| 472 |
self : object |
| 473 |
Returns self. |
| 474 |
""" |
| 475 |
X = check_array(X) |
| 476 |
|
| 477 |
if lengths is None: |
| 478 |
lengths = np.asarray([X.shape[0]]) |
| 479 |
|
| 480 |
self._init(X, lengths) |
| 481 |
self._check() |
| 482 |
self.monitor_._reset() |
| 483 |
|
| 484 |
for iter in range(self.n_iter): |
| 485 |
stats, curr_logprob = self._do_estep(X, lengths) |
| 486 |
|
| 487 |
|
| 488 |
lower_bound = self._compute_lower_bound(curr_logprob) |
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
self._do_mstep(stats) |
| 493 |
self.monitor_.report(lower_bound) |
| 494 |
if self.monitor_.converged: |
| 495 |
break |
| 496 |
|
| 497 |
if (self.transmat_.sum(axis=1) == 0).any(): |
| 498 |
_log.warning("Some rows of transmat_ have zero sum because no " |
| 499 |
"transition from the state was ever observed.") |
| 500 |
return self |
| 501 |
|
| 502 |
def _fit_scaling(self, X): |
| 503 |
raise NotImplementedError("Must be overridden in subclass") |
| 504 |
|
| 505 |
def _fit_log(self, X): |
| 506 |
raise NotImplementedError("Must be overridden in subclass") |
| 507 |
|
| 508 |
def _compute_posteriors_scaling(self, fwdlattice, bwdlattice): |
| 509 |
posteriors = fwdlattice * bwdlattice |
| 510 |
normalize(posteriors, axis=1) |
| 511 |
return posteriors |
| 512 |
|
| 513 |
def _compute_posteriors_log(self, fwdlattice, bwdlattice): |
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
log_gamma = fwdlattice + bwdlattice |
| 519 |
log_normalize(log_gamma, axis=1) |
| 520 |
with np.errstate(under="ignore"): |
| 521 |
return np.exp(log_gamma) |
| 522 |
|
| 523 |
def _needs_init(self, code, name): |
| 524 |
if code in self.init_params: |
| 525 |
if hasattr(self, name): |
| 526 |
_log.warning( |
| 527 |
"Even though the %r attribute is set, it will be " |
| 528 |
"overwritten during initialization because 'init_params' " |
| 529 |
"contains %r", name, code) |
| 530 |
return True |
| 531 |
if not hasattr(self, name): |
| 532 |
return True |
| 533 |
return False |
| 534 |
|
| 535 |
def _check_and_set_n_features(self, X): |
| 536 |
_, n_features = X.shape |
| 537 |
if hasattr(self, "n_features"): |
| 538 |
if self.n_features != n_features: |
| 539 |
raise ValueError( |
| 540 |
f"Unexpected number of dimensions, got {n_features} but " |
| 541 |
f"expected {self.n_features}") |
| 542 |
else: |
| 543 |
self.n_features = n_features |
| 544 |
|
| 545 |
def _get_n_fit_scalars_per_param(self): |
| 546 |
""" |
| 547 |
Return a mapping of fittable parameter names (as in ``self.params``) |
| 548 |
to the number of corresponding scalar parameters that will actually be |
| 549 |
fitted. |
| 550 |
|
| 551 |
This is used to detect whether the user did not pass enough data points |
| 552 |
for a non-degenerate fit. |
| 553 |
""" |
| 554 |
raise NotImplementedError("Must be overridden in subclass") |
| 555 |
|
| 556 |
def _check_sum_1(self, name): |
| 557 |
"""Check that an array describes one or more distributions.""" |
| 558 |
s = getattr(self, name).sum(axis=-1) |
| 559 |
if not np.allclose(s, 1): |
| 560 |
raise ValueError( |
| 561 |
f"{name} must sum to 1 (got {s:.4f})" |
| 562 |
if s.ndim == 0 |
| 563 |
else f"{name} rows must sum to 1 (got row sums of {s})" |
| 564 |
if s.ndim == 1 |
| 565 |
else "Expected 1D or 2D array") |
| 566 |
|
| 567 |
def _check(self): |
| 568 |
""" |
| 569 |
Validate model parameters prior to fitting. |
| 570 |
|
| 571 |
Raises |
| 572 |
------ |
| 573 |
ValueError |
| 574 |
If any of the parameters are invalid, e.g. if :attr:`startprob_` |
| 575 |
don't sum to 1. |
| 576 |
""" |
| 577 |
raise NotImplementedError("Must be overridden in subclass") |
| 578 |
|
| 579 |
def _compute_likelihood(self, X): |
| 580 |
""" |
| 581 |
Compute per-component probability under the model. |
| 582 |
|
| 583 |
Parameters |
| 584 |
---------- |
| 585 |
X : array-like, shape (n_samples, n_features) |
| 586 |
Feature matrix of individual samples. |
| 587 |
|
| 588 |
Returns |
| 589 |
------- |
| 590 |
log_prob : array, shape (n_samples, n_components) |
| 591 |
Log probability of each sample in ``X`` for each of the |
| 592 |
model states. |
| 593 |
""" |
| 594 |
if (self._compute_log_likelihood |
| 595 |
!= __class__._compute_log_likelihood.__get__(self)): |
| 596 |
|
| 597 |
with np.errstate(under="ignore"): |
| 598 |
return np.exp(self._compute_log_likelihood(X)) |
| 599 |
else: |
| 600 |
raise NotImplementedError("Must be overridden in subclass") |
| 601 |
|
| 602 |
def _compute_log_likelihood(self, X): |
| 603 |
""" |
| 604 |
Compute per-component emission log probability under the model. |
| 605 |
|
| 606 |
Parameters |
| 607 |
---------- |
| 608 |
X : array-like, shape (n_samples, n_features) |
| 609 |
Feature matrix of individual samples. |
| 610 |
|
| 611 |
Returns |
| 612 |
------- |
| 613 |
log_prob : array, shape (n_samples, n_components) |
| 614 |
Emission log probability of each sample in ``X`` for each of the |
| 615 |
model states, i.e., ``log(p(X|state))``. |
| 616 |
""" |
| 617 |
if (self._compute_likelihood |
| 618 |
!= __class__._compute_likelihood.__get__(self)): |
| 619 |
|
| 620 |
likelihood = self._compute_likelihood(X) |
| 621 |
with np.errstate(divide="ignore"): |
| 622 |
return np.log(likelihood) |
| 623 |
else: |
| 624 |
raise NotImplementedError("Must be overridden in subclass") |
| 625 |
|
| 626 |
def _generate_sample_from_state(self, state, random_state): |
| 627 |
""" |
| 628 |
Generate a random sample from a given component. |
| 629 |
|
| 630 |
Parameters |
| 631 |
---------- |
| 632 |
state : int |
| 633 |
Index of the component to condition on. |
| 634 |
random_state: RandomState |
| 635 |
A random number generator instance. (`sample` is the only caller |
| 636 |
for this method and already normalizes *random_state*.) |
| 637 |
|
| 638 |
Returns |
| 639 |
------- |
| 640 |
X : array, shape (n_features, ) |
| 641 |
A random sample from the emission distribution corresponding |
| 642 |
to a given component. |
| 643 |
""" |
| 644 |
return () |
| 645 |
|
| 646 |
def _initialize_sufficient_statistics(self): |
| 647 |
""" |
| 648 |
Initialize sufficient statistics required for M-step. |
| 649 |
|
| 650 |
The method is *pure*, meaning that it doesn't change the state of |
| 651 |
the instance. For extensibility computed statistics are stored |
| 652 |
in a dictionary. |
| 653 |
|
| 654 |
Returns |
| 655 |
------- |
| 656 |
nobs : int |
| 657 |
Number of samples in the data. |
| 658 |
start : array, shape (n_components, ) |
| 659 |
An array where the i-th element corresponds to the posterior |
| 660 |
probability of the first sample being generated by the i-th state. |
| 661 |
trans : array, shape (n_components, n_components) |
| 662 |
An array where the (i, j)-th element corresponds to the posterior |
| 663 |
probability of transitioning between the i-th to j-th states. |
| 664 |
""" |
| 665 |
stats = {'nobs': 0, |
| 666 |
'start': np.zeros(self.n_components), |
| 667 |
'trans': np.zeros((self.n_components, self.n_components))} |
| 668 |
return stats |
| 669 |
|
| 670 |
def _accumulate_sufficient_statistics( |
| 671 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 672 |
""" |
| 673 |
Update sufficient statistics from a given sample. |
| 674 |
|
| 675 |
Parameters |
| 676 |
---------- |
| 677 |
stats : dict |
| 678 |
Sufficient statistics as returned by |
| 679 |
:meth:`~.BaseHMM._initialize_sufficient_statistics`. |
| 680 |
|
| 681 |
X : array, shape (n_samples, n_features) |
| 682 |
Sample sequence. |
| 683 |
|
| 684 |
lattice : array, shape (n_samples, n_components) |
| 685 |
Probabilities OR Log Probabilities of each sample |
| 686 |
under each of the model states. Depends on the choice |
| 687 |
of implementation of the Forward-Backward algorithm |
| 688 |
|
| 689 |
posteriors : array, shape (n_samples, n_components) |
| 690 |
Posterior probabilities of each sample being generated by each |
| 691 |
of the model states. |
| 692 |
|
| 693 |
fwdlattice, bwdlattice : array, shape (n_samples, n_components) |
| 694 |
forward and backward probabilities. |
| 695 |
""" |
| 696 |
|
| 697 |
impl = { |
| 698 |
"scaling": self._accumulate_sufficient_statistics_scaling, |
| 699 |
"log": self._accumulate_sufficient_statistics_log, |
| 700 |
}[self.implementation] |
| 701 |
|
| 702 |
return impl(stats=stats, X=X, lattice=lattice, posteriors=posteriors, |
| 703 |
fwdlattice=fwdlattice, bwdlattice=bwdlattice) |
| 704 |
|
| 705 |
def _accumulate_sufficient_statistics_scaling( |
| 706 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 707 |
""" |
| 708 |
Implementation of `_accumulate_sufficient_statistics` |
| 709 |
for ``implementation = "log"``. |
| 710 |
""" |
| 711 |
stats['nobs'] += 1 |
| 712 |
if 's' in self.params: |
| 713 |
stats['start'] += posteriors[0] |
| 714 |
if 't' in self.params: |
| 715 |
n_samples, n_components = lattice.shape |
| 716 |
|
| 717 |
|
| 718 |
if n_samples <= 1: |
| 719 |
return |
| 720 |
xi_sum = _hmmc.compute_scaling_xi_sum( |
| 721 |
fwdlattice, self.transmat_, bwdlattice, lattice) |
| 722 |
stats['trans'] += xi_sum |
| 723 |
|
| 724 |
def _accumulate_sufficient_statistics_log( |
| 725 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 726 |
""" |
| 727 |
Implementation of `_accumulate_sufficient_statistics` |
| 728 |
for ``implementation = "log"``. |
| 729 |
""" |
| 730 |
stats['nobs'] += 1 |
| 731 |
if 's' in self.params: |
| 732 |
stats['start'] += posteriors[0] |
| 733 |
if 't' in self.params: |
| 734 |
n_samples, n_components = lattice.shape |
| 735 |
|
| 736 |
|
| 737 |
if n_samples <= 1: |
| 738 |
return |
| 739 |
log_xi_sum = _hmmc.compute_log_xi_sum( |
| 740 |
fwdlattice, self.transmat_, bwdlattice, lattice) |
| 741 |
with np.errstate(under="ignore"): |
| 742 |
stats['trans'] += np.exp(log_xi_sum) |
| 743 |
|
| 744 |
def _do_mstep(self, stats): |
| 745 |
""" |
| 746 |
Perform the M-step of EM algorithm. |
| 747 |
|
| 748 |
Parameters |
| 749 |
---------- |
| 750 |
stats : dict |
| 751 |
Sufficient statistics updated from all available samples. |
| 752 |
""" |
| 753 |
|
| 754 |
def _do_estep(self, X, lengths): |
| 755 |
impl = { |
| 756 |
"scaling": self._fit_scaling, |
| 757 |
"log": self._fit_log, |
| 758 |
}[self.implementation] |
| 759 |
|
| 760 |
stats = self._initialize_sufficient_statistics() |
| 761 |
self._estep_begin() |
| 762 |
curr_logprob = 0 |
| 763 |
for sub_X in _utils.split_X_lengths(X, lengths): |
| 764 |
lattice, logprob, posteriors, fwdlattice, bwdlattice = impl(sub_X) |
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
self._accumulate_sufficient_statistics( |
| 769 |
stats, sub_X, lattice, posteriors, fwdlattice, |
| 770 |
bwdlattice) |
| 771 |
curr_logprob += logprob |
| 772 |
return stats, curr_logprob |
| 773 |
|
| 774 |
def _estep_begin(self): |
| 775 |
pass |
| 776 |
|
| 777 |
def _compute_lower_bound(self, curr_logprob): |
| 778 |
raise NotImplementedError("Must be overridden in subclass") |
| 779 |
|
| 780 |
|
| 781 |
class BaseHMM(_AbstractHMM): |
| 782 |
""" |
| 783 |
Base class for Hidden Markov Models learned from Expectation-Maximization. |
| 784 |
|
| 785 |
This class allows for easy evaluation of, sampling from, and maximum a |
| 786 |
posteriori estimation of the parameters of a HMM. |
| 787 |
|
| 788 |
Attributes |
| 789 |
---------- |
| 790 |
monitor_ : ConvergenceMonitor |
| 791 |
Monitor object used to check the convergence of EM. |
| 792 |
startprob_ : array, shape (n_components, ) |
| 793 |
Initial state occupation distribution. |
| 794 |
transmat_ : array, shape (n_components, n_components) |
| 795 |
Matrix of transition probabilities between states. |
| 796 |
|
| 797 |
Notes |
| 798 |
----- |
| 799 |
Normally, one should use a subclass of `.BaseHMM`, with its specialization |
| 800 |
towards a given emission model. In rare cases, the base class can also be |
| 801 |
useful in itself, if one simply wants to generate a sequence of states |
| 802 |
using `.BaseHMM.sample`. In that case, the feature matrix will have zero |
| 803 |
features. |
| 804 |
""" |
| 805 |
|
| 806 |
def __init__(self, n_components=1, |
| 807 |
startprob_prior=1.0, transmat_prior=1.0, |
| 808 |
algorithm="viterbi", random_state=None, |
| 809 |
n_iter=10, tol=1e-2, verbose=False, |
| 810 |
params=string.ascii_letters, |
| 811 |
init_params=string.ascii_letters, |
| 812 |
implementation="log"): |
| 813 |
""" |
| 814 |
Parameters |
| 815 |
---------- |
| 816 |
n_components : int |
| 817 |
Number of states in the model. |
| 818 |
startprob_prior : array, shape (n_components, ), optional |
| 819 |
Parameters of the Dirichlet prior distribution for |
| 820 |
:attr:`startprob_`. |
| 821 |
transmat_prior : array, shape (n_components, n_components), optional |
| 822 |
Parameters of the Dirichlet prior distribution for each row |
| 823 |
of the transition probabilities :attr:`transmat_`. |
| 824 |
algorithm : {"viterbi", "map"}, optional |
| 825 |
Decoder algorithm. |
| 826 |
|
| 827 |
- "viterbi": finds the most likely sequence of states, given all |
| 828 |
emissions. |
| 829 |
- "map" (also known as smoothing or forward-backward): finds the |
| 830 |
sequence of the individual most-likely states, given all |
| 831 |
emissions. |
| 832 |
random_state: RandomState or an int seed, optional |
| 833 |
A random number generator instance. |
| 834 |
n_iter : int, optional |
| 835 |
Maximum number of iterations to perform. |
| 836 |
tol : float, optional |
| 837 |
Convergence threshold. EM will stop if the gain in log-likelihood |
| 838 |
is below this value. |
| 839 |
verbose : bool, optional |
| 840 |
Whether per-iteration convergence reports are printed to |
| 841 |
:data:`sys.stderr`. Convergence can also be diagnosed using the |
| 842 |
:attr:`monitor_` attribute. |
| 843 |
params, init_params : string, optional |
| 844 |
The parameters that get updated during (``params``) or initialized |
| 845 |
before (``init_params``) the training. Can contain any combination |
| 846 |
of 's' for startprob, 't' for transmat, and other characters for |
| 847 |
subclass-specific emission parameters. Defaults to all parameters. |
| 848 |
implementation: string, optional |
| 849 |
Determines if the forward-backward algorithm is implemented with |
| 850 |
logarithms ("log"), or using scaling ("scaling"). The default is |
| 851 |
to use logarithms for backwards compatability. However, the |
| 852 |
scaling implementation is generally faster. |
| 853 |
""" |
| 854 |
super().__init__( |
| 855 |
n_components=n_components, algorithm=algorithm, |
| 856 |
random_state=random_state, n_iter=n_iter, tol=tol, |
| 857 |
verbose=verbose, params=params, init_params=init_params, |
| 858 |
implementation=implementation) |
| 859 |
self.startprob_prior = startprob_prior |
| 860 |
self.transmat_prior = transmat_prior |
| 861 |
self.monitor_ = ConvergenceMonitor(self.tol, self.n_iter, self.verbose) |
| 862 |
|
| 863 |
def get_stationary_distribution(self): |
| 864 |
"""Compute the stationary distribution of states.""" |
| 865 |
|
| 866 |
|
| 867 |
|
| 868 |
check_is_fitted(self, "transmat_") |
| 869 |
eigvals, eigvecs = linalg.eig(self.transmat_.T) |
| 870 |
eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)]) |
| 871 |
return eigvec / eigvec.sum() |
| 872 |
|
| 873 |
def _fit_scaling(self, X): |
| 874 |
frameprob = self._compute_likelihood(X) |
| 875 |
log_prob, fwdlattice, scaling_factors = _hmmc.forward_scaling( |
| 876 |
self.startprob_, self.transmat_, frameprob) |
| 877 |
bwdlattice = _hmmc.backward_scaling( |
| 878 |
self.startprob_, self.transmat_, frameprob, scaling_factors) |
| 879 |
posteriors = self._compute_posteriors_scaling(fwdlattice, bwdlattice) |
| 880 |
return frameprob, log_prob, posteriors, fwdlattice, bwdlattice |
| 881 |
|
| 882 |
def _fit_log(self, X): |
| 883 |
log_frameprob = self._compute_log_likelihood(X) |
| 884 |
log_prob, fwdlattice = _hmmc.forward_log( |
| 885 |
self.startprob_, self.transmat_, log_frameprob) |
| 886 |
bwdlattice = _hmmc.backward_log( |
| 887 |
self.startprob_, self.transmat_, log_frameprob) |
| 888 |
posteriors = self._compute_posteriors_log(fwdlattice, bwdlattice) |
| 889 |
return log_frameprob, log_prob, posteriors, fwdlattice, bwdlattice |
| 890 |
|
| 891 |
def _do_mstep(self, stats): |
| 892 |
""" |
| 893 |
Perform the M-step of EM algorithm. |
| 894 |
|
| 895 |
Parameters |
| 896 |
---------- |
| 897 |
stats : dict |
| 898 |
Sufficient statistics updated from all available samples. |
| 899 |
""" |
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
if 's' in self.params: |
| 907 |
startprob_ = np.maximum(self.startprob_prior - 1 + stats['start'], |
| 908 |
0) |
| 909 |
self.startprob_ = np.where(self.startprob_ == 0, 0, startprob_) |
| 910 |
normalize(self.startprob_) |
| 911 |
if 't' in self.params: |
| 912 |
transmat_ = np.maximum(self.transmat_prior - 1 + stats['trans'], 0) |
| 913 |
self.transmat_ = np.where(self.transmat_ == 0, 0, transmat_) |
| 914 |
normalize(self.transmat_, axis=1) |
| 915 |
|
| 916 |
def _compute_lower_bound(self, curr_logprob): |
| 917 |
return curr_logprob |
| 918 |
|
| 919 |
def _init(self, X, lengths=None): |
| 920 |
""" |
| 921 |
Initialize model parameters prior to fitting. |
| 922 |
|
| 923 |
Parameters |
| 924 |
---------- |
| 925 |
X : array-like, shape (n_samples, n_features) |
| 926 |
Feature matrix of individual samples. |
| 927 |
""" |
| 928 |
self._check_and_set_n_features(X) |
| 929 |
init = 1. / self.n_components |
| 930 |
random_state = check_random_state(self.random_state) |
| 931 |
if self._needs_init("s", "startprob_"): |
| 932 |
self.startprob_ = random_state.dirichlet( |
| 933 |
np.full(self.n_components, init)) |
| 934 |
if self._needs_init("t", "transmat_"): |
| 935 |
self.transmat_ = random_state.dirichlet( |
| 936 |
np.full(self.n_components, init), size=self.n_components) |
| 937 |
n_fit_scalars_per_param = self._get_n_fit_scalars_per_param() |
| 938 |
if n_fit_scalars_per_param is not None: |
| 939 |
n_fit_scalars = sum( |
| 940 |
n_fit_scalars_per_param[p] for p in self.params) |
| 941 |
if X.size < n_fit_scalars: |
| 942 |
_log.warning( |
| 943 |
"Fitting a model with %d free scalar parameters with only " |
| 944 |
"%d data points will result in a degenerate solution.", |
| 945 |
n_fit_scalars, X.size) |
| 946 |
|
| 947 |
def _check_sum_1(self, name): |
| 948 |
"""Check that an array describes one or more distributions.""" |
| 949 |
s = getattr(self, name).sum(axis=-1) |
| 950 |
if not np.allclose(s, 1): |
| 951 |
raise ValueError( |
| 952 |
f"{name} must sum to 1 (got {s:.4f})" |
| 953 |
if s.ndim == 0 |
| 954 |
else f"{name} rows must sum to 1 (got row sums of {s})" |
| 955 |
if s.ndim == 1 |
| 956 |
else "Expected 1D or 2D array") |
| 957 |
|
| 958 |
def _check(self): |
| 959 |
""" |
| 960 |
Validate model parameters prior to fitting. |
| 961 |
|
| 962 |
Raises |
| 963 |
------ |
| 964 |
ValueError |
| 965 |
If any of the parameters are invalid, e.g. if :attr:`startprob_` |
| 966 |
don't sum to 1. |
| 967 |
""" |
| 968 |
self.startprob_ = np.asarray(self.startprob_) |
| 969 |
if len(self.startprob_) != self.n_components: |
| 970 |
raise ValueError("startprob_ must have length n_components") |
| 971 |
self._check_sum_1("startprob_") |
| 972 |
|
| 973 |
self.transmat_ = np.asarray(self.transmat_) |
| 974 |
if self.transmat_.shape != (self.n_components, self.n_components): |
| 975 |
raise ValueError( |
| 976 |
"transmat_ must have shape (n_components, n_components)") |
| 977 |
self._check_sum_1("transmat_") |
| 978 |
|
| 979 |
def aic(self, X, lengths=None): |
| 980 |
""" |
| 981 |
Akaike information criterion for the current model on the input X. |
| 982 |
|
| 983 |
AIC = -2*logLike + 2 * num_free_params |
| 984 |
|
| 985 |
https://en.wikipedia.org/wiki/Akaike_information_criterion |
| 986 |
|
| 987 |
Parameters |
| 988 |
---------- |
| 989 |
X : array of shape (n_samples, n_dimensions) |
| 990 |
The input samples. |
| 991 |
lengths : array-like of integers, shape (n_sequences, ) |
| 992 |
Lengths of the individual sequences in ``X``. The sum of |
| 993 |
these should be ``n_samples``. |
| 994 |
|
| 995 |
Returns |
| 996 |
------- |
| 997 |
aic : float |
| 998 |
The lower the better. |
| 999 |
""" |
| 1000 |
n_params = sum(self._get_n_fit_scalars_per_param().values()) |
| 1001 |
return -2 * self.score(X, lengths=lengths) + 2 * n_params |
| 1002 |
|
| 1003 |
def bic(self, X, lengths=None): |
| 1004 |
""" |
| 1005 |
Bayesian information criterion for the current model on the input X. |
| 1006 |
|
| 1007 |
BIC = -2*logLike + num_free_params * log(num_of_data) |
| 1008 |
|
| 1009 |
https://en.wikipedia.org/wiki/Bayesian_information_criterion |
| 1010 |
|
| 1011 |
Parameters |
| 1012 |
---------- |
| 1013 |
X : array of shape (n_samples, n_dimensions) |
| 1014 |
The input samples. |
| 1015 |
lengths : array-like of integers, shape (n_sequences, ) |
| 1016 |
Lengths of the individual sequences in ``X``. The sum of |
| 1017 |
these should be ``n_samples``. |
| 1018 |
|
| 1019 |
Returns |
| 1020 |
------- |
| 1021 |
bic : float |
| 1022 |
The lower the better. |
| 1023 |
""" |
| 1024 |
n_params = sum(self._get_n_fit_scalars_per_param().values()) |
| 1025 |
return -2 * self.score(X, lengths=lengths) + n_params * np.log(len(X)) |
| 1026 |
|
| 1027 |
|
| 1028 |
_BaseHMM = BaseHMM |
| 1029 |
|
| 1030 |
|
| 1031 |
class VariationalBaseHMM(_AbstractHMM): |
| 1032 |
|
| 1033 |
def __init__(self, n_components=1, |
| 1034 |
startprob_prior=None, transmat_prior=None, |
| 1035 |
algorithm="viterbi", random_state=None, |
| 1036 |
n_iter=100, tol=1e-6, verbose=False, |
| 1037 |
params="ste", init_params="ste", |
| 1038 |
implementation="log"): |
| 1039 |
super().__init__( |
| 1040 |
n_components=n_components, algorithm=algorithm, |
| 1041 |
random_state=random_state, n_iter=n_iter, tol=tol, |
| 1042 |
verbose=verbose, params=params, init_params=init_params, |
| 1043 |
implementation=implementation) |
| 1044 |
|
| 1045 |
self.startprob_prior = startprob_prior |
| 1046 |
self.transmat_prior = transmat_prior |
| 1047 |
self.monitor_ = ConvergenceMonitor( |
| 1048 |
self.tol, self.n_iter, self.verbose) |
| 1049 |
|
| 1050 |
def _init(self, X, lengths=None): |
| 1051 |
""" |
| 1052 |
Initialize model parameters prior to fitting. |
| 1053 |
|
| 1054 |
Parameters |
| 1055 |
---------- |
| 1056 |
X : array-like, shape (n_samples, n_features) |
| 1057 |
Feature matrix of individual samples. |
| 1058 |
lengths : array-like of integers, shape (n_sequences, ) |
| 1059 |
Lengths of the individual sequences in ``X``. The sum of |
| 1060 |
these should be ``n_samples``. |
| 1061 |
""" |
| 1062 |
self._check_and_set_n_features(X) |
| 1063 |
nc = self.n_components |
| 1064 |
uniform_prior = 1 / nc |
| 1065 |
random_state = check_random_state(self.random_state) |
| 1066 |
if (self._needs_init("s", "startprob_posterior_") |
| 1067 |
or self._needs_init("s", "startprob_prior_")): |
| 1068 |
if self.startprob_prior is None: |
| 1069 |
startprob_init = uniform_prior |
| 1070 |
else: |
| 1071 |
startprob_init = self.startprob_prior |
| 1072 |
|
| 1073 |
self.startprob_prior_ = np.full(nc, startprob_init) |
| 1074 |
self.startprob_posterior_ = random_state.dirichlet( |
| 1075 |
np.full(nc, uniform_prior)) * len(lengths) |
| 1076 |
|
| 1077 |
if (self._needs_init("t", "transmat_posterior_") |
| 1078 |
or self._needs_init("t", "transmat_prior_")): |
| 1079 |
if self.transmat_prior is None: |
| 1080 |
transmat_init = uniform_prior |
| 1081 |
else: |
| 1082 |
transmat_init = self.transmat_prior |
| 1083 |
self.transmat_prior_ = np.full( |
| 1084 |
(nc, nc), transmat_init) |
| 1085 |
self.transmat_posterior_ = random_state.dirichlet( |
| 1086 |
np.full(nc, uniform_prior), size=nc) |
| 1087 |
self.transmat_posterior_ *= sum(lengths) / nc |
| 1088 |
|
| 1089 |
n_fit_scalars_per_param = self._get_n_fit_scalars_per_param() |
| 1090 |
if n_fit_scalars_per_param is not None: |
| 1091 |
n_fit_scalars = sum( |
| 1092 |
n_fit_scalars_per_param[p] for p in self.params) |
| 1093 |
if X.size < n_fit_scalars: |
| 1094 |
_log.warning( |
| 1095 |
"Fitting a model with %d free scalar parameters with only " |
| 1096 |
"%d data points will result in a degenerate solution.", |
| 1097 |
n_fit_scalars, X.size) |
| 1098 |
|
| 1099 |
|
| 1100 |
|
| 1101 |
def _fit_scaling(self, X): |
| 1102 |
frameprob = self._compute_subnorm_likelihood(X) |
| 1103 |
logprob, fwdlattice, scaling_factors = _hmmc.forward_scaling( |
| 1104 |
self.startprob_subnorm_, self.transmat_subnorm_, frameprob) |
| 1105 |
|
| 1106 |
bwdlattice = _hmmc.backward_scaling( |
| 1107 |
self.startprob_subnorm_, self.transmat_subnorm_, |
| 1108 |
frameprob, scaling_factors) |
| 1109 |
posteriors = self._compute_posteriors_scaling(fwdlattice, bwdlattice) |
| 1110 |
return frameprob, logprob, posteriors, fwdlattice, bwdlattice |
| 1111 |
|
| 1112 |
def _fit_log(self, X): |
| 1113 |
framelogprob = self._compute_subnorm_log_likelihood(X) |
| 1114 |
logprob, fwdlattice = _hmmc.forward_log( |
| 1115 |
self.startprob_subnorm_, self.transmat_subnorm_, framelogprob) |
| 1116 |
bwdlattice = _hmmc.backward_log( |
| 1117 |
self.startprob_subnorm_, self.transmat_subnorm_, framelogprob) |
| 1118 |
posteriors = self._compute_posteriors_log(fwdlattice, bwdlattice) |
| 1119 |
return framelogprob, logprob, posteriors, fwdlattice, bwdlattice |
| 1120 |
|
| 1121 |
def _check(self): |
| 1122 |
""" |
| 1123 |
Validate model parameters prior to fitting. |
| 1124 |
|
| 1125 |
Raises |
| 1126 |
------ |
| 1127 |
ValueError |
| 1128 |
If any of the parameters are invalid, e.g. if :attr:`startprob_` |
| 1129 |
don't sum to 1. |
| 1130 |
""" |
| 1131 |
nc = self.n_components |
| 1132 |
|
| 1133 |
self.startprob_prior_ = np.asarray(self.startprob_prior_) |
| 1134 |
if len(self.startprob_prior_) != nc: |
| 1135 |
raise ValueError("startprob_prior_ must have length n_components") |
| 1136 |
self.startprob_posterior_ = np.asarray(self.startprob_posterior_) |
| 1137 |
if len(self.startprob_posterior_) != nc: |
| 1138 |
raise ValueError("startprob_posterior_ must have length " |
| 1139 |
"n_components") |
| 1140 |
|
| 1141 |
self.transmat_prior_ = np.asarray(self.transmat_prior_) |
| 1142 |
if self.transmat_prior_.shape != (nc, nc): |
| 1143 |
raise ValueError("transmat_prior_ must have shape " |
| 1144 |
"(n_components, n_components)") |
| 1145 |
self.transmat_posterior_ = np.asarray(self.transmat_posterior_) |
| 1146 |
if self.transmat_posterior_.shape != (nc, nc): |
| 1147 |
raise ValueError("transmat_posterior_ must have shape " |
| 1148 |
"(n_components, n_components)") |
| 1149 |
|
| 1150 |
def _compute_subnorm_likelihood(self, X): |
| 1151 |
if (self._compute_subnorm_log_likelihood != |
| 1152 |
__class__._compute_subnorm_log_likelihood.__get__(self)): |
| 1153 |
return np.exp(self._compute_subnorm_log_likelihood(X)) |
| 1154 |
else: |
| 1155 |
raise NotImplementedError("Must be overridden in subclass") |
| 1156 |
|
| 1157 |
def _compute_subnorm_log_likelihood(self, X): |
| 1158 |
if (self._compute_subnorm_likelihood != |
| 1159 |
__class__._compute_subnorm_likelihood.__get__(self)): |
| 1160 |
return np.log(self._compute_subnorm_likelihood(X)) |
| 1161 |
else: |
| 1162 |
raise NotImplementedError("Must be overridden in subclass") |
| 1163 |
|
| 1164 |
def _accumulate_sufficient_statistics_scaling( |
| 1165 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 1166 |
""" |
| 1167 |
Implementation of `_accumulate_sufficient_statistics` |
| 1168 |
for ``implementation = "log"``. |
| 1169 |
""" |
| 1170 |
stats['nobs'] += 1 |
| 1171 |
if 's' in self.params: |
| 1172 |
stats['start'] += posteriors[0] |
| 1173 |
if 't' in self.params: |
| 1174 |
n_samples, n_components = lattice.shape |
| 1175 |
|
| 1176 |
|
| 1177 |
if n_samples <= 1: |
| 1178 |
return |
| 1179 |
|
| 1180 |
xi_sum = _hmmc.compute_scaling_xi_sum(fwdlattice, |
| 1181 |
self.transmat_subnorm_, |
| 1182 |
bwdlattice, lattice) |
| 1183 |
stats['trans'] += xi_sum |
| 1184 |
|
| 1185 |
def _accumulate_sufficient_statistics_log( |
| 1186 |
self, stats, X, lattice, posteriors, fwdlattice, bwdlattice): |
| 1187 |
""" |
| 1188 |
Implementation of `_accumulate_sufficient_statistics` |
| 1189 |
for ``implementation = "log"``. |
| 1190 |
""" |
| 1191 |
stats['nobs'] += 1 |
| 1192 |
if 's' in self.params: |
| 1193 |
stats['start'] += posteriors[0] |
| 1194 |
if 't' in self.params: |
| 1195 |
n_samples, n_components = lattice.shape |
| 1196 |
|
| 1197 |
|
| 1198 |
if n_samples <= 1: |
| 1199 |
return |
| 1200 |
|
| 1201 |
log_xi_sum = _hmmc.compute_log_xi_sum( |
| 1202 |
fwdlattice, self.transmat_subnorm_, bwdlattice, |
| 1203 |
lattice) |
| 1204 |
with np.errstate(under="ignore"): |
| 1205 |
stats['trans'] += np.exp(log_xi_sum) |
| 1206 |
|
| 1207 |
def _estep_begin(self): |
| 1208 |
""" |
| 1209 |
Update the subnormalized model parameters. Called at the beginning of |
| 1210 |
each iteration of fit() |
| 1211 |
""" |
| 1212 |
startprob_log_subnorm = ( |
| 1213 |
special.digamma(self.startprob_posterior_) |
| 1214 |
- special.digamma(self.startprob_posterior_.sum())) |
| 1215 |
self.startprob_subnorm_ = np.exp(startprob_log_subnorm) |
| 1216 |
|
| 1217 |
transmat_log_subnorm = ( |
| 1218 |
special.digamma(self.transmat_posterior_) |
| 1219 |
- special.digamma(self.transmat_posterior_.sum(axis=1)[:, None])) |
| 1220 |
self.transmat_subnorm_ = np.exp(transmat_log_subnorm) |
| 1221 |
|
| 1222 |
def _do_mstep(self, stats): |
| 1223 |
""" |
| 1224 |
Perform the M-step of EM algorithm. |
| 1225 |
|
| 1226 |
Parameters |
| 1227 |
---------- |
| 1228 |
stats : dict |
| 1229 |
Sufficient statistics updated from all available samples. |
| 1230 |
""" |
| 1231 |
if 's' in self.params: |
| 1232 |
self.startprob_posterior_ = self.startprob_prior_ + stats['start'] |
| 1233 |
|
| 1234 |
self.startprob_ = (self.startprob_posterior_ |
| 1235 |
/ self.startprob_posterior_.sum()) |
| 1236 |
if 't' in self.params: |
| 1237 |
self.transmat_posterior_ = self.transmat_prior_ + stats['trans'] |
| 1238 |
|
| 1239 |
self.transmat_ = (self.transmat_posterior_ |
| 1240 |
/ self.transmat_posterior_.sum(axis=1)[:, None]) |
| 1241 |
|
| 1242 |
def _compute_lower_bound(self, curr_logprob): |
| 1243 |
""" |
| 1244 |
Compute the Variational Lower Bound of the model as currently |
| 1245 |
configured. |
| 1246 |
|
| 1247 |
Following the pattern elsewhere, derived implementations should call |
| 1248 |
this method to get the contribution of the current log_prob, |
| 1249 |
transmat, and startprob towards the lower bound |
| 1250 |
|
| 1251 |
Parameters |
| 1252 |
---------- |
| 1253 |
curr_logprob : float |
| 1254 |
The current log probability of the data as computed at |
| 1255 |
the subnormalized model parameters. |
| 1256 |
|
| 1257 |
Returns |
| 1258 |
------- |
| 1259 |
lower_bound: float |
| 1260 |
Returns the computed lower bound contribution of the |
| 1261 |
log_prob, startprob, and transmat. |
| 1262 |
""" |
| 1263 |
|
| 1264 |
|
| 1265 |
startprob_lower_bound = -_kl.kl_dirichlet( |
| 1266 |
self.startprob_posterior_, self.startprob_prior_) |
| 1267 |
transmat_lower_bound = 0 |
| 1268 |
for i in range(self.n_components): |
| 1269 |
transmat_lower_bound -= _kl.kl_dirichlet( |
| 1270 |
self.transmat_posterior_[i], self.transmat_prior_[i]) |
| 1271 |
return startprob_lower_bound + transmat_lower_bound + curr_logprob |