File: hmm.rst

package info (click to toggle)
python-bayespy 0.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,132 kB
  • sloc: python: 22,402; makefile: 156
file content (420 lines) | stat: -rw-r--r-- 12,291 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
..
   Copyright (C) 2014 Jaakko Luttinen

   This file is licensed under the MIT License. See LICENSE for a text of the
   license.


.. testsetup::

   import numpy
   numpy.random.seed(1)

Hidden Markov model
===================


In this example, we will demonstrate the use of hidden Markov model in the case
of known and unknown parameters.  We will also use two different emission
distributions to demonstrate the flexibility of the model construction.


Known parameters
----------------

This example follows the one presented in `Wikipedia
<http://en.wikipedia.org/wiki/Hidden_Markov_model#A_concrete_example>`__.

Model
+++++

Each day, the state of the weather is either 'rainy' or 'sunny'. The weather
follows a first-order discrete Markov process.  It has the following initial
state probabilities

>>> a0 = [0.6, 0.4] # p(rainy)=0.6, p(sunny)=0.4
    
and state transition probabilities:

>>> A = [[0.7, 0.3], # p(rainy->rainy)=0.7, p(rainy->sunny)=0.3
...      [0.4, 0.6]] # p(sunny->rainy)=0.4, p(sunny->sunny)=0.6
    
We will be observing one hundred samples:

>>> N = 100
    
The discrete first-order Markov chain is constructed as:

>>> from bayespy.nodes import CategoricalMarkovChain
>>> Z = CategoricalMarkovChain(a0, A, states=N)

However, instead of observing this process directly, we observe whether Bob is
'walking', 'shopping' or 'cleaning'. The probability of each activity depends on
the current weather as follows:

>>> P = [[0.1, 0.4, 0.5],
...      [0.6, 0.3, 0.1]]

where the first row contains activity probabilities on a rainy weather and the
second row contains activity probabilities on a sunny weather.  Using these
emission probabilities, the observed process is constructed as:

>>> from bayespy.nodes import Categorical, Mixture
>>> Y = Mixture(Z, Categorical, P)

Data
++++

In order to test our method, we'll generate artificial data from the model
itself.  First, draw realization of the weather process:

>>> weather = Z.random()

Then, using this weather, draw realizations of the activities:

>>> activity = Mixture(weather, Categorical, P).random()

Inference
+++++++++

Now, using this data, we set our variable :math:`Y` to be observed:

>>> Y.observe(activity)

In order to run inference, we construct variational Bayesian inference engine:

>>> from bayespy.inference import VB
>>> Q = VB(Y, Z)

Note that we need to give all random variables to ``VB``. In this case, the only
random variables were ``Y`` and ``Z``. Next we run the inference, that is,
compute our posterior distribution:

>>> Q.update()
Iteration 1: loglike=-1.095883e+02 (... seconds)

In this case, because there is only one unobserved random variable, we
recover the exact posterior distribution and there is no need to iterate
more than one step.

Results
+++++++

.. currentmodule:: bayespy.plot

One way to plot a 2-class categorical timeseries is to use the basic
:func:`plot` function:

>>> import bayespy.plot as bpplt
>>> bpplt.plot(Z)
>>> bpplt.plot(1-weather, color='r', marker='x')

.. plot::

   import numpy
   numpy.random.seed(1)
   from bayespy.nodes import CategoricalMarkovChain
   a0 = [0.6, 0.4] # p(rainy)=0.6, p(sunny)=0.4
   A = [[0.7, 0.3], # p(rainy->rainy)=0.7, p(rainy->sunny)=0.3
        [0.4, 0.6]] # p(sunny->rainy)=0.4, p(sunny->sunny)=0.6
   N = 100
   Z = CategoricalMarkovChain(a0, A, states=N)
   from bayespy.nodes import Categorical, Mixture
   P = [[0.1, 0.4, 0.5],
        [0.6, 0.3, 0.1]]
   Y = Mixture(Z, Categorical, P)
   weather = Z.random()
   activity = Mixture(weather, Categorical, P).random()
   Y.observe(activity)
   from bayespy.inference import VB
   Q = VB(Y, Z)
   Q.update()
   import bayespy.plot as bpplt
   bpplt.plot(Z)
   bpplt.plot(1-weather, color='r', marker='x')
   bpplt.pyplot.show()


The black line shows the posterior probability of rain and the red line and
crosses show the true state.  Clearly, the method is not able to infer the
weather very accurately in this case because the activies do not give that much
information about the weather.



Unknown parameters
------------------

In this example, we consider unknown parameters for the Markov process and
different emission distribution.

Data
++++

We generate data from three 2-dimensional Gaussian distributions with different
mean vectors and common standard deviation:

>>> import numpy as np
>>> mu = np.array([ [0,0], [3,4], [6,0] ])
>>> std = 2.0

Thus, the number of clusters is three:

>>> K = 3

And the number of samples is 200:

>>> N = 200

Each initial state is equally probable:

