-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
kalman_filter.py
1399 lines (1243 loc) · 51.1 KB
/
kalman_filter.py
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Kalman Filter Transformers.
Series based transformers, based on Kalman Filter algorithm. Contains Base class and two
transformers which are each Adapters for external packages pykalman and FilterPy.
"""
__author__ = ["NoaBenAmi", "lielleravid"]
__all__ = [
"BaseKalmanFilter",
"KalmanFilterTransformerPK",
"KalmanFilterTransformerFP",
]
import numpy as np
from sktime.transformations.base import BaseTransformer
from sktime.utils.validation._dependencies import _check_soft_dependencies
from sktime.utils.warnings import warn
def _get_t_matrix(time_t, matrices, shape, time_steps):
"""Extract matrix to be used at iteration ``time_t`` of Kalman filter iterations.
Parameters
----------
time_t : int
The required time step.
matrices : np.ndarray
shape : tuple
The shape of a single matrix.
time_steps : int
Number of iterations.
Returns
-------
matrix : np.ndarray
matrix to be used at iteration ``time_t``
"""
matrices = np.asarray(matrices)
if matrices.shape == shape:
return matrices
if matrices.shape == (time_steps, *shape):
return matrices[time_t]
raise ValueError(
f"Shape of `matrices` {matrices.shape}, does not match single matrix"
f"`shape` {shape}, nor shape of list of matrices {(time_steps, *shape)}."
)
def _validate_param_shape(param_name, matrix_shape, actual_shape, time_steps=None):
"""Validate shape of matrix parameter.
Assert ``actual_shape`` equals to:
- 'shape' of a single matrix or
- 'shape' of time_steps matrices.
If neither, raise an informative ``ValueError`` that includes the parameter's name.
Parameters
----------
param_name : str
The name of the matrix-parameter.
matrix_shape : tuple
The supposed shape of a single matrix.
actual_shape : tuple
The actual shape of matrix-parameter.
time_steps : int
actual_shape[0] if matrix-parameter is dynamic (matrix per time-step).
Raises
------
ValueError
error with an informative message that includes parameter's name,
and the shape that parameter should have.
"""
if time_steps is None:
if actual_shape != matrix_shape:
raise ValueError(
f"Shape of parameter `{param_name}` is: {actual_shape}, "
f"but should be: {matrix_shape}."
)
else:
matrices_shape = (time_steps, *matrix_shape)
if not (actual_shape == matrix_shape or actual_shape == matrices_shape):
raise ValueError(
f"Shape of parameter `{param_name}` is: {actual_shape}, but should be: "
f"{matrix_shape} or {matrices_shape}."
)
def _init_matrix(matrices, transform_func, default_val):
"""Initialize default value if matrix is None, or transform to np.ndarray.
Parameters
----------
matrices : np.ndarray
transform_func : transformation function from array-like to ndarray
default_val : np.ndarray
Returns
-------
transformed_matrices : np.ndarray
matrices as np.ndarray
"""
if matrices is None:
return default_val
return transform_func(matrices)
def _check_conditional_dependency(
obj, condition, package, severity, package_import_alias=None, msg=None
):
"""If ``condition`` applies, check the soft dependency ``package`` installation.
Call _check_soft_dependencies.
If ``package`` is not installed, raise ModuleNotFoundError with
``msg`` as the error message.
Parameters
----------
condition : bool
The condition to perform the soft dependency check.
msg : str
Error message to attach to ModuleNotFoundError.
package : str
Package name for soft dependency check.
package_import_alias : dict with str keys and values or None, optional, default=None
import name is str used in python import, i.e., from import_name import ...
should be provided if import name differs from package name
severity : str
'error' or 'warning'.
Raises
------
ModuleNotFoundError
error with informative message, asking to install required soft dependencies
"""
if condition:
if msg is None:
msg = (
f"The specific parameter values of {obj.__class__.__name__}'s "
f"class instance require `{package}` installed. Please run: "
f"`pip install {package}` to "
f"install the `{package}` package. "
)
try:
_check_soft_dependencies(
package,
package_import_alias=package_import_alias,
severity=severity,
obj=obj,
)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(msg) from e
def _validate_estimate_matrices(input_ems, all_ems):
"""Validate elements of ``estimate_matrices``.
Parameters
----------
input_ems : str or list of str
List of matrices names or "all"
all_ems : List of str
List of all legal parameters.
Returns
-------
em_vars : list
Legal parameters names
"""
if isinstance(input_ems, str):
if input_ems == "all":
return all_ems
if input_ems in all_ems:
return list([input_ems])
raise ValueError(
f"If `estimate_matrices` is passed as a "
f"string, "
f"it must be `all` / one of: "
f"{all_ems}, but found: "
f"{input_ems}"
)
for em in input_ems:
if em not in all_ems:
raise ValueError(
f"Elements of `estimate_matrices` "
f"must be a subset of "
f"{all_ems}, but found: "
f"{em}"
)
return input_ems
class BaseKalmanFilter:
"""Kalman Filter is used for denoising data, or inferring the hidden state of data.
Note - this class is a base class and should not be used directly.
The Kalman filter is an unsupervised algorithm consisting of
several mathematical equations which are used to create
an estimate of the state of a process.
The algorithm does this efficiently and recursively in a
way where the mean squared error is minimal.
The Kalman Filter has the ability to support estimations
of past, present and future states.
The strength of the Kalman Filter is in its ability to
infer the state of a system even when the exact nature of the
system is not known.
When given time series data, the Kalman filter creates a denoising effect
by removing noise from the data, and recovering the true
state of the underlying object we are tracking within the
data.
The Kalman Filter computations are based on five equations.
Two prediction equations:
- State Extrapolation Equation - prediction or estimation of the future state,
based on the known present estimation.
- Covariance Extrapolation Equation - the measure of uncertainty in our prediction.
Two update equations:
- State Update Equation - estimation of the current state,
based on the known past estimation and present measurement.
- Covariance Update Equation - the measure of uncertainty in our estimation.
Kalman Gain Equation - this is a required argument for the update equations.
It acts as a weighting parameter for the past estimations and the given measurement.
It defines the weight of the past estimation and
the weight of the measurement in estimating the current state.
Parameters
----------
state_dim : int
System state feature dimension
state_transition : np.ndarray, optional (default=None)
of shape (state_dim, state_dim) or (time_steps, state_dim, state_dim).
State transition matrix, also referred to as F, is a matrix
which describes the way the underlying series moves
through successive time periods.
process_noise : np.ndarray, optional (default=None)
of shape (state_dim, state_dim) or (time_steps, state_dim, state_dim).
Process noise matrix, also referred to as Q,
the uncertainty of the dynamic model.
measurement_noise : np.ndarray, optional (default=None)
of shape (measurement_dim, measurement_dim) or
(time_steps, measurement_dim, measurement_dim).
Measurement noise matrix, also referred to as R,
represents the uncertainty of the measurements.
measurement_function : np.ndarray, optional (default=None)
of shape (measurement_dim, state_dim) or
(time_steps, measurement_dim, state_dim).
Measurement equation matrix, also referred to as H, adjusts
dimensions of measurements to match dimensions of state.
initial_state : np.ndarray, optional (default=None)
of shape (state_dim,).
Initial estimated system state, also referred to as x0.
initial_state_covariance : np.ndarray, optional (default=None)
of shape (state_dim, state_dim).
Initial estimated system state covariance, also referred to as P0.
References
----------
.. [1] Greg Welch and Gary Bishop, "An Introduction to the Kalman Filter", 2006
https://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf
.. [2] R.H.Shumway and D.S.Stoffer "An Approach to time
Series Smoothing and Forecasting Using the EM Algorithm", 1982
https://www.stat.pitt.edu/stoffer/dss_files/em.pdf
"""
_tags = {"authors": ["NoaBenAmi", "lielleravid"], "maintainers": ["NoaBenAmi"]}
def __init__(
self,
state_dim,
state_transition=None,
process_noise=None,
measurement_noise=None,
measurement_function=None,
initial_state=None,
initial_state_covariance=None,
):
self.state_dim = state_dim
# F/A
self.state_transition = state_transition
# Q
self.process_noise = process_noise
# R
self.measurement_noise = measurement_noise
# H/C
self.measurement_function = measurement_function
# X0
self.initial_state = initial_state
# P0
self.initial_state_covariance = initial_state_covariance
super().__init__()
def _get_shapes(self, state_dim, measurement_dim):
"""Return dictionary with default shape of each matrix parameter.
Parameters
----------
state_dim : int
Dimension of ``state``.
measurement_dim : int
Dimension of measurements.
Returns
-------
shapes : dict
Dictionary with default shape of each matrix parameter
"""
shapes = {
"F": (state_dim, state_dim),
"Q": (state_dim, state_dim),
"R": (measurement_dim, measurement_dim),
"H": (measurement_dim, state_dim),
"X0": (state_dim,),
"P0": (state_dim, state_dim),
}
return shapes
def _get_init_values(self, measurement_dim, state_dim):
"""Initialize matrix parameters to default values and returns them.
Parameters
----------
measurement_dim : int
state_dim : int
Returns
-------
Six matrix parameters F,Q,R,H,X0,P0 as np.ndarray
"""
shapes = self._get_shapes(state_dim=state_dim, measurement_dim=measurement_dim)
F = _init_matrix(
matrices=self.state_transition,
transform_func=np.atleast_2d,
default_val=np.eye(*shapes["F"]),
)
Q = _init_matrix(
matrices=self.process_noise,
transform_func=np.atleast_2d,
default_val=np.eye(*shapes["Q"]),
)
R = _init_matrix(
matrices=self.measurement_noise,
transform_func=np.atleast_2d,
default_val=np.eye(*shapes["R"]),
)
H = _init_matrix(
matrices=self.measurement_function,
transform_func=np.atleast_2d,
default_val=np.eye(*shapes["H"]),
)
X0 = _init_matrix(
matrices=self.initial_state,
transform_func=np.atleast_1d,
default_val=np.zeros(*shapes["X0"]),
)
P0 = _init_matrix(
matrices=self.initial_state_covariance,
transform_func=np.atleast_2d,
default_val=np.eye(*shapes["P0"]),
)
return F, Q, R, H, X0, P0
def _set_attribute(
self, param_name, attr_name, value, matrix_shape, time_steps=None
):
"""Validate the shape of parameter and set as attribute if no error.
Parameters
----------
param_name : str
The name of matrix-parameter.
attr_name : str
The name of corresponding attribute.
value : np.ndarray
The value of corresponding attribute.
matrix_shape : tuple
The supposed shape of a single matrix.
time_steps : int, optional (default=None)
"""
_validate_param_shape(
param_name=param_name,
matrix_shape=matrix_shape,
actual_shape=value.shape,
time_steps=time_steps,
)
setattr(self, attr_name, value)
class KalmanFilterTransformerPK(BaseKalmanFilter, BaseTransformer):
"""Kalman Filter is used for denoising data, or inferring the hidden state of data.
The Kalman Filter is an unsupervised algorithm, consisting of
several mathematical equations which are used to create
an estimate of the state of a process.
This class is the adapter for the ``pykalman`` package into ``sktime``.
``KalmanFilterTransformerPK`` implements hidden inferred states and
denoising, depending on the boolean input parameter ``denoising``.
In addition, ``KalmanFilterTransformerPK`` provides parameter
optimization via Expectation-Maximization (EM) algorithm [2]_,
implemented by ``pykalman``.
Parameters
----------
state_dim : int
System state feature dimension.
state_transition : np.ndarray, optional (default=None)
of shape (state_dim, state_dim) or (time_steps, state_dim, state_dim).
State transition matrix, also referred to as ``F``, is a matrix
which describes the way the underlying series moves
through successive time periods.
process_noise : np.ndarray, optional (default=None)
of shape (state_dim, state_dim) or
(time_steps, state_dim, state_dim).
Process noise matrix, also referred to as ``Q``,
the uncertainty of the dynamic model.
measurement_noise : np.ndarray, optional (default=None)
of shape (measurement_dim, measurement_dim) or
(time_steps, measurement_dim, measurement_dim).
Measurement noise matrix, also referred to as ``R``,
represents the uncertainty of the measurements.
measurement_function : np.ndarray, optional (default=None)
of shape (measurement_dim, state_dim) or
(time_steps, measurement_dim, state_dim).
Measurement equation matrix, also referred to as ``H``, adjusts
dimensions of measurements to match dimensions of state.
initial_state : np.ndarray, optional (default=None)
of shape (state_dim,).
Initial estimated system state, also referred to as ``X0``.
initial_state_covariance : np.ndarray, optional (default=None)
of shape (state_dim, state_dim).
Initial estimated system state covariance, also referred to as ``P0``.
transition_offsets : np.ndarray, optional (default=None)
of shape (state_dim,) or (time_steps, state_dim).
State offsets, also referred to as ``b``, as described in ``pykalman``.
measurement_offsets : np.ndarray, optional (default=None)
of shape (measurement_dim,) or (time_steps, measurement_dim).
Observation (measurement) offsets, also referred to as ``d``,
as described in ``pykalman``.
denoising : bool, optional (default=False).
This parameter affects ``transform``. If False, then ``transform`` will be
inferring
hidden state. If True, uses ``pykalman`` ``smooth`` for denoising.
estimate_matrices : str or list of str, optional (default=None).
Subset of [``state_transition``, ``measurement_function``,
``process_noise``, ``measurement_noise``, ``initial_state``,
``initial_state_covariance``, ``transition_offsets``, ``measurement_offsets``]
or - ``all``. If ``estimate_matrices`` is an iterable of strings,
only matrices in ``estimate_matrices`` will be estimated using EM algorithm,
like described in ``pykalman``. If ``estimate_matrices`` is ``all``,
then all matrices will be estimated using EM algorithm.
Note - parameters estimated by EM algorithm assumed to be constant.
See Also
--------
KalmanFilterTransformerFP :
Kalman Filter transformer, adapter for the ``FilterPy`` package into ``sktime``.
Notes
-----
``pykalman`` KalmanFilter documentation :
https://pykalman.github.io/#kalmanfilter
References
----------
.. [1] Greg Welch and Gary Bishop, "An Introduction to the Kalman Filter", 2006
https://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf
.. [2] R.H.Shumway and D.S.Stoffer "An Approach to time
Series Smoothing and Forecasting Using the EM Algorithm", 1982
https://www.stat.pitt.edu/stoffer/dss_files/em.pdf
Examples
--------
Basic example:
>>> import numpy as np # doctest: +SKIP
>>> import sktime.transformations.series.kalman_filter as kf
>>> time_steps, state_dim, measurement_dim = 10, 2, 3
>>>
>>> X = np.random.rand(time_steps, measurement_dim) * 10
>>> transformer = kf.KalmanFilterTransformerPK(state_dim=state_dim) # doctest: +SKIP
>>> X_transformed = transformer.fit_transform(X=X) # doctest: +SKIP
Example of - denoising, matrix estimation and missing values:
>>> import numpy as np # doctest: +SKIP
>>> import sktime.transformations.series.kalman_filter as kf
>>> time_steps, state_dim, measurement_dim = 10, 2, 2
>>>
>>> X = np.random.rand(time_steps, measurement_dim)
>>> # missing value
>>> X[0][0] = np.nan
>>>
>>> # If matrices estimation is required, elements of ``estimate_matrices``
>>> # are assumed to be constants.
>>> transformer = kf.KalmanFilterTransformerPK( # doctest: +SKIP
... state_dim=state_dim,
... measurement_noise=np.eye(measurement_dim),
... denoising=True,
... estimate_matrices=['measurement_noise']
... )
>>>
>>> X_transformed = transformer.fit_transform(X=X) # doctest: +SKIP
Example of - dynamic inputs (matrix per time-step) and missing values:
>>> import numpy as np # doctest: +SKIP
>>> import sktime.transformations.series.kalman_filter as kf
>>> time_steps, state_dim, measurement_dim = 10, 4, 4
>>>
>>> X = np.random.rand(time_steps, measurement_dim)
>>> # missing values
>>> X[0] = [np.NaN for i in range(measurement_dim)]
>>>
>>> # Dynamic input -
>>> # ``state_transition`` provide different matrix for each time step.
>>> transformer = kf.KalmanFilterTransformerPK( # doctest: +SKIP
... state_dim=state_dim,
... state_transition=np.random.rand(time_steps, state_dim, state_dim),
... estimate_matrices=['initial_state', 'initial_state_covariance']
... )
>>>
>>> X_transformed = transformer.fit_transform(X=X) # doctest: +SKIP
"""
_tags = {
# packaging info
# --------------
"authors": ["NoaBenAmi", "lielleravid"],
"maintainers": ["NoaBenAmi"],
"python_dependencies": "pykalman",
# estimator type
# --------------
"X_inner_mtype": "np.ndarray", # which mtypes do _fit/_predict support for X?
"requires_y": False, # does y need to be passed in fit?
"fit_is_empty": False, # is fit empty and can be skipped? Yes = True
"capability:unequal_length": False,
# can the transformer handle unequal length time series (if passed Panel)?
"handles-missing-data": True, # can estimator handle missing data?
"capability:missing_values:removes": False,
# is transform result always guaranteed to contain no missing values?
"scitype:instancewise": True, # is this an instance-wise transform?
}
def __init__(
self,
state_dim,
state_transition=None,
transition_offsets=None,
measurement_offsets=None,
process_noise=None,
measurement_noise=None,
measurement_function=None,
initial_state=None,
initial_state_covariance=None,
estimate_matrices=None,
denoising=False,
):
super().__init__(
state_dim=state_dim,
state_transition=state_transition,
process_noise=process_noise,
measurement_noise=measurement_noise,
measurement_function=measurement_function,
initial_state=initial_state,
initial_state_covariance=initial_state_covariance,
)
# b
self.transition_offsets = transition_offsets
# d
self.measurement_offsets = measurement_offsets
self.estimate_matrices = estimate_matrices
self.denoising = denoising
def _fit(self, X, y=None):
"""Fit transformer to X and y.
This method prepares the transformer.
The matrix initializations or estimations
(if requested by user) are calculated here.
Parameters
----------
X : np.ndarray
of shape (time_steps, measurement_dim).
Data (measurements) to be transformed.
Missing values must be represented as np.NaN or np.nan.
y : ignored argument for interface compatibility
Returns
-------
self: reference to self
"""
measurement_dim = X.shape[1]
time_steps = X.shape[0]
shapes = self._get_shapes(
state_dim=self.state_dim, measurement_dim=measurement_dim
)
if self.estimate_matrices is None:
(F_, Q_, R_, H_, X0_, P0_) = self._get_init_values(
measurement_dim, self.state_dim
)
transition_offsets_ = _init_matrix(
matrices=self.transition_offsets,
transform_func=np.atleast_1d,
default_val=np.zeros(*shapes["b"]),
)
measurement_offsets_ = _init_matrix(
matrices=self.measurement_offsets,
transform_func=np.atleast_1d,
default_val=np.zeros(*shapes["d"]),
)
else:
(
F_,
H_,
Q_,
R_,
transition_offsets_,
measurement_offsets_,
X0_,
P0_,
) = self._em(X=X, measurement_dim=measurement_dim, state_dim=self.state_dim)
self._set_attribute(
param_name="state_transition",
attr_name="F_",
value=F_,
matrix_shape=shapes["F"],
time_steps=time_steps,
)
self._set_attribute(
param_name="process_noise",
attr_name="Q_",
value=Q_,
matrix_shape=shapes["Q"],
time_steps=time_steps,
)
self._set_attribute(
param_name="measurement_noise",
attr_name="R_",
value=R_,
matrix_shape=shapes["R"],
time_steps=time_steps,
)
self._set_attribute(
param_name="measurement_function",
attr_name="H_",
value=H_,
matrix_shape=shapes["H"],
time_steps=time_steps,
)
self._set_attribute(
param_name="initial_state",
attr_name="X0_",
value=X0_,
matrix_shape=shapes["X0"],
)
self._set_attribute(
param_name="initial_state_covariance",
attr_name="P0_",
value=P0_,
matrix_shape=shapes["P0"],
)
_validate_param_shape(
param_name="transition_offsets",
matrix_shape=shapes["b"],
actual_shape=transition_offsets_.shape,
time_steps=time_steps,
)
self.transition_offsets_ = np.copy(transition_offsets_)
_validate_param_shape(
param_name="measurement_offsets",
matrix_shape=shapes["d"],
actual_shape=measurement_offsets_.shape,
time_steps=time_steps,
)
self.measurement_offsets_ = np.copy(measurement_offsets_)
return self
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
This method performs the transformation of the input data
according to the constructor input parameter ``denoising``.
If ``denoising`` is True - then denoise data using
``pykalman``'s ``smooth`` function.
Else, infer hidden state using ``pykalman``'s ``filter`` function.
Parameters
----------
X : np.ndarray
of shape (time_steps, measurement_dim).
Data (measurements) to be transformed.
Missing values must be represented as np.NaN or np.nan.
y : ignored argument for interface compatibility
Returns
-------
X_transformed : np.ndarray
transformed version of X
"""
from pykalman import KalmanFilter
X_masked = np.ma.masked_invalid(X)
kf = KalmanFilter(
transition_matrices=self.F_,
observation_matrices=self.H_,
transition_covariance=self.Q_,
observation_covariance=self.R_,
transition_offsets=self.transition_offsets_,
observation_offsets=self.measurement_offsets_,
initial_state_mean=self.X0_,
initial_state_covariance=self.P0_,
)
if self.denoising:
(state_means, state_covariances) = kf.smooth(X_masked)
else:
(state_means, state_covariances) = kf.filter(X_masked)
return state_means
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return ``"default"`` set.
There are currently no reserved values for transformers.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
``MyClass(**params)`` or ``MyClass(**params[i])`` creates a valid test
instance.
``create_test_instance`` uses the first (or only) dictionary in ``params``
"""
params1 = {"state_dim": 2}
params2 = {
"state_dim": 2,
"initial_state": np.array([0, 0]),
"initial_state_covariance": np.array([[0.1, 0], [0.1, 0]]),
"state_transition": np.array([[1, 0.1], [0, 1]]),
"process_noise": np.array(
[
[1 / 4 * (0.1**4), 1 / 2 * (0.1**3)],
[1 / 2 * (0.1**3), 0.1**2],
]
)
* 0.1,
"denoising": True,
"estimate_matrices": ["measurement_noise"],
}
return [params1, params2]
def _em(self, X, measurement_dim, state_dim):
"""Estimate matrices algorithm if requested by user.
If input matrices are specified in ``estimate_matrices``,
this method will use the ``pykalman`` EM algorithm function
to estimate said matrices needed to calculate the Kalman Filter.
Algorithm explained in References[2].
If ``estimate_matrices`` is None no matrices will be estimated.
Parameters
----------
X : np.ndarray
of shape (time_steps, measurement_dim).
Data (measurements). Missing values must be represented as np.NaN or np.nan.
measurement_dim : int
Measurement feature dimensions.
state_dim : int
``state`` feature dimensions.
Returns
-------
Eight matrix parameters -
F, H, Q, R, transition_offsets, measurement_offsets,
X0, P0 as np.ndarray.
"""
from pykalman import KalmanFilter
X_masked = np.ma.masked_invalid(X)
estimate_matrices_ = self._get_estimate_matrices()
kf = KalmanFilter(
transition_matrices=self.state_transition,
observation_matrices=self.measurement_function,
transition_covariance=self.process_noise,
observation_covariance=self.measurement_noise,
transition_offsets=self.transition_offsets,
observation_offsets=self.measurement_offsets,
initial_state_mean=self.initial_state,
initial_state_covariance=self.initial_state_covariance,
n_dim_obs=measurement_dim,
n_dim_state=state_dim,
)
kf = kf.em(X=X_masked, em_vars=estimate_matrices_)
F = kf.transition_matrices
H = kf.observation_matrices
Q = kf.transition_covariance
R = kf.observation_covariance
transition_offsets = kf.transition_offsets
measurement_offsets = kf.observation_offsets
X0 = kf.initial_state_mean
P0 = kf.initial_state_covariance
return F, H, Q, R, transition_offsets, measurement_offsets, X0, P0
def _get_estimate_matrices(self):
"""Map parameter names to ``pykalman`` names for use of ``em``.
Returns
-------
em_vars : list
mapped parameters names
"""
params_mapping = {
"state_transition": "transition_matrices",
"process_noise": "transition_covariance",
"measurement_offsets": "observation_offsets",
"transition_offsets": "transition_offsets",
"measurement_noise": "observation_covariance",
"measurement_function": "observation_matrices",
"initial_state": "initial_state_mean",
"initial_state_covariance": "initial_state_covariance",
}
valid_ems = _validate_estimate_matrices(
input_ems=self.estimate_matrices, all_ems=list(params_mapping.keys())
)
em_vars = [params_mapping[em_var] for em_var in valid_ems]
return em_vars
def _get_shapes(self, state_dim, measurement_dim):
"""Return a dictionary with default shape of each matrix parameter.
Parameters
----------
state_dim : int
``state`` feature dimensions.
measurement_dim : int
Measurement (data) feature dimensions.
Returns
-------
Dictionary with default shape of each matrix parameter
"""
shapes = super()._get_shapes(state_dim, measurement_dim)
shapes["b"] = (state_dim,)
shapes["d"] = (measurement_dim,)
return shapes
class KalmanFilterTransformerFP(BaseKalmanFilter, BaseTransformer):
"""Kalman Filter is used for denoising or inferring the hidden state of given data.
The Kalman Filter is an unsupervised algorithm, consisting of
several mathematical equations which are used to create
an estimate of the state of a process.
This class is the adapter for the ``FilterPy`` package into ``sktime``.
``KalmanFilterTransformerFP`` implements hidden inferred states and
denoising, depending on the boolean input parameter ``denoising``.
In addition, ``KalmanFilterTransformerFP`` provides parameter
optimization via Expectation-Maximization (EM) algorithm.
Parameters
----------
state_dim : int
System state feature dimension.
state_transition : np.ndarray, optional (default=None)
of shape (state_dim, state_dim) or (time_steps, state_dim, state_dim).
State transition matrix, also referred to as ``F``, is a matrix
which describes the way the underlying series moves
through successive time periods.
process_noise : np.ndarray, optional (default=None)
of shape (state_dim, state_dim) or (time_steps, state_dim, state_dim).
Process noise matrix, also referred to as ``Q``,
the uncertainty of the dynamic model.
measurement_noise : np.ndarray, optional (default=None)
of shape (measurement_dim, measurement_dim) or
(time_steps, measurement_dim, measurement_dim).
Measurement noise matrix, also referred to as ``R``,
represents the uncertainty of the measurements.
measurement_function : np.ndarray, optional (default=None)
of shape (measurement_dim, state_dim) or
(time_steps, measurement_dim, state_dim).
Measurement equation matrix, also referred to as ``H``, adjusts
dimensions of measurements to match dimensions of state.
initial_state : np.ndarray, optional (default=None)
of shape (state_dim,).
Initial estimated system state, also referred to as ``X0``.
initial_state_covariance : np.ndarray, optional (default=None)
of shape (state_dim, state_dim).
Initial estimated system state covariance, also referred to as ``P0``.
control_transition : np.ndarray, optional (default=None)
of shape (state_dim, control_variable_dim) or
(time_steps, state_dim, control_variable_dim).
Control transition matrix, also referred to as ``G``.
``control_variable_dim`` is the dimension of ``control variable``,
also referred to as ``u``.
``control variable`` is an optional parameter for ``fit`` and ``transform``
functions.
denoising : bool, optional (default=False).
This parameter affects ``transform``. If False, then ``transform`` will be
inferring
hidden state. If True, uses ``FilterPy`` ``rts_smoother`` for denoising.
estimate_matrices : str or list of str, optional (default=None).
Subset of [``state_transition``, ``measurement_function``,
``process_noise``, ``measurement_noise``, ``initial_state``,
``initial_state_covariance``]
or - ``all``. If ``estimate_matrices`` is an iterable of strings,
only matrices in ``estimate_matrices`` will be estimated using EM algorithm.
If ``estimate_matrices`` is ``all``,
then all matrices will be estimated using EM algorithm.
Note -
- parameters estimated by EM algorithm assumed to be constant.
- ``control_transition`` matrix cannot be estimated.
See Also
--------
KalmanFilterTransformerPK :
Kalman Filter transformer, adapter for the ``pykalman`` package
into ``sktime``.
Notes
-----
``FilterPy`` KalmanFilter documentation :
https://filterpy.readthedocs.io/en/latest/kalman/KalmanFilter.html
References
----------
.. [1] Greg Welch and Gary Bishop, "An Introduction to the Kalman Filter", 2006
https://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf
.. [2] R.H.Shumway and D.S.Stoffer "An Approach to time
Series Smoothing and Forecasting Using the EM Algorithm", 1982
https://www.stat.pitt.edu/stoffer/dss_files/em.pdf
Examples
--------
Basic example:
>>> import numpy as np # doctest: +SKIP
>>> import sktime.transformations.series.kalman_filter as kf
>>> time_steps, state_dim, measurement_dim = 10, 2, 3
>>>
>>> X = np.random.rand(time_steps, measurement_dim) * 10
>>> transformer = kf.KalmanFilterTransformerFP(state_dim=state_dim) # doctest: +SKIP
>>> Xt = transformer.fit_transform(X=X) # doctest: +SKIP
Example of - denoising, matrix estimation, missing values and transform with y:
>>> import numpy as np # doctest: +SKIP
>>> import sktime.transformations.series.kalman_filter as kf
>>> time_steps, state_dim, measurement_dim = 10, 3, 3
>>> control_variable_dim = 2
>>>
>>> X = np.random.rand(time_steps, measurement_dim)
>>> # missing value
>>> X[0][0] = np.nan
>>>
>>> # y
>>> control_variable = np.random.rand(time_steps, control_variable_dim)
>>>
>>> # If matrices estimation is required, elements of ``estimate_matrices``
>>> # are assumed to be constants.
>>> transformer = kf.KalmanFilterTransformerFP( # doctest: +SKIP
... state_dim=state_dim,
... measurement_noise=np.eye(measurement_dim),
... denoising=True,
... estimate_matrices='measurement_noise'
... )
>>> Xt = transformer.fit_transform(X=X, y=control_variable) # doctest: +SKIP