Kalman filter behavior

I used the kalman filter implanted here: https://gist.github.com/alexbw/1867612

I have a very general understanding of this. this is the test code I have:

import matplotlib.pyplot as plt
import numpy as np
from Kalman import Kalman

n = 50    
d = 5

xf = np.zeros(n - d)
yf = np.zeros(n - d)

xp = np.zeros(d)
yp = np.zeros(d)

x = np.zeros(n)
y = np.zeros(n)

for i in range(n):

    if i==0:
        x[i] = 05
        y[i] = 20
        KLF = Kalman(6, 2)

    elif i< (n - d):
        xf[i], yf[i] = KLF.predict()  
        x[i] = x[i-1] + 1
        y[i] = y[i-1] + np.random.random() * 10
        NewPoint = np.r_[x[i], y[i]]
        KLF.update(NewPoint)
    else:
        x[i] = x[i-1] + 1
        y[i] = y[i-1] + np.random.random() * 10
        xp[n - i -1], yp[n - i -1] = KLF.predict()  
        NewPoint = np.r_[x[i] , yp[n - i -1]]
        KLF.update(NewPoint)

plt.figure(1)
plt.plot(x, y, 'ro') #original
plt.plot(xp, yp, 'go-') #predicted kalman
plt.plot(xf, yf, 'b') #kalman filter
plt.legend( ('Original', 'Prediction', 'Filtered') ) 
plt.show()

      

enter image description here

My question is, why does Kalman filtering start at zero if the data starts at x = 5, y = 20? Is this some kind of standard behavior?

thank

+3


source to share


1 answer


The current state of the Kalman instance is stored in an attribute x

:

In [48]: KLF = Kalman(6, 2)

In [49]: KLF.x
Out[49]: 
matrix([[ 0.],
        [ 0.],
        [ 0.],
        [ 0.],
        [ 0.],
        [ 0.]])

      

The six components represent position, speed and acceleration. Therefore, by default, a Kalman instance starts (0,0)

at zero speed and acceleration.

After creating the instance KLF

, when i=1

the first modification xf

and yf

is made by a call KLF.predict

:

xf[i], yf[i] = KLF.predict()

      

There are two problems with this. First, it xf[0], yf[0]

never gets updated, so it stays in (0, 0)

. Hence, the blue line starts with (0, 0)

.



The second problem is that the current state is KLF.x

by default equal (0, 0)

because of the way the Kalman class is defined. If you want the instance to KLF

start at position in (5, 20)

, you need to change it KLF.x

yourself.

Also keep in mind that the Kalman filter must be updated first by the observation and then a second prediction. This is mentioned in the cool line of the class.

Now I don't quite understand the purpose of your code, so I'm not going to figure out how the s update

should appear predict

, but as far as the initial state is concerned, you can use this:

if i==0:
    x[i] = 5
    y[i] = 20
    KLF = Kalman(6, 2)
    KLF.x[:2] = np.matrix((x[0], y[0])).T
    xf[i], yf[i] = KLF.predict()  

      

what gives

enter image description here

+4


source







All Articles