Debian Codegraph @

src/hmmlearn/tests/test_categorical_hmm.py

raw symbols SCIP
1 import numpy as np
2 from numpy.testing import assert_allclose
3 import pytest
4
5 from hmmlearn import hmm
6
7 from . import assert_log_likelihood_increasing, normalized
8
9
10 class TestCategoricalAgainstWikipedia:
11 """
12 Examples from Wikipedia:
13
14 - http://en.wikipedia.org/wiki/Hidden_Markov_model
15 - http://en.wikipedia.org/wiki/Viterbi_algorithm
16 """
17
18 def new_hmm(self, impl):
19 n_components = 2 # ['Rainy', 'Sunny']
20 n_features = 3 # ['walk', 'shop', 'clean']
21 h = hmm.CategoricalHMM(n_components, implementation=impl)
22 h.n_features = n_features
23 h.startprob_ = np.array([0.6, 0.4])
24 h.transmat_ = np.array([[0.7, 0.3], [0.4, 0.6]])
25 h.emissionprob_ = np.array([[0.1, 0.4, 0.5],
26 [0.6, 0.3, 0.1]])
27 return h
28
29 @pytest.mark.parametrize("implementation", ["scaling", "log"])
30 def test_decode_viterbi(self, implementation):
31 # From http://en.wikipedia.org/wiki/Viterbi_algorithm:
32 # "This reveals that the observations ['walk', 'shop', 'clean']
33 # were most likely generated by states ['Sunny', 'Rainy', 'Rainy'],
34 # with probability 0.01344."
35 h = self.new_hmm(implementation)
36 X = [[0], [1], [2]]
37 log_prob, state_sequence = h.decode(X, algorithm="viterbi")
38 assert round(np.exp(log_prob), 5) == 0.01344
39 assert_allclose(state_sequence, [1, 0, 0])
40
41 @pytest.mark.parametrize("implementation", ["scaling", "log"])
42 def test_decode_map(self, implementation):
43 X = [[0], [1], [2]]
44 h = self.new_hmm(implementation)
45 _log_prob, state_sequence = h.decode(X, algorithm="map")
46 assert_allclose(state_sequence, [1, 0, 0])
47
48 @pytest.mark.parametrize("implementation", ["scaling", "log"])
49 def test_predict(self, implementation):
50 X = [[0], [1], [2]]
51 h = self.new_hmm(implementation)
52 state_sequence = h.predict(X)
53 posteriors = h.predict_proba(X)
54 assert_allclose(state_sequence, [1, 0, 0])
55 assert_allclose(posteriors, [
56 [0.23170303, 0.76829697],
57 [0.62406281, 0.37593719],
58 [0.86397706, 0.13602294],
59 ], rtol=0, atol=1e-6)
60
61
62 class TestCategoricalHMM:
63 n_components = 2
64 n_features = 3
65
66 def new_hmm(self, impl):
67 h = hmm.CategoricalHMM(self.n_components, implementation=impl)
68 h.startprob_ = np.array([0.6, 0.4])
69 h.transmat_ = np.array([[0.7, 0.3], [0.4, 0.6]])
70 h.emissionprob_ = np.array([[0.1, 0.4, 0.5], [0.6, 0.3, 0.1]])
71 return h
72
73 @pytest.mark.parametrize("implementation", ["scaling", "log"])
74 def test_n_features(self, implementation):
75 sequences, _ = self.new_hmm(implementation).sample(500)
76 # set n_features
77 model = hmm.CategoricalHMM(
78 n_components=2, implementation=implementation)
79
80 assert_log_likelihood_increasing(model, sequences, [500], 10)
81 assert model.n_features == 3
82
83 # Respect n_features
84 model = hmm.CategoricalHMM(
85 n_components=2,
86 implementation=implementation,
87 n_features=5)
88
89 assert_log_likelihood_increasing(model, sequences, [500], 10)
90 assert model.n_features == 5
91
92 @pytest.mark.parametrize("implementation", ["scaling", "log"])
93 def test_attributes(self, implementation):
94 with pytest.raises(ValueError):
95 h = self.new_hmm(implementation)
96 h.emissionprob_ = []
97 h._check()
98 with pytest.raises(ValueError):
99 h.emissionprob_ = np.zeros((self.n_components - 2,
100 self.n_features))
101 h._check()
102
103 @pytest.mark.parametrize("implementation", ["scaling", "log"])
104 def test_score_samples(self, implementation):
105 idx = np.repeat(np.arange(self.n_components), 10)
106 n_samples = len(idx)
107 X = np.random.randint(self.n_features, size=(n_samples, 1))
108 h = self.new_hmm(implementation)
109
110 ll, posteriors = h.score_samples(X)
111 assert posteriors.shape == (n_samples, self.n_components)
112 assert_allclose(posteriors.sum(axis=1), np.ones(n_samples))
113
114 @pytest.mark.parametrize("implementation", ["scaling", "log"])
115 def test_sample(self, implementation, n_samples=1000):
116 h = self.new_hmm(implementation)
117 X, state_sequence = h.sample(n_samples)
118 assert X.ndim == 2
119 assert len(X) == len(state_sequence) == n_samples
120 assert len(np.unique(X)) == self.n_features
121
122 @pytest.mark.parametrize("implementation", ["scaling", "log"])
123 def test_fit(self, implementation, params='ste', n_iter=5):
124
125 h = self.new_hmm(implementation)
126 h.params = params
127
128 lengths = np.array([10] * 10)
129 X, _state_sequence = h.sample(lengths.sum())
130
131 # Mess up the parameters and see if we can re-learn them.
132 h.startprob_ = normalized(np.random.random(self.n_components))
133 h.transmat_ = normalized(
134 np.random.random((self.n_components, self.n_components)),
135 axis=1)
136 h.emissionprob_ = normalized(
137 np.random.random((self.n_components, self.n_features)),
138 axis=1)
139
140 assert_log_likelihood_increasing(h, X, lengths, n_iter)
141
142 @pytest.mark.parametrize("implementation", ["scaling", "log"])
143 def test_fit_emissionprob(self, implementation):
144 self.test_fit(implementation, 'e')
145
146 @pytest.mark.parametrize("implementation", ["scaling", "log"])
147 def test_fit_with_init(self, implementation, params='ste', n_iter=5):
148 lengths = [10] * 10
149 h = self.new_hmm(implementation)
150 X, _state_sequence = h.sample(sum(lengths))
151
152 # use init_function to initialize paramerters
153 h = hmm.CategoricalHMM(self.n_components, params=params,
154 init_params=params)
155 h._init(X, lengths)
156
157 assert_log_likelihood_increasing(h, X, lengths, n_iter)
158
159 @pytest.mark.parametrize("implementation", ["scaling", "log"])
160 def test__check_and_set_categorical_n_features(self, implementation):
161 h = self.new_hmm(implementation)
162 h._check_and_set_n_features(np.array([[0, 0, 2, 1, 3, 1, 1]]).T)
163 h._check_and_set_n_features(np.array([[0, 0, 1, 3, 1]], np.uint8))
164 with pytest.raises(ValueError): # non-integral
165 h._check_and_set_n_features(np.array([[0., 2., 1., 3.]]))
166 with pytest.raises(ValueError): # negative integers
167 h._check_and_set_n_features(np.array([[0, -2, 1, 3, 1, 1]]))