[英]Implementing Kalman filter for state space model of movement process
是否可以像贝叶斯过滤和平滑中介绍的那样实现 model,例如 statsmodels 中的示例 3.6?
我可以跟随提供的 Matlab 代码,但我不确定这种 model 是否以及如何在 statsmodels 中实现。
该示例涉及在二维空间中跟踪 object 的 position。 state 是四维x=(x_1, x_2, x_3, x_4)
,但我重新排列了向量,使(x_1, x_3)
代表 position 和(x_2, x_4)
代表两个方向的速度。 该过程的模拟数据由 100 个 position 观测值组成,排列在 2x100 矩阵Y
中。
import numpy as np
from scipy import linalg
# The matrices in the dynamic model are set up as follows
q, dt, s = 1, 0.1, 0.5
A = np.array([[1, dt, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, dt],
[0, 0, 0, 1]])
Q = q * np.array([[dt ** 3 / 3, dt ** 2 / 2, 0, 0],
[dt ** 2 / 2, dt, 0, 0],
[0, 0, dt ** 3 / 3, dt ** 2 / 2],
[0, 0, dt ** 2 / 2, dt]])
# Matrices in the measurement model are designed as follows
H = np.array([[1, 0, 0, 0],
[0, 0, 1, 0]])
R = s ** 2 * np.eye(2)
# Starting values
m0 = np.array([[0, 1, 0, -1]]).T # column vector
P0 = np.eye(4)
该过程的卡尔曼滤波器然后实现如下:
m = m0
P = P0
kf_m = np.zeros((m.shape[0], n))
kf_P = np.zeros((P.shape[0], P.shape[1], n))
for k in range(n):
m = A @ m
P = A @ P @ A.T + Q
S = H @ P @ H.T + R
K = linalg.lstsq(S.T, (P @ H.T).T)[0].T
m = m + K @ (Y[:, k, np.newaxis] - H @ m)
P = P - K @ S @ K.T
kf_m[:, k] = m.flatten()
kf_P[:, :, k] = P
如果可能的话,如何在 statsmodels 中实现这个过滤器? 如果数据更大,statsmodels 可能会更有效地运行,并且可以在子类中的过滤器上实现更平滑。
是的,你可以这样做; 最主要的是 map 您对 Statsmodels 使用的符号/变量名称的符号。
以下是您可以如何执行此操作的示例:
import numpy as np
import pandas as pd # Pandas isn't necessary, but makes some output nicer
import statsmodels.api as sm
# The matrices in the dynamic model are set up as follows
q, dt, s = 1, 0.1, 0.5
A = np.array([[1, dt, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, dt],
[0, 0, 0, 1]])
Q = q * np.array([[dt ** 3 / 3, dt ** 2 / 2, 0, 0],
[dt ** 2 / 2, dt, 0, 0],
[0, 0, dt ** 3 / 3, dt ** 2 / 2],
[0, 0, dt ** 2 / 2, dt]])
# Matrices in the measurement model are designed as follows
H = np.array([[1, 0, 0, 0],
[0, 0, 1, 0]])
R = s ** 2 * np.eye(2)
# Starting values
m0 = np.array([[0, 1, 0, -1]]).T # column vector
P0 = np.eye(4)
# Now instantiate a statespace model with the data
# (data should be shaped nobs x n_variables))
kf = sm.tsa.statespace.MLEModel(pd.DataFrame(Y.T), k_states=4)
kf._state_names = ['x1', 'dx1/dt', 'x2', 'dx2/dt']
kf['design'] = H
kf['obs_cov'] = R
kf['transition'] = A
kf['selection'] = np.eye(4)
kf['state_cov'] = Q
kf.initialize_known(m0[:, 0], P0)
# To performan Kalman filtering and smoothing, use:
res = kf.smooth([])
# Then, for example, to print the smoothed estimates of
# the state vector:
print(res.states.smoothed)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.