Skip to the lesson
FixTheRobot Explore Robotics / Probability for Robotics / M7 Kalman Filter / M7-T3

Probability for Robotics · Theory · M7

M7-T3 — Innovation, Gain and Tuning Q and R

Q and R are the two numbers you have to supply. The innovations tell you whether you chose them well.

  • Lesson 3 of 4
  • Intermediate
  • Module 7: Kalman Filter
  • Theory
  • About 12 minutes to read

The Kalman filter is optimal only for the noise it is told about. Q and R are never known exactly, and most of the practical work of using a Kalman filter is choosing them. The good news is that the filter produces, at every step, a quantity that exposes mistakes in them: the innovation. This lesson looks at its statistics, shows with a sweep how the filter fails when Q is too small or too large, and gives a practical recipe.

Learning objectives

After this lesson, you should be able to:

  • Define the innovation and its covariance, and state the properties of the innovation sequence of a correctly tuned filter.
  • Describe how a Q or R that is too small or too large changes the gain, the error and the claimed uncertainty.
  • Compute and interpret the normalised innovation squared (NIS) and its expected value.
  • Apply a practical recipe to choose R from a sensor and Q from the model and the data.

The intuition

At each step the filter predicts the reading, sees the reading and is surprised by the difference: the innovation y=z−Hxˉy = z - H\bar{x}. If the filter is right about its models, the surprises should be what it expects: zero on average, with the covariance S=HPˉH⊤+RS = H\bar PH^\top + R it computed, and no pattern from one step to the next. Anything else is a sign that something is wrong:

  • Surprises larger than S predicts: the filter is overconfident. Its Q or R is too small, or the model is wrong.
  • Surprises smaller than S predicts: the filter is underconfident. Q or R is too large. It is safe but wasteful.
  • Surprises that go in the same direction several steps in a row: the model is missing something (a bias, a slip, an acceleration).
Error, claimed error and the NIS as the assumed process noise q is variedLeft: the real error of the filter against the assumed process noise q on a log scale from 0.0001 to 1. It is lowest, about 0.126 metres, near the true value 0.01, and rises on both sides. The claimed standard deviation, shown as a second line, rises steadily with q and crosses the real error exactly near the true q: below it the filter underestimates its error, above it overestimates. Right: the mean normalised innovation squared is about 1 at the true q, much higher when q is too small and below 1 when q is too large.-4-3-2-1000.10.20.30.4log10 of the assumed qstd (m) true q real errorclaimed std -4-3-2-1001234log10 of the assumed qmean NISNIS = 1: consistent
Left: the real error (blue) and the claimed standard deviation (orange) as the assumed process noise is varied. Right: the mean NIS, which should be 1.

The sweep of the figure filters the same robot as lesson 1 with a range of assumed process noises. At the true value the real error is lowest and the claim matches it. With q too small, the filter trusts its model too much (gain 0.10), lags the truth, and claims an error of 6 cm while its real error is 22 cm: overconfident and wrong. With q too large, the gain goes up to 0.88, the filter chases the noise in each reading, and the real error is 18 cm. The NIS shows the diagnosis in one number.

A wrong Q or R does not crash the filter. It quietly produces estimates that are worse than they could be and uncertainties that cannot be trusted. The innovations are how you find out.

Definitions

Innovation yt\mathbf{y}_t
zt−Hxˉt\mathbf{z}_t - H\bar{\mathbf{x}}_t: measurement minus predicted measurement.
Innovation covariance StS_t
HPˉtH⊤+RH\bar P_tH^\top + R: how large the filter expects the innovation to be.
NIS
ϵt=yt⊤St−1yt\epsilon_t = \mathbf{y}_t^\top S_t^{-1}\mathbf{y}_t: the squared Mahalanobis size of the innovation. For a consistent filter it follows a χ2\chi^2 distribution with as many degrees of freedom as the measurement has components, so its mean equals that number.
Whiteness
The innovations of a consistent filter are uncorrelated in time: E[ytyt+k⊤]=0\mathbb{E}[\mathbf{y}_t\mathbf{y}_{t+k}^\top] = 0 for k≠0k\neq 0.
Over/under-confident
Overconfident: the claimed covariance is smaller than the real error covariance. Underconfident: larger.
Innovation statistics
yt∼N(0,St),ϵt=yt⊤St−1yt∼χm2,E[ϵt]=m\mathbf{y}_t\sim\mathcal{N}(0,S_t), \qquad \epsilon_t = \mathbf{y}_t^\top S_t^{-1}\mathbf{y}_t \sim \chi^2_m, \qquad \mathbb{E}[\epsilon_t] = m
Under the filter’s own assumptions. The average NIS over many steps should be close to the measurement dimension m.
Gain and the ratio q : r
K∞=σˉ∞2σˉ∞2+r,σˉ∞2=q+q2+4qr2K_\infty = \frac{\bar\sigma^2_\infty}{\bar\sigma^2_\infty + r}, \qquad \bar\sigma^2_\infty = \frac{q + \sqrt{q^2 + 4qr}}{2}
Scaling q and r by the same factor does not change the gain, only the claimed variance: it is the ratio that sets how the filter behaves.

