卡尔曼滤波 Python代码实现
时间: 2023-11-05 08:19:02 浏览: 102
卡尔曼滤波Python代码实例实现
5星 · 资源好评率100%
以下是一个简单的卡尔曼滤波器的Python代码实现示例:
```python
import numpy as np
class KalmanFilter:
def __init__(self, initial_state, initial_covariance, transition_matrix, observation_matrix, process_noise_covariance, measurement_noise_covariance):
self.state = initial_state
self.covariance = initial_covariance
self.transition_matrix = transition_matrix
self.observation_matrix = observation_matrix
self.process_noise_covariance = process_noise_covariance
self.measurement_noise_covariance = measurement_noise_covariance
def predict(self):
self.state = np.dot(self.transition_matrix, self.state)
self.covariance = np.dot(np.dot(self.transition_matrix, self.covariance), np.transpose(self.transition_matrix)) + self.process_noise_covariance
def update(self, measurement):
innovation = measurement - np.dot(self.observation_matrix, self.state)
innovation_covariance = np.dot(np.dot(self.observation_matrix, self.covariance), np.transpose(self.observation_matrix)) + self.measurement_noise_covariance
kalman_gain = np.dot(np.dot(self.covariance, np.transpose(self.observation_matrix)), np.linalg.inv(innovation_covariance))
self.state += np.dot(kalman_gain, innovation)
self.covariance = np.dot((np.eye(len(self.state)) - np.dot(kalman_gain, self.observation_matrix)), self.covariance)
# 定义初始状态、转移矩阵、观测矩阵、过程噪声协方差矩阵和测量噪声协方差矩阵
initial_state = np.array([[0], [0]])
transition_matrix = np.array([[1, 1], [0, 1]])
observation_matrix = np.array([[1, 0]])
process_noise_covariance = np.array([[0.1, 0], [0, 0.1]])
measurement_noise_covariance = np.array([[1]])
# 创建KalmanFilter对象
kalman_filter = KalmanFilter(initial_state, np.eye(2), transition_matrix, observation_matrix, process_noise_covariance, measurement_noise_covariance)
# 生成随机观测数据
np.random.seed(0)
measurements = np.random.normal(0, 1, (100, 1))
# 使用Kalman滤波器进行状态估计
estimated_states = []
for measurement in measurements:
kalman_filter.predict()
kalman_filter.update(measurement)
estimated_states.append(kalman_filter.state)
# 输出估计的状态值
for i in range(len(estimated_states)):
print("Step", i+1, "Estimated State:", estimated_states[i])
```
该代码实现了一个简单的一维卡尔曼滤波器。在示例中,我们定义了初始状态、转移矩阵、观测矩阵、过程噪声协方差矩阵和测量噪声协方差矩阵。然后,我们使用随机生成的观测数据来进行状态估计,并输出每个时间步的估计状态值。
请注意,这只是一个简单的示例,实际应用中可能需要根据具体问题进行调整和优化。
阅读全文