>>> p0 = np.ones(K) / K

State transition matrix is such that with probability 0.9 the process stays in
the same state.  The probability to move one of the other two states is 0.05 for
both of those states.

>>> q = 0.9
>>> r = (1-q) / (K-1)
>>> P = q*np.identity(K) + r*(np.ones((3,3))-np.identity(3))

Simulate the data:

>>> y = np.zeros((N,2))
>>> z = np.zeros(N)
>>> state = np.random.choice(K, p=p0)
>>> for n in range(N):
...     z[n] = state
...     y[n,:] = std*np.random.randn(2) + mu[state]
...     state = np.random.choice(K, p=P[state])

Then, let us visualize the data:

>>> bpplt.pyplot.figure()
<matplotlib.figure.Figure object at 0x...>
>>> bpplt.pyplot.axis('equal')
(...)
>>> colors = [ [[1,0,0], [0,1,0], [0,0,1]][int(state)] for state in z ]
>>> bpplt.pyplot.plot(y[:,0], y[:,1], 'k-', zorder=-10)
[<matplotlib.lines.Line2D object at 0x...>]
>>> bpplt.pyplot.scatter(y[:,0], y[:,1], c=colors, s=40)
<matplotlib.collections.PathCollection object at 0x...>

.. plot::

   import numpy
   numpy.random.seed(1)
   from bayespy.nodes import CategoricalMarkovChain
   a0 = [0.6, 0.4] # p(rainy)=0.6, p(sunny)=0.4
   A = [[0.7, 0.3], # p(rainy->rainy)=0.7, p(rainy->sunny)=0.3
        [0.4, 0.6]] # p(sunny->rainy)=0.4, p(sunny->sunny)=0.6
   N = 100
   Z = CategoricalMarkovChain(a0, A, states=N)
   from bayespy.nodes import Categorical, Mixture
   P = [[0.1, 0.4, 0.5],
        [0.6, 0.3, 0.1]]
   Y = Mixture(Z, Categorical, P)
   weather = Z.random()
   from bayespy.inference import VB
   import bayespy.plot as bpplt
   import numpy as np
   mu = np.array([ [0,0], [3,4], [6,0] ])
   std = 2.0
   K = 3
   N = 200
   p0 = np.ones(K) / K
   q = 0.9
   r = (1-q)/(K-1)
   P = q*np.identity(K) + r*(np.ones((3,3))-np.identity(3))
   y = np.zeros((N,2))
   z = np.zeros(N)
   state = np.random.choice(K, p=p0)
   for n in range(N):
       z[n] = state
       y[n,:] = std*np.random.randn(2) + mu[state]
       state = np.random.choice(K, p=P[state])
   bpplt.pyplot.figure()
   bpplt.pyplot.axis('equal')
   colors = [ [[1,0,0], [0,1,0], [0,0,1]][int(state)] for state in z ]
   bpplt.pyplot.plot(y[:,0], y[:,1], 'k-', zorder=-10)
   bpplt.pyplot.scatter(y[:,0], y[:,1], c=colors, s=40)
   bpplt.pyplot.show()

Consecutive states are connected by a solid black line and the dot color shows
the true class.

Model
+++++

Now, assume that we do not know the parameters of the process (initial state
probability and state transition probabilities). We give these parameters quite
non-informative priors, but it is possible to provide more informative priors if
such information is available:

>>> from bayespy.nodes import Dirichlet
>>> a0 = Dirichlet(1e-3*np.ones(K))
>>> A = Dirichlet(1e-3*np.ones((K,K)))

The discrete Markov chain is constructed as:

>>> Z = CategoricalMarkovChain(a0, A, states=N)

Now, instead of using categorical emission distribution as before, we'll use
Gaussian distribution.  For simplicity, we use the true parameters of the
Gaussian distributions instead of giving priors and estimating them.  The known
standard deviation can be converted to a precision matrix as:

>>> Lambda = std**(-2) * np.identity(2)

Thus, the observed process is a Gaussian mixture with cluster assignments from
the hidden Markov process ``Z``:

>>> from bayespy.nodes import Gaussian
>>> Y = Mixture(Z, Gaussian, mu, Lambda)

Note that ``Lambda`` does not have cluster plate axis because it is shared
between the clusters.

Inference
+++++++++

Let us use the simulated data:

>>> Y.observe(y)

Because ``VB`` takes all the random variables, we need to provide ``A`` and
``a0`` also:

>>> Q = VB(Y, Z, A, a0)

Then, run VB iteration until convergence:

>>> Q.update(repeat=1000)
Iteration 1: loglike=-9.963054e+02 (... seconds)
...
Iteration 8: loglike=-9.235053e+02 (... seconds)
Converged at iteration 8.


Results
+++++++

Plot the classification of the data similarly as the data:

>>> bpplt.pyplot.figure()
<matplotlib.figure.Figure object at 0x...>
>>> bpplt.pyplot.axis('equal')
(...)
>>> colors = Y.parents[0].get_moments()[0]
>>> bpplt.pyplot.plot(y[:,0], y[:,1], 'k-', zorder=-10)
[<matplotlib.lines.Line2D object at 0x...>]
>>> bpplt.pyplot.scatter(y[:,0], y[:,1], c=colors, s=40)
<matplotlib.collections.PathCollection object at 0x...>

.. plot::

   import numpy
   numpy.random.seed(1)
   from bayespy.nodes import CategoricalMarkovChain
   a0 = [0.6, 0.4] # p(rainy)=0.6, p(sunny)=0.4
   A = [[0.7, 0.3], # p(rainy->rainy)=0.7, p(rainy->sunny)=0.3
        [0.4, 0.6]] # p(sunny->rainy)=0.4, p(sunny->sunny)=0.6
   N = 100
   Z = CategoricalMarkovChain(a0, A, states=N)
   from bayespy.nodes import Categorical, Mixture
   P = [[0.1, 0.4, 0.5],
        [0.6, 0.3, 0.1]]
   Y = Mixture(Z, Categorical, P)
   weather = Z.random()
   from bayespy.inference import VB
   import bayespy.plot as bpplt
   import numpy as np
   mu = np.array([ [0,0], [3,4], [6,0] ])
   std = 2.0
   K = 3
   N = 200
   p0 = np.ones(K) / K
   q = 0.9
   r = (1-q)/(K-1)
   P = q*np.identity(K) + r*(np.ones((3,3))-np.identity(3))
   y = np.zeros((N,2))
   z = np.zeros(N)
   state = np.random.choice(K, p=p0)
   for n in range(N):
       z[n] = state
       y[n,:] = std*np.random.randn(2) + mu[state]
       state = np.random.choice(K, p=P[state])
   from bayespy.nodes import Dirichlet
   a0 = Dirichlet(1e-3*np.ones(K))
   A = Dirichlet(1e-3*np.ones((K,K)))
   Z = CategoricalMarkovChain(a0, A, states=N)
   Lambda = std**(-2) * np.identity(2)
   from bayespy.nodes import Gaussian
   Y = Mixture(Z, Gaussian, mu, Lambda)
   Y.observe(y)
   Q = VB(Y, Z, A, a0)
   Q.update(repeat=1000)
   bpplt.pyplot.figure()
   bpplt.pyplot.axis('equal')
   colors = Y.parents[0].get_moments()[0]
   bpplt.pyplot.plot(y[:,0], y[:,1], 'k-', zorder=-10)
   bpplt.pyplot.scatter(y[:,0], y[:,1], c=colors, s=40)
   bpplt.pyplot.show()

The data has been classified quite correctly.  Even samples that are more in the
region of another cluster are classified correctly if the previous and next
sample provide enough evidence for the correct class.  We can also plot the
state transition matrix:

>>> bpplt.hinton(A)

.. plot::

   import numpy
   numpy.random.seed(1)
   from bayespy.nodes import CategoricalMarkovChain
   a0 = [0.6, 0.4] # p(rainy)=0.6, p(sunny)=0.4
   A = [[0.7, 0.3], # p(rainy->rainy)=0.7, p(rainy->sunny)=0.3
        [0.4, 0.6]] # p(sunny->rainy)=0.4, p(sunny->sunny)=0.6
   N = 100
   Z = CategoricalMarkovChain(a0, A, states=N)
   from bayespy.nodes import Categorical, Mixture
   P = [[0.1, 0.4, 0.5],
        [0.6, 0.3, 0.1]]
   Y = Mixture(Z, Categorical, P)
   weather = Z.random()
   from bayespy.inference import VB
   import bayespy.plot as bpplt
   import numpy as np
   mu = np.array([ [0,0], [3,4], [6,0] ])
   std = 2.0
   K = 3
   N = 200
   p0 = np.ones(K) / K
   q = 0.9
   r = (1-q)/(K-1)
   P = q*np.identity(K) + r*(np.ones((3,3))-np.identity(3))
   y = np.zeros((N,2))
   z = np.zeros(N)
   state = np.random.choice(K, p=p0)
   for n in range(N):
       z[n] = state
       y[n,:] = std*np.random.randn(2) + mu[state]
       state = np.random.choice(K, p=P[state])
   from bayespy.nodes import Dirichlet
   a0 = Dirichlet(1e-3*np.ones(K))
   A = Dirichlet(1e-3*np.ones((K,K)))
   Z = CategoricalMarkovChain(a0, A, states=N)
   Lambda = std**(-2) * np.identity(2)
   from bayespy.nodes import Gaussian
   Y = Mixture(Z, Gaussian, mu, Lambda)
   Y.observe(y)
   Q = VB(Y, Z, A, a0)
   Q.update(repeat=1000)
   bpplt.hinton(A)
   bpplt.pyplot.show()

Clearly, the learned state transition matrix is close to the true matrix.  The
models described above could also be used for classification by providing the
known class assignments as observed data to ``Z`` and the unknown class
assignments as missing data.