aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/timeseries/python/timeseries/state_space_models/kalman_filter_test.py
blob: 57f29f3c7f1a05ddf2cfb55eff174f0b2e274fe8 (plain)
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
421
422
423
424
425
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Kalman filtering."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy

from tensorflow.contrib.timeseries.python.timeseries import math_utils
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import kalman_filter

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test


# Two-dimensional state model with "slope" and "level" components.
STATE_TRANSITION = [
    [1., 1.],  # Add slope to level
    [0., 1.]   # Maintain slope
]
# Independent noise for each component
STATE_TRANSITION_NOISE = [[0.1, 0.0], [0.0, 0.2]]
OBSERVATION_MODEL = [[[0.5, 0.0], [0.0, 1.0]]]
OBSERVATION_NOISE = [[0.0001, 0.], [0., 0.0002]]
STATE_NOISE_TRANSFORM = [[1.0, 0.0], [0.0, 1.0]]


def _powers_and_sums_from_transition_matrix(
    state_transition, state_transition_noise_covariance,
    state_noise_transform, max_gap=1):
  def _transition_matrix_powers(powers):
    return math_utils.matrix_to_powers(state_transition, powers)
  def _power_sums(num_steps):
    power_sums_tensor = math_utils.power_sums_tensor(
        max_gap + 1, state_transition,
        math_ops.matmul(state_noise_transform,
                        math_ops.matmul(
                            state_transition_noise_covariance,
                            state_noise_transform,
                            adjoint_b=True)))
    return array_ops.gather(power_sums_tensor, indices=num_steps)
  return (_transition_matrix_powers, _power_sums)


class MultivariateTests(test.TestCase):

  def _multivariate_symmetric_covariance_test_template(
      self, dtype, simplified_posterior_variance_computation):
    """Check that errors aren't building up asymmetries in covariances."""
    kf = kalman_filter.KalmanFilter(dtype=dtype)
    observation_noise_covariance = constant_op.constant(
        [[1., 0.5], [0.5, 1.]], dtype=dtype)
    observation_model = constant_op.constant(
        [[[1., 0., 0., 0.], [0., 0., 1., 0.]]], dtype=dtype)
    state = array_ops.placeholder(shape=[1, 4], dtype=dtype)
    state_var = array_ops.placeholder(shape=[1, 4, 4], dtype=dtype)
    observation = array_ops.placeholder(shape=[1, 2], dtype=dtype)
    transition_fn, power_sum_fn = _powers_and_sums_from_transition_matrix(
        state_transition=constant_op.constant(
            [[1., 1., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 1.],
             [0., 0., 0., 1.]],
            dtype=dtype),
        state_noise_transform=linalg_ops.eye(4, dtype=dtype),
        state_transition_noise_covariance=constant_op.constant(
            [[1., 0., 0.5, 0.], [0., 1., 0., 0.5], [0.5, 0., 1., 0.],
             [0., 0.5, 0., 1.]],
            dtype=dtype))
    pred_state = kf.predict_state_mean(
        prior_state=state, transition_matrices=transition_fn([1]))
    pred_state_var = kf.predict_state_var(
        prior_state_var=state_var, transition_matrices=transition_fn([1]),
        transition_noise_sums=power_sum_fn([1]))
    observed_mean, observed_var = kf.observed_from_state(
        state_mean=pred_state, state_var=pred_state_var,
        observation_model=observation_model,
        observation_noise=observation_noise_covariance)
    post_state, post_state_var = kf.posterior_from_prior_state(
        prior_state=pred_state, prior_state_var=pred_state_var,
        observation=observation,
        observation_model=observation_model,
        predicted_observations=(observed_mean, observed_var),
        observation_noise=observation_noise_covariance)
    with self.test_session() as session:
      evaled_state = numpy.array([[1., 1., 1., 1.]])
      evaled_state_var = numpy.eye(4)[None]
      for i in range(500):
        evaled_state, evaled_state_var, evaled_observed_var = session.run(
            [post_state, post_state_var, observed_var],
            feed_dict={state: evaled_state,
                       state_var: evaled_state_var,
                       observation: [[float(i), float(i)]]})
        self.assertAllClose(evaled_observed_var[0],
                            evaled_observed_var[0].T)
        self.assertAllClose(evaled_state_var[0],
                            evaled_state_var[0].T)

  def test_multivariate_symmetric_covariance_float32(self):
    self._multivariate_symmetric_covariance_test_template(
        dtypes.float32, simplified_posterior_variance_computation=False)

  def test_multivariate_symmetric_covariance_float64(self):
    self._multivariate_symmetric_covariance_test_template(
        dtypes.float64, simplified_posterior_variance_computation=True)