Derivation: why the innovation is white with covariance S

Why should the innovations of a correct filter be zero-mean, white and of covariance SS? Because the filter has already extracted from the past everything that is predictable.

  1. yt=zt−Hxˉt=H(xt−xˉt)+vt\mathbf{y}_t = \mathbf{z}_t - H\bar{\mathbf{x}}_t = H(\mathbf{x}_t - \bar{\mathbf{x}}_t) + \mathbf{v}_t

    Substitute zt=Hxt+vt\mathbf{z}_t = H\mathbf{x}_t + \mathbf{v}_t. The innovation is the prediction error seen through HH, plus the measurement noise.

  2. E[yt]=0,Cov(yt)=HPˉtH⊤+R=St\mathbb{E}[\mathbf{y}_t] = 0, \qquad \mathrm{Cov}(\mathbf{y}_t) = H\bar P_tH^\top + R = S_t

    The prior error xt−xˉt\mathbf{x}_t - \bar{\mathbf{x}}_t has zero mean and covariance Pˉt\bar P_t if the filter is consistent, and is independent of the new noise vt\mathbf{v}_t.

  3. E[yt zs⊤]=0for s<t\mathbb{E}\bigl[\mathbf{y}_t\,\mathbf{z}_s^\top\bigr] = 0\quad\text{for } s<t

    The posterior at time t−1 is the conditional mean given all measurements up to t−1; its error is orthogonal to those measurements (the orthogonality principle of the conditional mean). The innovation at t is built from that error, so it is uncorrelated with every past measurement.

  4. ys is a function of z1:s;⇒;E[ytys⊤]=0,;s<t\mathbf{y}_s \text{ is a function of } \mathbf{z}_{1:s} ;\Rightarrow; \mathbb{E}[\mathbf{y}_t\mathbf{y}_s^\top] = 0,; s<t

    Past innovations are functions of past measurements, so the innovations are mutually uncorrelated: white.

The effect of a wrong q or r

If the filter is run with q~≠q\tilde q \ne q, the real prediction-error covariance is not Pˉ\bar P, so E[ϵt]≠m\mathbb{E}[\epsilon_t] \ne m: too high if the filter understates its uncertainty, too low if it overstates it. This is what the NIS column of the example shows (2.25 for a q that is 25 times too small, 0.25 for a q that is 25 times too large). The whiteness fails as well when the model misses a systematic effect: a slowly varying bias in the innovation shows up as a positive autocorrelation.

Average NIS = measurement dimension: a necessary test of consistency. It does not say which of Q or R is wrong, only that something is.

A worked example

The robot of lesson 1 has a true process noise q=0.01q = 0.01 and measurement noise r=0.04r = 0.04. We filter it five times, with the correct values and with each of Q and R wrong by a large factor, over 200 runs of 60 steps (the first 20 steps ignored).

  1. Correct tuning. Gain 0.39, real error 0.126 m, claimed 0.125 m, mean NIS 1.0.
  2. q 25 times too small. The gain falls to 0.10. The real error is 0.223 m, the claim 0.062 m, and the NIS 2.25: overconfident, and worse than the raw sensor (0.2 m).
  3. q 25 times too large. The gain is 0.88. The real error is 0.178 m, the claim 0.187 m (nearly honest, but too large) and the NIS 0.25: underconfident.
  4. r 25 times too small. The gain is the same 0.88 and the same real error, but the filter claims 3.8 cm: the worst case, confidently wrong, with a NIS of 6.2.
  5. r 25 times too large. The gain is 0.10 and the real error 0.224 m. The claim of 0.31 m is conservative and the NIS is 0.09.
