请基于python写一份基于卡尔曼滤波的数据去噪代码
时间: 2024-05-10 17:15:19 浏览: 97
好的,以下是一份基于Python的卡尔曼滤波数据去噪代码:
```python
import numpy as np
class KalmanFilter:
def __init__(self, x0, P0, F, Q, H, R):
self.x = x0
self.P = P0
self.F = F
self.Q = Q
self.H = H
self.R = R
def predict(self):
self.x = np.dot(self.F, self.x)
self.P = np.dot(self.F, np.dot(self.P, self.F.T)) + self.Q
def update(self, z):
K = np.dot(self.P, np.dot(self.H.T, np.linalg.inv(np.dot(self.H, np.dot(self.P, self.H.T)) + self.R)))
self.x = self.x + np.dot(K, (z - np.dot(self.H, self.x)))
self.P = np.dot((np.eye(self.P.shape[0]) - np.dot(K, self.H)), self.P)
def kalman_filter(data):
x0 = np.array([data[0], 0])
P0 = np.diag([1, 1])
F = np.array([[1, 1], [0, 1]])
Q = np.diag([0.1, 0.1])
H = np.array([[1, 0]])
R = np.array([[0.1]])
kf = KalmanFilter(x0, P0, F, Q, H, R)
n = len(data)
result = np.zeros(n)
for i in range(n):
kf.predict()
kf.update(data[i])
result[i] = kf.x[0]
return result
```
使用方法:
```python
import matplotlib.pyplot as plt
# 生成原始数据
t = np.linspace(0, 10, 100)
data = np.sin(t) + np.random.normal(0, 0.1, 100)
# 进行卡尔曼滤波去噪
filtered_data = kalman_filter(data)
# 绘制原始数据与滤波后的数据
plt.plot(t, data, label='Raw Data')
plt.plot(t, filtered_data, label='Filtered Data')
plt.legend()
plt.show()
```
运行后会生成一张原始数据与滤波后的数据的对比图。
阅读全文