class KalmanFilterNonBatchTest(test.TestCase):
  """Single-batch KalmanFilter tests."""

  def setUp(self):
    """The basic model defined above, with unit batches."""
    self.kalman_filter = kalman_filter.KalmanFilter()
    self.transition_fn, self.power_sum_fn = (
        _powers_and_sums_from_transition_matrix(
            state_transition=STATE_TRANSITION,
            state_transition_noise_covariance=STATE_TRANSITION_NOISE,
            state_noise_transform=STATE_NOISE_TRANSFORM,
            max_gap=5))

  def test_observed_from_state(self):
    """Compare observation mean and noise to hand-computed values."""
    with self.test_session():
      state = constant_op.constant([[2., 1.]])
      state_var = constant_op.constant([[[4., 0.], [0., 3.]]])
      observed_mean, observed_var = self.kalman_filter.observed_from_state(
          state, state_var,
          observation_model=OBSERVATION_MODEL,
          observation_noise=OBSERVATION_NOISE)
      observed_mean_override, observed_var_override = (
          self.kalman_filter.observed_from_state(
              state, state_var,
              observation_model=OBSERVATION_MODEL,
              observation_noise=100 * constant_op.constant(
                  OBSERVATION_NOISE)[None]))
      self.assertAllClose(numpy.array([[1., 1.]]),
                          observed_mean.eval())
      self.assertAllClose(numpy.array([[1., 1.]]),
                          observed_mean_override.eval())
      self.assertAllClose(numpy.array([[[1.0001, 0.], [0., 3.0002]]]),
                          observed_var.eval())
      self.assertAllClose(numpy.array([[[1.01, 0.], [0., 3.02]]]),
                          observed_var_override.eval())

  def _posterior_from_prior_state_test_template(
      self, state, state_var, observation, observation_model, observation_noise,
      expected_state, expected_state_var):
    """Test that repeated observations converge to the expected value."""
    predicted_observations = self.kalman_filter.observed_from_state(
        state, state_var, observation_model,
        observation_noise=observation_noise)
    state_update, state_var_update = (
        self.kalman_filter.posterior_from_prior_state(
            state, state_var, observation,
            observation_model=observation_model,
            predicted_observations=predicted_observations,
            observation_noise=observation_noise))
    with self.test_session() as session:
      evaled_state, evaled_state_var = session.run([state, state_var])
      for _ in range(300):
        evaled_state, evaled_state_var = session.run(
            [state_update, state_var_update],
            feed_dict={state: evaled_state, state_var: evaled_state_var})
    self.assertAllClose(expected_state,
                        evaled_state,
                        atol=1e-5)
    self.assertAllClose(
        expected_state_var,
        evaled_state_var,
        atol=1e-5)

  def test_posterior_from_prior_state_univariate(self):
    self._posterior_from_prior_state_test_template(
        state=constant_op.constant([[0.3]]),
        state_var=constant_op.constant([[[1.]]]),
        observation=constant_op.constant([[1.]]),
        observation_model=[[[2.]]],
        observation_noise=[[[0.01]]],
        expected_state=numpy.array([[0.5]]),
        expected_state_var=[[[0.]]])

  def test_posterior_from_prior_state_univariate_unit_noise(self):
    self._posterior_from_prior_state_test_template(
        state=constant_op.constant([[0.3]]),
        state_var=constant_op.constant([[[1e10]]]),
        observation=constant_op.constant([[1.]]),
        observation_model=[[[2.]]],
        observation_noise=[[[1.0]]],
        expected_state=numpy.array([[0.5]]),
        expected_state_var=[[[1. / (300. * 2. ** 2)]]])

  def test_posterior_from_prior_state_multivariate_2d(self):
    self._posterior_from_prior_state_test_template(
        state=constant_op.constant([[1.9, 1.]]),
        state_var=constant_op.constant([[[1., 0.], [0., 2.]]]),
        observation=constant_op.constant([[1., 1.]]),
        observation_model=OBSERVATION_MODEL,
        observation_noise=OBSERVATION_NOISE,
        expected_state=numpy.array([[2., 1.]]),
        expected_state_var=[[[0., 0.], [0., 0.]]])

  def test_posterior_from_prior_state_multivariate_3d(self):
    self._posterior_from_prior_state_test_template(
        state=constant_op.constant([[1.9, 1., 5.]]),
        state_var=constant_op.constant(
            [[[200., 0., 1.], [0., 2000., 0.], [1., 0., 40000.]]]),
        observation=constant_op.constant([[1., 1., 3.]]),
        observation_model=constant_op.constant(
            [[[0.5, 0., 0.],
              [0., 10., 0.],
              [0., 0., 100.]]]),
        observation_noise=linalg_ops.eye(3) / 10000.,
        expected_state=numpy.array([[2., .1, .03]]),
        expected_state_var=numpy.zeros([1, 3, 3]))

  def test_predict_state_mean(self):
    """Compare state mean transitions with simple hand-computed values."""
    with self.test_session():
      state = constant_op.constant([[4., 2.]])
      state = self.kalman_filter.predict_state_mean(
          state, self.transition_fn([1]))
      for _ in range(2):
        state = self.kalman_filter.predict_state_mean(
            state, self.transition_fn([1]))
      self.assertAllClose(
          numpy.array([[2. * 3. + 4.,  # Slope * time + base
                        2.]]),
          state.eval())

  def test_predict_state_var(self):
    """Compare a variance transition with simple hand-computed values."""
    with self.test_session():
      state_var = constant_op.constant([[[1., 0.], [0., 2.]]])
      state_var = self.kalman_filter.predict_state_var(
          state_var, self.transition_fn([1]), self.power_sum_fn([1]))
      self.assertAllClose(
          numpy.array([[[3.1, 2.0], [2.0, 2.2]]]),
          state_var.eval())

  def test_do_filter(self):
    """Tests do_filter.

    Tests that correct values have high probability and incorrect values
    have low probability when there is low uncertainty.
    """
    with self.test_session():
      state = constant_op.constant([[4., 2.]])
      state_var = constant_op.constant([[[0.0001, 0.], [0., 0.0001]]])
      observation = constant_op.constant([[
          .5 * (
              4.  # Base
              + 2.),  # State transition
          2.
      ]])
      estimated_state = self.kalman_filter.predict_state_mean(
          state, self.transition_fn([1]))
      estimated_state_covariance = self.kalman_filter.predict_state_var(
          state_var, self.transition_fn([1]), self.power_sum_fn([1]))
      (predicted_observation,
       predicted_observation_covariance) = (
           self.kalman_filter.observed_from_state(
               estimated_state, estimated_state_covariance,
               observation_model=OBSERVATION_MODEL,
               observation_noise=OBSERVATION_NOISE))
      (_, _, first_log_prob) = self.kalman_filter.do_filter(
          estimated_state=estimated_state,
          estimated_state_covariance=estimated_state_covariance,
          predicted_observation=predicted_observation,
          predicted_observation_covariance=predicted_observation_covariance,
          observation=observation,
          observation_model=OBSERVATION_MODEL,
          observation_noise=OBSERVATION_NOISE)
      self.assertGreater(first_log_prob.eval()[0], numpy.log(0.99))

  def test_predict_n_ahead_mean(self):
    with self.test_session():
      original_state = constant_op.constant([[4., 2.]])
      n = 5
      iterative_state = original_state
      for i in range(n):
        self.assertAllClose(
            iterative_state.eval(),
            self.kalman_filter.predict_state_mean(
                original_state,
                self.transition_fn([i])).eval())
        iterative_state = self.kalman_filter.predict_state_mean(
            iterative_state,
            self.transition_fn([1]))

  def test_predict_n_ahead_var(self):
    with self.test_session():
      original_var = constant_op.constant([[[2., 3.], [4., 5.]]])
      n = 5
      iterative_var = original_var
      for i in range(n):
        self.assertAllClose(
            iterative_var.eval(),
            self.kalman_filter.predict_state_var(
                original_var,
                self.transition_fn([i]),
                self.power_sum_fn([i])).eval())
        iterative_var = self.kalman_filter.predict_state_var(
            iterative_var,
            self.transition_fn([1]),
            self.power_sum_fn([1]))


class KalmanFilterBatchTest(test.TestCase):
  """KalmanFilter tests with more than one element batches."""

  def test_do_filter_batch(self):
    """Tests do_filter, in batch mode.

    Tests that correct values have high probability and incorrect values
    have low probability when there is low uncertainty.
    """
    with self.test_session():
      state = constant_op.constant([[4., 2.], [5., 3.], [6., 4.]])
      state_var = constant_op.constant(3 * [[[0.0001, 0.], [0., 0.0001]]])
      observation = constant_op.constant([
          [
              .5 * (
                  4.  # Base
                  + 2.),  # State transition
              2.
          ],
          [
              .5 * (
                  5.  # Base
                  + 3.),  # State transition
              3.
          ],
          [3.14, 2.71]
      ])  # Low probability observation
      kf = kalman_filter.KalmanFilter()
      transition_fn, power_sum_fn = _powers_and_sums_from_transition_matrix(
          state_transition=STATE_TRANSITION,
          state_transition_noise_covariance=STATE_TRANSITION_NOISE,
          state_noise_transform=STATE_NOISE_TRANSFORM,
          max_gap=2)
      estimated_state = kf.predict_state_mean(state, transition_fn(3*[1]))
      estimated_state_covariance = kf.predict_state_var(
          state_var, transition_fn(3*[1]), power_sum_fn(3*[1]))
      observation_model = array_ops.tile(OBSERVATION_MODEL, [3, 1, 1])
      (predicted_observation,
       predicted_observation_covariance) = (
           kf.observed_from_state(
               estimated_state, estimated_state_covariance,
               observation_model=observation_model,
               observation_noise=OBSERVATION_NOISE))
      (state, state_var, log_prob) = kf.do_filter(
          estimated_state=estimated_state,
          estimated_state_covariance=estimated_state_covariance,
          predicted_observation=predicted_observation,
          predicted_observation_covariance=predicted_observation_covariance,
          observation=observation,
          observation_model=observation_model,
          observation_noise=OBSERVATION_NOISE)
      first_log_prob, second_log_prob, third_log_prob = log_prob.eval()
      self.assertGreater(first_log_prob.sum(), numpy.log(0.99))
      self.assertGreater(second_log_prob.sum(), numpy.log(0.99))
      self.assertLess(third_log_prob.sum(), numpy.log(0.01))

  def test_predict_n_ahead_mean(self):
    with self.test_session():
      kf = kalman_filter.KalmanFilter()
      transition_fn, _ = _powers_and_sums_from_transition_matrix(
          state_transition=STATE_TRANSITION,
          state_transition_noise_covariance=STATE_TRANSITION_NOISE,
          state_noise_transform=STATE_NOISE_TRANSFORM,
          max_gap=2)
      original_state = constant_op.constant([[4., 2.], [3., 1.], [6., 2.]])
      state0 = original_state
      state1 = kf.predict_state_mean(state0, transition_fn(3 * [1]))
      state2 = kf.predict_state_mean(state1, transition_fn(3 * [1]))
      batch_eval = kf.predict_state_mean(
          original_state, transition_fn([1, 0, 2])).eval()
      self.assertAllClose(state0.eval()[1], batch_eval[1])
      self.assertAllClose(state1.eval()[0], batch_eval[0])
      self.assertAllClose(state2.eval()[2], batch_eval[2])

  def test_predict_n_ahead_var(self):
    with self.test_session():
      kf = kalman_filter.KalmanFilter()
      transition_fn, power_sum_fn = _powers_and_sums_from_transition_matrix(
          state_transition=STATE_TRANSITION,
          state_transition_noise_covariance=STATE_TRANSITION_NOISE,
          state_noise_transform=STATE_NOISE_TRANSFORM,
          max_gap=2)
      base_var = 2.0 * numpy.identity(2) + numpy.ones([2, 2])
      original_var = constant_op.constant(
          numpy.array(
              [base_var, 2.0 * base_var, 3.0 * base_var], dtype=numpy.float32))
      var0 = original_var
      var1 = kf.predict_state_var(
          var0, transition_fn(3 * [1]), power_sum_fn(3 * [1]))
      var2 = kf.predict_state_var(
          var1, transition_fn(3 * [1]), power_sum_fn(3 * [1]))
      batch_eval = kf.predict_state_var(
          original_var,
          transition_fn([1, 0, 2]),
          power_sum_fn([1, 0, 2])).eval()
      self.assertAllClose(var0.eval()[1], batch_eval[1])
      self.assertAllClose(var1.eval()[0], batch_eval[0])
      self.assertAllClose(var2.eval()[2], batch_eval[2])


if __name__ == "__main__":
  test.main()