import math
from robotprob import Rng, kalman1d_predict, kalman1d_update, mean

q_true, r_true, u = 0.01, 0.04, 0.5          # the real robot

def run(seed, q, r, steps=60):                # filter it with an assumed q and r
    rng = Rng(seed)
    x, mu, var = 0.0, 0.0, 1.0
    err, innov, svar = [], [], []
    for t in range(steps):
        x += u + rng.gauss(0.0, math.sqrt(q_true))
        z = x + rng.gauss(0.0, math.sqrt(r_true))
        mu, var = kalman1d_predict(mu, var, u, q)
        s = var + r                           # the innovation variance the filter expects
        y = z - mu                            # the innovation
        mu, var, k = kalman1d_update(mu, var, z, r)
        if t >= 20:
            err.append(mu - x); innov.append(y); svar.append(s)
    return err, innov, svar, var

print('tuning        q      r   gain   rms err  claimed std  mean nis')
for name, q, r in [('correct', 0.01, 0.04), ('q too small', 0.0004, 0.04), ('q too large', 0.25, 0.04), ('r too small', 0.01, 0.0016), ('r too large', 0.01, 1.0)]:
    E, N = [], []
    for seed in range(1, 201):
        err, innov, svar, var = run(seed, q, r)
        E += [e * e for e in err]
        N += [y * y / s for y, s in zip(innov, svar)]   # normalised innovation squared
    err, innov, svar, var = run(1, q, r)
    k = (var + q) / (var + q + r)
    print(name.ljust(12), str(q).rjust(7), str(r).rjust(6), str(round(k, 2)).rjust(6), str(round(math.sqrt(mean(E)), 4)).rjust(9), str(round(math.sqrt(var), 4)).rjust(11), str(round(mean(N), 2)).rjust(9))
tuning        q      r   gain   rms err  claimed std  mean nis
correct         0.01   0.04   0.39    0.1262       0.125       1.0
q too small   0.0004   0.04    0.1    0.2232      0.0617      2.25
q too large     0.25   0.04   0.88    0.1778      0.1873      0.25
r too small     0.01 0.0016   0.88    0.1778      0.0375      6.19
r too large     0.01    1.0    0.1    0.2235      0.3084      0.09
The filter is the one of lesson 1. Only the numbers it is told, q and r, change. The NIS is computed from quantities the filter has, with no knowledge of the truth.

Note that two very different mistakes (q too small and r too large) give almost the same gain, hence the same behaviour: only the ratio matters to the estimate, but the claimed uncertainty and the NIS tell them apart in scale, and a gating test on the innovations (module 4) would use S directly, so a wrong scale also wrongly accepts or rejects readings.

In robotics

A recipe for R

The measurement noise is the easiest to find: leave the robot still, record the sensor for a minute, and take the variance of the readings (the identification lesson of module 2). Inflate it a little for what the test does not capture (vibration, temperature, a moving target). Do not forget the sensor's resolution, which sets a floor.

A recipe for Q

The process noise stands for everything the model does not know, so it can rarely be measured directly. Start from physics (for a constant-velocity model, how much can the velocity change in a step?), then adjust: raise Q until the average NIS is close to its expected value and the innovations look white. A Q that is a little too large costs a bit of accuracy; one that is too small makes the filter fail suddenly when the robot does something the model did not expect. When in doubt, err on the large side.

Test with logged data

Record the innovations and S during a real run, then plot them with their ±2 standard-deviation envelope: about 95% should be inside. Plot the autocorrelation. Compare the NIS average with the measurement dimension. The Perception course shows the filtering workflow in Simple Filtering and Kalman Filter Intuition.

Adaptive filters

Some systems estimate Q or R online from the innovations (innovation-based adaptive estimation), or inflate the covariance when the NIS rises. These are tools for a changing environment (a sensor that degrades in rain), but they can mask a model error as noise. Start with a fixed tuning and use the diagnostics to understand it.

Outliers

The NIS is also the gate for outliers: a reading whose NIS exceeds a χ2\chi^2 threshold is rejected (module 4). The gate depends on S, so it is only as good as Q and R.

