python卡尔曼多维_卡尔曼二维过滤器在python

这篇博客介绍了如何在Python中实现二维卡尔曼滤波器,基于Wikipedia上的公式。文章展示了如何处理状态向量(位置和速度)并定义F和H矩阵,以及如何在存在外部运动和噪声的情况下更新状态和不确定性协方差矩阵。示例代码演示了如何应用卡尔曼滤波器平滑噪声位置测量数据。
摘要由CSDN通过智能技术生成

这是基于

equations given on wikipedia的卡尔曼滤波器的实现。请注意,我对卡尔曼滤波器的理解非常简单,所以有可能的方法来改进这个代码。 (例如,它受到

here讨论的数值不稳定性问题的影响。据我所知,这只会影响Q值运动噪声非常小时的数值稳定性,在现实生活中,噪声通常不是很小,幸运的是至少对于我的实施)在实践中数值不稳定性不会出现。)

在下面的例子中,kalman_xy假定状态向量是4元组:位置的2个数字和速度的2个数字。

已经为该状态向量定义了F和H矩阵:如果x是4元组状态,则

new_x = F * x

position = H * x

然后调用卡尔曼,这是广义卡尔曼滤波器。一般来说,如果你想定义一个不同的状态向量 – 也许是代表位置,速度和加速度的6元组,它仍然是有用的。您只需通过提供适当的F和H来定义运动方程。

import numpy as np

import matplotlib.pyplot as plt

def kalman_xy(x, P, measurement, R,

motion = np.matrix('0. 0. 0. 0.').T,

Q = np.matrix(np.eye(4))):

"""

Parameters:

x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)

P: initial uncertainty convariance matrix

measurement: observed position

R: measurement noise

motion: external motion added to state vector x

Q: motion noise (same shape as P)

"""

return kalman(x, P, measurement, R, motion, Q,

F = np.matrix('''

1. 0. 1. 0.;

0. 1. 0. 1.;

0. 0. 1. 0.;

0. 0. 0. 1.

'''),

H = np.matrix('''

1. 0. 0. 0.;

0. 1. 0. 0.'''))

def kalman(x, P, measurement, R, motion, Q, F, H):

'''

Parameters:

x: initial state

P: initial uncertainty convariance matrix

measurement: observed position (same shape as H*x)

R: measurement noise (same shape as H)

motion: external motion added to state vector x

Q: motion noise (same shape as P)

F: next state function: x_prime = F*x

H: measurement function: position = H*x

Return: the updated and predicted new values for (x, P)

See also http://en.wikipedia.org/wiki/Kalman_filter

This version of kalman can be applied to many different situations by

appropriately defining F and H

'''

# UPDATE x, P based on measurement m

# distance between measured and current position-belief

y = np.matrix(measurement).T - H * x

S = H * P * H.T + R # residual convariance

K = P * H.T * S.I # Kalman gain

x = x + K*y

I = np.matrix(np.eye(F.shape[0])) # identity matrix

P = (I - K*H)*P

# PREDICT x, P based on motion

x = F*x + motion

P = F*P*F.T + Q

return x, P

def demo_kalman_xy():

x = np.matrix('0. 0. 0. 0.').T

P = np.matrix(np.eye(4))*1000 # initial uncertainty

N = 20

true_x = np.linspace(0.0, 10.0, N)

true_y = true_x**2

observed_x = true_x + 0.05*np.random.random(N)*true_x

observed_y = true_y + 0.05*np.random.random(N)*true_y

plt.plot(observed_x, observed_y, 'ro')

result = []

R = 0.01**2

for meas in zip(observed_x, observed_y):

x, P = kalman_xy(x, P, meas, R)

result.append((x[:2]).tolist())

kalman_x, kalman_y = zip(*result)

plt.plot(kalman_x, kalman_y, 'g-')

plt.show()

demo_kalman_xy()

红点显示嘈杂的位置测量,绿线显示卡尔曼预测位置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值