| 1 |
import numpy as np |
| 2 |
from numpy.testing import assert_allclose |
| 3 |
import pytest |
| 4 |
from sklearn.utils import check_random_state |
| 5 |
|
| 6 |
from .. import hmm |
| 7 |
from . import assert_log_likelihood_increasing, make_covar_matrix, normalized |
| 8 |
|
| 9 |
|
| 10 |
class GaussianHMMTestMixin: |
| 11 |
covariance_type = None |
| 12 |
|
| 13 |
@pytest.fixture(autouse=True) |
| 14 |
def setup(self): |
| 15 |
self.prng = prng = np.random.RandomState(10) |
| 16 |
self.n_components = n_components = 3 |
| 17 |
self.n_features = n_features = 3 |
| 18 |
self.startprob = normalized(prng.rand(n_components)) |
| 19 |
self.transmat = normalized( |
| 20 |
prng.rand(n_components, n_components), axis=1) |
| 21 |
self.means = prng.randint(-20, 20, (n_components, n_features)) |
| 22 |
self.covars = make_covar_matrix( |
| 23 |
self.covariance_type, n_components, n_features, random_state=prng) |
| 24 |
|
| 25 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 26 |
def test_bad_covariance_type(self, implementation): |
| 27 |
with pytest.raises(ValueError): |
| 28 |
h = hmm.GaussianHMM(20, implementation=implementation, |
| 29 |
covariance_type='badcovariance_type') |
| 30 |
h.means_ = self.means |
| 31 |
h.covars_ = [] |
| 32 |
h.startprob_ = self.startprob |
| 33 |
h.transmat_ = self.transmat |
| 34 |
h._check() |
| 35 |
|
| 36 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 37 |
def test_score_samples_and_decode(self, implementation): |
| 38 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 39 |
init_params="st", implementation=implementation) |
| 40 |
h.means_ = self.means |
| 41 |
h.covars_ = self.covars |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
h.means_ = 20 * h.means_ |
| 46 |
|
| 47 |
gaussidx = np.repeat(np.arange(self.n_components), 5) |
| 48 |
n_samples = len(gaussidx) |
| 49 |
X = (self.prng.randn(n_samples, self.n_features) |
| 50 |
+ h.means_[gaussidx]) |
| 51 |
h._init(X, [n_samples]) |
| 52 |
ll, posteriors = h.score_samples(X) |
| 53 |
assert posteriors.shape == (n_samples, self.n_components) |
| 54 |
assert_allclose(posteriors.sum(axis=1), np.ones(n_samples)) |
| 55 |
|
| 56 |
viterbi_ll, stateseq = h.decode(X) |
| 57 |
assert_allclose(stateseq, gaussidx) |
| 58 |
|
| 59 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 60 |
def test_sample(self, implementation, n=1000): |
| 61 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 62 |
implementation=implementation) |
| 63 |
h.startprob_ = self.startprob |
| 64 |
h.transmat_ = self.transmat |
| 65 |
|
| 66 |
|
| 67 |
h.means_ = 20 * self.means |
| 68 |
h.covars_ = np.maximum(self.covars, 0.1) |
| 69 |
|
| 70 |
X, state_sequence = h.sample(n, random_state=self.prng) |
| 71 |
assert X.shape == (n, self.n_features) |
| 72 |
assert len(state_sequence) == n |
| 73 |
|
| 74 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 75 |
def test_fit(self, implementation, params='stmc', n_iter=5, **kwargs): |
| 76 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 77 |
implementation=implementation) |
| 78 |
h.startprob_ = self.startprob |
| 79 |
h.transmat_ = normalized( |
| 80 |
self.transmat + np.diag(self.prng.rand(self.n_components)), 1) |
| 81 |
h.means_ = 20 * self.means |
| 82 |
h.covars_ = self.covars |
| 83 |
|
| 84 |
lengths = [10] * 10 |
| 85 |
X, _state_sequence = h.sample(sum(lengths), random_state=self.prng) |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
h.fit(X, lengths=lengths) |
| 90 |
|
| 91 |
|
| 92 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 93 |
def test_criterion(self, implementation): |
| 94 |
random_state = check_random_state(42) |
| 95 |
m1 = hmm.GaussianHMM(self.n_components, init_params="", |
| 96 |
covariance_type=self.covariance_type) |
| 97 |
m1.startprob_ = self.startprob |
| 98 |
m1.transmat_ = self.transmat |
| 99 |
m1.means_ = self.means * 10 |
| 100 |
m1.covars_ = self.covars |
| 101 |
|
| 102 |
X, _ = m1.sample(2000, random_state=random_state) |
| 103 |
|
| 104 |
aic = [] |
| 105 |
bic = [] |
| 106 |
ns = [2, 3, 4] |
| 107 |
for n in ns: |
| 108 |
h = hmm.GaussianHMM(n, self.covariance_type, n_iter=500, |
| 109 |
random_state=random_state, implementation=implementation) |
| 110 |
h.fit(X) |
| 111 |
aic.append(h.aic(X)) |
| 112 |
bic.append(h.bic(X)) |
| 113 |
|
| 114 |
assert np.all(aic) > 0 |
| 115 |
assert np.all(bic) > 0 |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 121 |
def test_fit_ignored_init_warns(self, implementation, caplog): |
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 126 |
implementation=implementation) |
| 127 |
h.startprob_ = self.startprob |
| 128 |
h.fit(self.prng.randn(100, self.n_components)) |
| 129 |
found = False |
| 130 |
for record in caplog.records: |
| 131 |
if "will be overwritten" in record.getMessage(): |
| 132 |
found = True |
| 133 |
assert found, "Did not find expected warning message" |
| 134 |
|
| 135 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 136 |
def test_fit_too_little_data(self, implementation, caplog): |
| 137 |
h = hmm.GaussianHMM( |
| 138 |
self.n_components, self.covariance_type, init_params="", |
| 139 |
implementation=implementation) |
| 140 |
h.startprob_ = self.startprob |
| 141 |
h.transmat_ = self.transmat |
| 142 |
h.means_ = 20 * self.means |
| 143 |
h.covars_ = np.maximum(self.covars, 0.1) |
| 144 |
h._init(self.prng.randn(5, self.n_components), 5) |
| 145 |
assert len(caplog.records) == 1 |
| 146 |
assert "degenerate solution" in caplog.records[0].getMessage() |
| 147 |
|
| 148 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 149 |
def test_fit_sequences_of_different_length(self, implementation): |
| 150 |
lengths = [3, 4, 5] |
| 151 |
X = self.prng.rand(sum(lengths), self.n_features) |
| 152 |
|
| 153 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 154 |
implementation=implementation) |
| 155 |
|
| 156 |
|
| 157 |
h.fit(X, lengths=lengths) |
| 158 |
|
| 159 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 160 |
def test_fit_with_length_one_signal(self, implementation): |
| 161 |
lengths = [10, 8, 1] |
| 162 |
X = self.prng.rand(sum(lengths), self.n_features) |
| 163 |
|
| 164 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 165 |
implementation=implementation) |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
h.fit(X, lengths=lengths) |
| 170 |
|
| 171 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 172 |
def test_fit_zero_variance(self, implementation): |
| 173 |
|
| 174 |
X = np.asarray([ |
| 175 |
[7.15000000e+02, 5.85000000e+02, 0.00000000e+00, 0.00000000e+00], |
| 176 |
[7.15000000e+02, 5.20000000e+02, 1.04705811e+00, -6.03696289e+01], |
| 177 |
[7.15000000e+02, 4.55000000e+02, 7.20886230e-01, -5.27055664e+01], |
| 178 |
[7.15000000e+02, 3.90000000e+02, -4.57946777e-01, -7.80605469e+01], |
| 179 |
[7.15000000e+02, 3.25000000e+02, -6.43127441e+00, -5.59954834e+01], |
| 180 |
[7.15000000e+02, 2.60000000e+02, -2.90063477e+00, -7.80220947e+01], |
| 181 |
[7.15000000e+02, 1.95000000e+02, 8.45532227e+00, -7.03294373e+01], |
| 182 |
[7.15000000e+02, 1.30000000e+02, 4.09387207e+00, -5.83621216e+01], |
| 183 |
[7.15000000e+02, 6.50000000e+01, -1.21667480e+00, -4.48131409e+01] |
| 184 |
]) |
| 185 |
h = hmm.GaussianHMM(3, self.covariance_type, |
| 186 |
implementation=implementation) |
| 187 |
h.fit(X) |
| 188 |
|
| 189 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 190 |
def test_fit_with_priors(self, implementation, init_params='mc', |
| 191 |
params='stmc', n_iter=20): |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
startprob_prior = 10 * self.startprob + 2.0 |
| 199 |
transmat_prior = 10 * self.transmat + 2.0 |
| 200 |
means_prior = self.means |
| 201 |
means_weight = 2.0 |
| 202 |
covars_weight = 2.0 |
| 203 |
if self.covariance_type in ('full', 'tied'): |
| 204 |
covars_weight += self.n_features |
| 205 |
covars_prior = self.covars |
| 206 |
h = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 207 |
implementation=implementation) |
| 208 |
h.startprob_ = self.startprob |
| 209 |
h.startprob_prior = startprob_prior |
| 210 |
h.transmat_ = normalized( |
| 211 |
self.transmat + np.diag(self.prng.rand(self.n_components)), 1) |
| 212 |
h.transmat_prior = transmat_prior |
| 213 |
h.means_ = 20 * self.means |
| 214 |
h.means_prior = means_prior |
| 215 |
h.means_weight = means_weight |
| 216 |
h.covars_ = self.covars |
| 217 |
h.covars_prior = covars_prior |
| 218 |
h.covars_weight = covars_weight |
| 219 |
|
| 220 |
lengths = [200] * 10 |
| 221 |
X, _state_sequence = h.sample(sum(lengths), random_state=self.prng) |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
h_learn = hmm.GaussianHMM(self.n_components, self.covariance_type, |
| 226 |
init_params=init_params, params=params, |
| 227 |
implementation=implementation,) |
| 228 |
|
| 229 |
init = 1. / h_learn.n_components |
| 230 |
h_learn.startprob_ = np.full(h_learn.n_components, init) |
| 231 |
h_learn.transmat_ = \ |
| 232 |
np.full((h_learn.n_components, h_learn.n_components), init) |
| 233 |
|
| 234 |
h_learn.n_iter = 0 |
| 235 |
h_learn.fit(X, lengths=lengths) |
| 236 |
|
| 237 |
assert_log_likelihood_increasing(h_learn, X, lengths, n_iter) |
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
assert_allclose(sorted(h.means_.ravel().tolist()), |
| 244 |
sorted(h_learn.means_.ravel().tolist()), |
| 245 |
0.01) |
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
orig = np.broadcast_to(h._covars_, h_learn._covars_.shape) |
| 251 |
assert_allclose( |
| 252 |
sorted(orig.ravel().tolist()), |
| 253 |
sorted(h_learn._covars_.ravel().tolist()), |
| 254 |
10) |
| 255 |
|
| 256 |
|
| 257 |
class TestGaussianHMMWithSphericalCovars(GaussianHMMTestMixin): |
| 258 |
covariance_type = 'spherical' |
| 259 |
|
| 260 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 261 |
def test_issue_385(self, implementation): |
| 262 |
model = hmm.GaussianHMM(n_components=2, covariance_type="spherical") |
| 263 |
model.startprob_ = np.array([0.6, 0.4]) |
| 264 |
model.transmat_ = np.array([[0.4, 0.6], |
| 265 |
[0.9, 0.1]]) |
| 266 |
model.means_ = np.array([[3.0], [5.0]]) |
| 267 |
model.covars_ = np.array([[[[4.0]]], [[[3.0]]]]) |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
model.n_features = 1 |
| 272 |
covars = model.covars_ |
| 273 |
|
| 274 |
|
| 275 |
model.sample(1000) |
| 276 |
|
| 277 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 278 |
def test_fit_startprob_and_transmat(self, implementation): |
| 279 |
self.test_fit(implementation, 'st') |
| 280 |
|
| 281 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 282 |
def test_underflow_from_scaling(self, implementation): |
| 283 |
|
| 284 |
data1 = self.prng.normal(0, 1, 100).tolist() |
| 285 |
data2 = self.prng.normal(5, 1, 100).tolist() |
| 286 |
data3 = self.prng.normal(0, 1, 100).tolist() |
| 287 |
data4 = self.prng.normal(5, 1, 100).tolist() |
| 288 |
data = np.concatenate([data1, data2, data3, data4]) |
| 289 |
|
| 290 |
data[40] = 10000 |
| 291 |
data2d = data[:, None] |
| 292 |
lengths = [len(data2d)] |
| 293 |
h = hmm.GaussianHMM(2, n_iter=100, verbose=True, |
| 294 |
covariance_type=self.covariance_type, |
| 295 |
implementation=implementation, init_params="") |
| 296 |
h.startprob_ = [0.0, 1] |
| 297 |
h.transmat_ = [[0.4, 0.6], [0.6, 0.4]] |
| 298 |
h.means_ = [[0], [5]] |
| 299 |
h.covars_ = [[1], [1]] |
| 300 |
if implementation == "scaling": |
| 301 |
with pytest.raises(ValueError): |
| 302 |
h.fit(data2d, lengths) |
| 303 |
|
| 304 |
else: |
| 305 |
h.fit(data2d, lengths) |
| 306 |
|
| 307 |
|
| 308 |
class TestGaussianHMMWithDiagonalCovars(GaussianHMMTestMixin): |
| 309 |
covariance_type = 'diag' |
| 310 |
|
| 311 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 312 |
def test_covar_is_writeable(self, implementation): |
| 313 |
h = hmm.GaussianHMM(n_components=1, covariance_type="diag", |
| 314 |
init_params="c", implementation=implementation) |
| 315 |
X = self.prng.normal(size=(1000, 5)) |
| 316 |
h._init(X, 1000) |
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
assert h._covars_.flags["WRITEABLE"] |
| 323 |
|
| 324 |
@pytest.mark.parametrize("implementation", ["scaling", "log"]) |
| 325 |
def test_fit_left_right(self, implementation): |
| 326 |
transmat = np.zeros((self.n_components, self.n_components)) |
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
for i in range(self.n_components): |
| 331 |
if i == self.n_components - 1: |
| 332 |
transmat[i, i] = 1.0 |
| 333 |
else: |
| 334 |
transmat[i, i] = transmat[i, i + 1] = 0.5 |
| 335 |
|
| 336 |
|
| 337 |
startprob = np.zeros(self.n_components) |
| 338 |
startprob[0] = 1.0 |
| 339 |
|
| 340 |
lengths = [10, 8, 1] |
| 341 |
X = self.prng.rand(sum(lengths), self.n_features) |
| 342 |
|
| 343 |
h = hmm.GaussianHMM(self.n_components, covariance_type="diag", |
| 344 |
params="mct", init_params="cm", |
| 345 |
implementation=implementation) |
| 346 |
h.startprob_ = startprob.copy() |
| 347 |
h.transmat_ = transmat.copy() |
| 348 |
h.fit(X) |
| 349 |
|
| 350 |
assert (h.startprob_[startprob == 0.0] == 0.0).all() |
| 351 |
assert (h.transmat_[transmat == 0.0] == 0.0).all() |
| 352 |
|
| 353 |
posteriors = h.predict_proba(X) |
| 354 |
assert not np.isnan(posteriors).any() |
| 355 |
assert_allclose(posteriors.sum(axis=1), 1.) |
| 356 |
|
| 357 |
score, state_sequence = h.decode(X, algorithm="viterbi") |
| 358 |
assert np.isfinite(score) |
| 359 |
|
| 360 |
|
| 361 |
class TestGaussianHMMWithTiedCovars(GaussianHMMTestMixin): |
| 362 |
covariance_type = 'tied' |
| 363 |
|
| 364 |
|
| 365 |
class TestGaussianHMMWithFullCovars(GaussianHMMTestMixin): |
| 366 |
covariance_type = 'full' |