Common misconceptions

“A smoother output means a better filter.”

A smooth output may be a sign that q is too small: the filter has stopped listening to the sensor and lags the truth. The error against a reference, or the NIS, tells; smoothness does not.

“Q and R can be tuned independently.”

The gain and the estimate depend on their ratio, so different pairs give the same estimate. What fixes them separately is R from a static sensor test, then Q from the NIS.

“If the average NIS is 1, the filter is correct.”

It is necessary, not sufficient. A wrong model can give a NIS of 1 by chance, or the NIS can be right on average while the innovations are correlated. Check whiteness and, in simulation, the real error.

“The filter’s covariance is a property of the sensor.”

It is a prediction made from the models you supplied. It changes if you change Q or R, even though the sensor and the robot do not.

Key takeaways

  1. The innovation is the surprise, y = z − Hx̄, with covariance S = HP̄Hᵀ + R. For a consistent filter it is zero-mean and white.
  2. NIS = yᵀS⁻¹y has an expected value equal to the measurement dimension. Far above means overconfident, far below underconfident.
  3. The gain depends on the ratio q : r. A q that is too small gives a sluggish filter, a q that is too large gives a noisy one, and a small r gives a noisy filter that claims to be precise.
  4. Choose R from a static sensor test, Q from physics and the NIS, and when in doubt make Q a little larger.
  5. A wrong tuning does not crash the filter: it hides in the numbers. Only the innovations expose it.

References and further reading

Each source is marked free or paid. Free to read does not mean free to reuse: the course resources page lists every source with its licence.

Knowledge check

Three questions. Write an answer, then reveal the explanation. Your answers stay in your browser.

Question 1

A filter with a 2-dimensional measurement has an average NIS of 5.8 over 500 steps. What does this indicate, and what is the first thing to try?

Explanation

The expected NIS equals the measurement dimension, 2, so 5.8 is much too high: the innovations are about three times larger (in squared Mahalanobis terms) than S predicts, so the filter is overconfident. The first thing to try is to raise R if the sensor test was optimistic, or Q if the robot moves in ways the model does not capture, until the average NIS is near 2 and the innovations look white. Also check for outliers, which can inflate the average.

Question 2

Two tunings have the same ratio q/r: (q, r) = (0.01, 0.04) and (0.1, 0.4). Compare the gains, the estimates and the claimed variances.

Explanation

The steady-state gain depends only on q/r, so the gains are the same (0.39) and so are the estimates. The claimed variance scales with the noise: the second tuning claims 10 times the variance (a standard deviation 3.2 times larger). If the true noises are those of the first, the second filter is correct in its estimate but underconfident in its claim, and its NIS is about 0.1, which the NIS reveals and the estimate does not.

Question 3

Why can an innovation sequence that is correlated in time (long runs above and below zero) not be fixed by changing R alone?

Explanation

Correlated innovations mean that the filter is systematically predicting the reading wrongly in a way that persists: a bias, a drift, an unmodelled acceleration, or a q too small so that the estimate lags the truth. Changing R only changes how much of the surprise is accepted, not the fact that the surprises are predictable from the past. The fix is in the model: add a state for the bias or the unmodelled effect, or raise Q so the filter can follow it. Whiteness is what tells a modelling error apart from a noise level error.

What’s next

The innovations test a filter against its own assumptions. The last lesson of the module asks when the filter can be believed at all, using the error statistics (NEES), the observability of the state, and the signs of divergence.

Practice this lesson

1D Kalman Filter

Rover drives along a rail with a noisy range sensor and slipping wheels. Implement predict and update, tune Q and R, and prove with the innovation that the filter is consistent.

Next lesson

M7-T4 — Consistency, Observability and Divergence

Test a filter with the normalized innovation and estimation error, and recognise unobservable states and divergence.

Nothing below is required to finish this lesson.

  • Before
    M7-T2: Deriving the Multivariate Kalman Filter

    Derive the matrix prediction and update equations from the conditioning of a joint Gaussian, and state the assumptions.

  • Lab
    M7-L1: 1D Kalman Filter

    Rover drives along a rail with a noisy range sensor and slipping wheels. Implement predict and update, tune Q and R, and prove with the innovation that the filter is consistent.

Other courses on this site treat neighbouring topics from their own angle: