I have a trajectory of an object in a 2D space (a surface). The trajectory is given as a sequence of (x,y)
coordinates. I know that my measurements are noisy and sometimes I have obvious outliers. So, I want to filter my observations.
As far as I understood Kalman filter, it does exactly what I need. So, I try to use it. I found a python implementation here. And this is the example that the documentation provides:
from pykalman import KalmanFilter
import numpy as np
kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]])
measurements = np.asarray([[1,0], [0,0], [0,1]]) # 3 observations
kf = kf.em(measurements, n_iter=5)
(filtered_state_means, filtered_state_covariances) = kf.filter(measurements)
(smoothed_state_means, smoothed_state_covariances) = kf.smooth(measurements)
I have some troubles with interpretation of input and output. I guess that measurements
is exactly what my measurements are (coordinates). Although I am a bit confused because measurements in the example are integers.
I also need to provide some transition_matrices
and observation_matrices
. What values should I put there? What do these matrices mean?
Finally, where can I find my output? Should it be filtered_state_means
or smoothed_state_means
. These arrays have correct shapes (2, n_observations)
. However, the values in these array are too far from the original coordinates.
So, how to use this Kalman filter?
Best Answer
Here is an example of a 2-dimensional Kalman filter that may be useful to you. It is in Python.
The state vector is consists of four variables: position in the x0-direction, position in the x1-direction, velocity in the x0-direction, and velocity in the x1-direction. See the commented line "x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)".
The state-transition matrix (F), which facilitates prediction of the system/objects next state, combines the present state values of position and velocity to predict position (i.e. x0 + x0_dot and x1 + x1_dot) and the present state values of velocity for velocity (i.e. x0_dot and x1_dot).
The measurement matrix (H) appears to consider only position in both the x0 and x1 positions.
The motion noise matrix (Q) is initialized to a 4-by-4 identity matrix, while the measurement noise is set to 0.0001.
Hopefully this example will allow you to get your code working.