piercus / kalman-filter

Kalman filter in javascript
MIT License
106 stars 15 forks source link

Question regarding the Online Kalman Filter #65

Closed miguel436 closed 1 year ago

miguel436 commented 1 year ago

Hello! I have been testing this library by following the Online Kalman Filter example but I have some questions about the prediction results and would be grateful if someone could help me.

I started by running the following code:

const kFilter = new pkg.KalmanFilter();

const observations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let previousCorrected = null;
const results = [];

observations.forEach(observation => {
    const predicted = kFilter.predict({
        previousCorrected
    });

     const correctedState = kFilter.correct({
        predicted,
        observation
    });

    results.push(correctedState.mean);

    // update the previousCorrected for next loop iteration
    previousCorrected = correctedState
});

After updating the filter based on all the available observations, I ran the predict method again to predict the next state while monitoring both the previous and the predicted states:

console.log(previousCorrected)
const anotherPrediction = kFilter.predict({
    previousCorrected
});
console.log('******************')
console.log(anotherPrediction)

The yielded results are the following:

State {
  mean: [ [ 9.382113820899052 ] ],
  covariance: [ [ 0.6180339985217815 ] ],
  index: 9
}
******************
State {
  mean: [ [ 9.382113820899052 ] ],
  covariance: [ [ 1.6180339985217815 ] ],
  index: 10
}

Based on these logs, my question is: are the mean values supposed to be exactly the same ? I was expecting the mean value of the predicted state to be different from the one of the previous state.

Thanks for the awesome library!

piercus commented 1 year ago

You are using the default KalmanFilter by doing const kFilter = new pkg.KalmanFilter(); By default, the filter model is a 'constant-position' model.

It means that the prediction step will do x[t+1] = x[t] (see documentation and the Wikipedia article about kalman-filter to understand more)

I'm curious about what do you expect exactly ? do you want the filter to "continue the trend" of previous observation ?

If this is the case, i would suggest you choose a "constant-speed" model, which will keep 1st-order trend in the filter. If you want 2nd order trend, you can play with "constant-acceleration" model.

miguel436 commented 1 year ago

Thank you! That's exactly what I was looking for! I want my filter to continue the trend of previous observations.