Filed under Math, Physics & Foundations

Implementing the Kalman Filter in Python

Hello. Im trying to experiment with some recent articles that tries to connect transformers and kalman filter. I remember that I saw in my undergrad this concept on the control lecture but to be honest I didnt quite understand the concept at the time. To help my understanding i tried to implement using only some basic python libraries the Kalman Filter in python.

Before the notebook with the implementation here is a quick summary of what is this filter provided by GPT ( =P ):

A Kalman filter is a powerful algorithm used for making estimates or predictions in systems that are subject to various uncertainties. Its widely used in fields like robotics, aerospace, finance, and even weather forecasting. Heres a simplified explanation suitable for a blog post:

The beauty of the Kalman filter lies in its ability to deal with uncertainty. Its designed to weigh both the predicted state and the new measurements, considering the uncertainties in both. If the measurements are very accurate, it gives them more weight. If the predictions are believed to be more reliable, it leans more on them.

That weighing is the Kalman gain, and it is worth playing with directly. Below, a hidden state does a random walk and you only ever see the noisy dots. The two sliders do not change the data they change what the filter believes about the noise. Push Q down and it decides the state can barely move, so it smooths hard and lags; push Q up and it chases every measurement. In between it beats the raw sensor by a wide margin.

One thing worth noticing: only the ratio Q/R affects the estimate. Scale both up by a thousand and the red line does not move at all but the uncertainty band does, because the filter now believes it is far less sure than it really is.

A scalar Kalman filter on a local-level model. The blue line is the hidden state you are trying to recover, the grey dots are what the sensor reports, and the red line with its ±2σ band is the filter's estimate. RMSE is measured against the hidden truth, so you can see directly how much the filter buys you over the raw measurements.

Finally here is the notebook : Colab

#kalman-filter#bayesian#time-series