| 1 |
import numpy as np |
| 2 |
from numpy.testing import assert_allclose |
| 3 |
import pytest |
| 4 |
from scipy import special |
| 5 |
|
| 6 |
from hmmlearn.base import BaseHMM, ConvergenceMonitor |
| 7 |
from hmmlearn import _hmmc |
| 8 |
|
| 9 |
|
| 10 |
class TestMonitor: |
| 11 |
def test_converged_by_iterations(self): |
| 12 |
m = ConvergenceMonitor(tol=1e-3, n_iter=2, verbose=False) |
| 13 |
assert not m.converged |
| 14 |
m.report(-0.01) |
| 15 |
assert not m.converged |
| 16 |
m.report(-0.1) |
| 17 |
assert m.converged |
| 18 |
|
| 19 |
def test_converged_by_log_prob(self): |
| 20 |
m = ConvergenceMonitor(tol=1e-3, n_iter=10, verbose=False) |
| 21 |
for log_prob in [-0.03, -0.02, -0.01]: |
| 22 |
m.report(log_prob) |
| 23 |
assert not m.converged |
| 24 |
|
| 25 |
m.report(-0.0101) |
| 26 |
assert m.converged |
| 27 |
|
| 28 |
def test_reset(self): |
| 29 |
m = ConvergenceMonitor(tol=1e-3, n_iter=10, verbose=False) |
| 30 |
m.iter = 1 |
| 31 |
m.history.append(-0.01) |
| 32 |
m._reset() |
| 33 |
assert m.iter == 0 |
| 34 |
assert not m.history |
| 35 |
|
| 36 |
def test_report_first_iteration(self, capsys): |
| 37 |
m = ConvergenceMonitor(tol=1e-3, n_iter=10, verbose=True) |
| 38 |
m.report(-0.01) |
| 39 |
out, err = capsys.readouterr() |
| 40 |
assert not out |
| 41 |
expected = m._template.format(iter=1, log_prob=-0.01, delta=np.nan) |
| 42 |
assert err.splitlines() == [expected] |
| 43 |
|
| 44 |
def test_report(self, capsys): |
| 45 |
n_iter = 10 |
| 46 |
m = ConvergenceMonitor(tol=1e-3, n_iter=n_iter, verbose=True) |
| 47 |
for i in reversed(range(n_iter)): |
| 48 |
m.report(-0.01 * i) |
| 49 |
|
| 50 |
out, err = capsys.readouterr() |
| 51 |
assert not out |
| 52 |
assert len(err.splitlines()) == n_iter |
| 53 |
assert len(m.history) == n_iter |
| 54 |
|
| 55 |
|
| 56 |
class StubHMM(BaseHMM): |
| 57 |
"""An HMM with hardcoded observation probabilities.""" |
| 58 |
def _compute_log_likelihood(self, X): |
| 59 |
return self.log_frameprob |
| 60 |
|
| 61 |
|
| 62 |
class TestBaseAgainstWikipedia: |
| 63 |
def setup_method(self, method): |
| 64 |
|
| 65 |
self.frameprob = np.asarray([[0.9, 0.2], |
| 66 |
[0.9, 0.2], |
| 67 |
[0.1, 0.8], |
| 68 |
[0.9, 0.2], |
| 69 |
[0.9, 0.2]]) |
| 70 |
self.log_frameprob = np.log(self.frameprob) |
| 71 |
h = StubHMM(2) |
| 72 |
h.transmat_ = [[0.7, 0.3], [0.3, 0.7]] |
| 73 |
h.startprob_ = [0.5, 0.5] |
| 74 |
h.log_frameprob = self.log_frameprob |
| 75 |
h.frameprob = self.frameprob |
| 76 |
self.hmm = h |
| 77 |
|
| 78 |
def test_do_forward_scaling_pass(self): |
| 79 |
log_prob, fwdlattice, scaling_factors = _hmmc.forward_scaling( |
| 80 |
self.hmm.startprob_, self.hmm.transmat_, self.frameprob) |
| 81 |
ref_log_prob = -3.3725 |
| 82 |
assert round(log_prob, 4) == ref_log_prob |
| 83 |
reffwdlattice = np.exp([[0.4500, 0.1000], |
| 84 |
[0.3105, 0.0410], |
| 85 |
[0.0230, 0.0975], |
| 86 |
[0.0408, 0.0150], |
| 87 |
[0.0298, 0.0046]]) |
| 88 |
assert_allclose(np.exp(fwdlattice), reffwdlattice, 4) |
| 89 |
|
| 90 |
def test_do_forward_pass(self): |
| 91 |
log_prob, fwdlattice = _hmmc.forward_log( |
| 92 |
self.hmm.startprob_, self.hmm.transmat_, self.log_frameprob) |
| 93 |
|
| 94 |
ref_log_prob = -3.3725 |
| 95 |
assert round(log_prob, 4) == ref_log_prob |
| 96 |
reffwdlattice = np.array([[0.4500, 0.1000], |
| 97 |
[0.3105, 0.0410], |
| 98 |
[0.0230, 0.0975], |
| 99 |
[0.0408, 0.0150], |
| 100 |
[0.0298, 0.0046]]) |
| 101 |
assert_allclose(np.exp(fwdlattice), reffwdlattice, 4) |
| 102 |
|
| 103 |
def test_do_backward_scaling_pass(self): |
| 104 |
log_prob, fwdlattice, scaling_factors = _hmmc.forward_scaling( |
| 105 |
self.hmm.startprob_, self.hmm.transmat_, self.frameprob) |
| 106 |
bwdlattice = _hmmc.backward_scaling(self.hmm.startprob_, |
| 107 |
self.hmm.transmat_, self.frameprob, scaling_factors) |
| 108 |
refbwdlattice = np.array([[0.0661, 0.0455], |
| 109 |
[0.0906, 0.1503], |
| 110 |
[0.4593, 0.2437], |
| 111 |
[0.6900, 0.4100], |
| 112 |
[1.0000, 1.0000]]) |
| 113 |
scaling_factors = np.cumprod(scaling_factors[::-1])[::-1] |
| 114 |
bwdlattice_scaled = bwdlattice / scaling_factors[:, None] |
| 115 |
|
| 116 |
assert_allclose(bwdlattice_scaled, refbwdlattice, 4) |
| 117 |
|
| 118 |
def test_do_backward_log_pass(self): |
| 119 |
bwdlattice = _hmmc.backward_log( |
| 120 |
self.hmm.startprob_, self.hmm.transmat_, self.log_frameprob) |
| 121 |
refbwdlattice = np.array([[0.0661, 0.0455], |
| 122 |
[0.0906, 0.1503], |
| 123 |
[0.4593, 0.2437], |
| 124 |
[0.6900, 0.4100], |
| 125 |
[1.0000, 1.0000]]) |
| 126 |
assert_allclose(np.exp(bwdlattice), refbwdlattice, 4) |
| 127 |
|
| 128 |
def test_do_viterbi_pass(self): |
| 129 |
log_prob, state_sequence = _hmmc.viterbi( |
| 130 |
self.hmm.startprob_, self.hmm.transmat_, self.log_frameprob) |
| 131 |
refstate_sequence = [0, 0, 1, 0, 0] |
| 132 |
assert_allclose(state_sequence, refstate_sequence) |
| 133 |
ref_log_prob = -4.4590 |
| 134 |
assert round(log_prob, 4) == ref_log_prob |
| 135 |
|
| 136 |
def test_score_samples(self): |
| 137 |
|
| 138 |
|
| 139 |
log_prob, posteriors = self.hmm.score_samples(self.log_frameprob) |
| 140 |
assert_allclose(posteriors.sum(axis=1), np.ones(len(posteriors))) |
| 141 |
ref_log_prob = -3.3725 |
| 142 |
assert round(log_prob, 4) == ref_log_prob |
| 143 |
refposteriors = np.array([[0.8673, 0.1327], |
| 144 |
[0.8204, 0.1796], |
| 145 |
[0.3075, 0.6925], |
| 146 |
[0.8204, 0.1796], |
| 147 |
[0.8673, 0.1327]]) |
| 148 |
assert_allclose(posteriors, refposteriors, atol=1e-4) |
| 149 |
|
| 150 |
def test_generate_samples(self): |
| 151 |
X0, Z0 = self.hmm.sample(n_samples=10) |
| 152 |
X, Z = self.hmm.sample(n_samples=10, currstate=Z0[-1]) |
| 153 |
assert len(Z0) == len(Z) == 10 and Z[0] == Z0[-1] |
| 154 |
|
| 155 |
|
| 156 |
class TestBaseConsistentWithGMM: |
| 157 |
def setup_method(self, method): |
| 158 |
n_components = 8 |
| 159 |
n_samples = 10 |
| 160 |
|
| 161 |
self.log_frameprob = np.log( |
| 162 |
np.random.random((n_samples, n_components))) |
| 163 |
|
| 164 |
h = StubHMM(n_components) |
| 165 |
h.log_frameprob = self.log_frameprob |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
h.startprob_ = np.ones(n_components) / n_components |
| 172 |
h.transmat_ = np.ones((n_components, n_components)) / n_components |
| 173 |
|
| 174 |
self.hmm = h |
| 175 |
|
| 176 |
def test_score_samples(self): |
| 177 |
log_prob, hmmposteriors = self.hmm.score_samples(self.log_frameprob) |
| 178 |
|
| 179 |
n_samples, n_components = self.log_frameprob.shape |
| 180 |
assert_allclose(hmmposteriors.sum(axis=1), np.ones(n_samples)) |
| 181 |
|
| 182 |
norm = special.logsumexp(self.log_frameprob, axis=1)[:, np.newaxis] |
| 183 |
gmmposteriors = np.exp(self.log_frameprob |
| 184 |
- np.tile(norm, (1, n_components))) |
| 185 |
assert_allclose(hmmposteriors, gmmposteriors) |
| 186 |
|
| 187 |
def test_decode(self): |
| 188 |
_log_prob, state_sequence = self.hmm.decode(self.log_frameprob) |
| 189 |
|
| 190 |
n_samples, n_components = self.log_frameprob.shape |
| 191 |
norm = special.logsumexp(self.log_frameprob, axis=1)[:, np.newaxis] |
| 192 |
gmmposteriors = np.exp(self.log_frameprob |
| 193 |
- np.tile(norm, (1, n_components))) |
| 194 |
gmmstate_sequence = gmmposteriors.argmax(axis=1) |
| 195 |
assert_allclose(state_sequence, gmmstate_sequence) |
| 196 |
|
| 197 |
|
| 198 |
def test_base_hmm_attributes(): |
| 199 |
n_components = 20 |
| 200 |
startprob = np.random.random(n_components) |
| 201 |
startprob /= startprob.sum() |
| 202 |
transmat = np.random.random((n_components, n_components)) |
| 203 |
transmat /= np.tile(transmat.sum(axis=1)[:, np.newaxis], (1, n_components)) |
| 204 |
|
| 205 |
h = StubHMM(n_components) |
| 206 |
|
| 207 |
assert h.n_components == n_components |
| 208 |
|
| 209 |
h.startprob_ = startprob |
| 210 |
assert_allclose(h.startprob_, startprob) |
| 211 |
|
| 212 |
with pytest.raises(ValueError): |
| 213 |
h.startprob_ = 2 * startprob |
| 214 |
h._check() |
| 215 |
with pytest.raises(ValueError): |
| 216 |
h.startprob_ = [] |
| 217 |
h._check() |
| 218 |
with pytest.raises(ValueError): |
| 219 |
h.startprob_ = np.zeros((n_components - 2, 2)) |
| 220 |
h._check() |
| 221 |
|
| 222 |
h.startprob_ = startprob |
| 223 |
h.transmat_ = transmat |
| 224 |
assert_allclose(h.transmat_, transmat) |
| 225 |
with pytest.raises(ValueError): |
| 226 |
h.transmat_ = 2 * transmat |
| 227 |
h._check() |
| 228 |
with pytest.raises(ValueError): |
| 229 |
h.transmat_ = [] |
| 230 |
h._check() |
| 231 |
with pytest.raises(ValueError): |
| 232 |
h.transmat_ = np.zeros((n_components - 2, n_components)) |
| 233 |
h._check() |
| 234 |
|
| 235 |
|
| 236 |
def test_stationary_distribution(): |
| 237 |
n_components = 10 |
| 238 |
h = StubHMM(n_components) |
| 239 |
transmat = np.random.random((n_components, n_components)) |
| 240 |
transmat /= np.tile(transmat.sum(axis=1)[:, np.newaxis], (1, n_components)) |
| 241 |
h.transmat_ = transmat |
| 242 |
stationary = h.get_stationary_distribution() |
| 243 |
assert stationary.dtype == float |
| 244 |
assert (h.get_stationary_distribution().T @ h.transmat_ |
| 245 |
== pytest.approx(stationary)) |