Skip to the lesson
FixTheRobot Explore Robotics / Probability for Robotics / M4 Expectation, Variance and Covariance / M4-T3

Probability for Robotics · Theory · M4

M4-T3 — The Multivariate Gaussian and Covariance Ellipses

A covariance matrix is a shape. Its eigenvectors give the directions of the ellipse, its eigenvalues the squared lengths of its axes.

  • Lesson 3 of 5
  • Beginner
  • Module 4: Expectation, Variance and Covariance
  • Theory
  • About 16 minutes to read

This is the lesson where the covariance matrix becomes a picture. The Gaussian in several dimensions is the distribution behind every pose estimate in the course, and the ellipse of its contour lines is how robotics engineers draw, read and compare uncertainty. We derive the density, the ellipse and the Mahalanobis distance, and find something that surprises almost everyone: the familiar one-sigma ellipse holds only 39% of a two-dimensional Gaussian, not 68%.

Learning objectives

After this lesson, you should be able to:

  • Write the density of a multivariate Gaussian and explain each factor, including the role of the determinant.
  • Turn a 2 × 2 covariance matrix into an ellipse using its eigenvalues and eigenvectors, and draw 1, 2 and 3 sigma contours.
  • Compute the Mahalanobis distance, and explain why it differs from the Euclidean distance.
  • Derive the probability inside a k-sigma ellipse, and choose a gating threshold from the chi-square distribution.

The intuition

The last lesson ended with a covariance matrix [[13, 12], [12, 13]] cm² for a diagonal drive. What does a Gaussian with this covariance look like? Every contour line of its density, the set of points that are equally plausible, is an ellipse. The ellipse is centred on the mean, its long axis points in the direction of greatest uncertainty, and its short axis in the direction of least. Here the long axis lies along the 45° diagonal and is five times longer than the short one.

A covariance ellipse and the probability it containsLeft: 320 simulated error points lying in a thin cloud along the rising diagonal. Three nested ellipses show 1, 2 and 3 standard deviations. Two arrows give the principal axes: a long one along the diagonal with a standard deviation of 5 centimetres and a short one across it of 1 centimetre. Two marked points: one at (4, 0) outside the 2 sigma ellipse although it is only 4 centimetres from the centre, and one at (3, 3), inside the 1 sigma ellipse though 4.2 centimetres away. Right: the probability that a Gaussian value lies inside the k sigma ellipse, for one, two and three dimensions. A horizontal line marks 0.95: it is reached at 1.96 in one dimension, 2.45 in two and 2.80 in three. (4, 0)(3, 3) 1σ2σ3σaxes: 5 cm long, 1 cm short (1σ) 0123400.250.50.751k: size of the ellipse, in standard deviationsprobability inside 1 dimension2 dimensions3 dimensions
Left: the diagonal-drive error cloud with its 1, 2 and 3 standard-deviation ellipses and its principal axes. Right: the probability that a Gaussian value falls inside the k-sigma ellipse, in one, two and three dimensions. The ellipse that holds 95% grows with the dimension.

Two things in this figure deserve a careful look.

  • Distance depends on direction. The point (4, 0) is 4.0 cm from the centre, and the point (3, 3) is 4.2 cm away. But (4, 0) lies across the thin direction of the cloud, where errors of this size are rare, and is outside the 2σ ellipse. The point (3, 3) lies along the cloud and is inside the 1σ ellipse. A fair measure of “how far is this point from the mean?” must count distance in units of the local spread, in the direction of the point. That is the Mahalanobis distance: 2.88σ for the first point and 0.85σ for the second.
  • The “1σ ellipse” is not a 68% region. In one dimension ±1σ holds 68%. In two dimensions the 1σ ellipse holds only 39%, the 2σ ellipse 86% and the 3σ ellipse 98.9%. To contain 95% in two dimensions you must draw the ellipse at 2.45σ. In three dimensions, 2.80σ. Spreading probability over more directions leaves less of it near the centre.

A covariance ellipse is the set of points at the same Mahalanobis distance from the mean. Its axes point along the eigenvectors of the covariance matrix and their lengths are the square roots of its eigenvalues, times the size k of the ellipse.

Definitions

Multivariate Gaussian N(μ,Σ)\mathcal{N}(\boldsymbol\mu, \Sigma)
A distribution over a vector x\mathbf{x} of nn quantities with mean vector μ\boldsymbol\mu and covariance matrix Σ\Sigma (symmetric, positive definite).
Determinant ∣Σ∣|\Sigma|
A single number that measures the volume of the cloud: the area of the 2D ellipse is proportional to ∣Σ∣\sqrt{|\Sigma|}. For a diagonal Σ\Sigma it is the product of the variances.
Precision (information) matrix Σ−1\Sigma^{-1}
The inverse of the covariance. A large entry means a tightly known direction.
Mahalanobis distance dd
The distance from the mean in units of the standard deviation in the direction of the point: d2=(x−μ)⊤Σ−1(x−μ)d^2 = (\mathbf{x}-\boldsymbol\mu)^{\top}\Sigma^{-1}(\mathbf{x}-\boldsymbol\mu).
Eigenvalue λi\lambda_i and eigenvector vi\mathbf{v}_i
The directions vi\mathbf{v}_i along which Σ\Sigma only stretches, and the stretch factors λi\lambda_i (Σvi=λivi\Sigma \mathbf{v}_i = \lambda_i \mathbf{v}_i). They are the variances along the principal axes of the cloud.
Multivariate Gaussian density
f(x)=1(2π)n/2 ∣Σ∣1/2 exp⁡ ⁣(−12 (x−μ)⊤ Σ−1 (x−μ))f(\mathbf{x}) = \frac{1}{(2\pi)^{n/2}\,|\Sigma|^{1/2}}\, \exp\!\Bigl(-\tfrac{1}{2}\,(\mathbf{x}-\boldsymbol\mu)^{\top}\,\Sigma^{-1}\,(\mathbf{x}-\boldsymbol\mu)\Bigr)
For n=1n = 1 it is the Gaussian of the last module, with Σ=σ2\Sigma = \sigma^2. The exponent is −12d2-\tfrac12 d^2: the density falls with the square of the Mahalanobis distance.
Eigen-decomposition of a covariance matrix
Σ=R Λ R⊤,Λ=diag(λ1,…,λn),R=[v1  ⋯  vn]\Sigma = R\,\Lambda\,R^{\top}, \quad \Lambda = \mathrm{diag}(\lambda_1, \dots, \lambda_n), \quad R = [\mathbf{v}_1 \; \cdots \; \mathbf{v}_n]
The columns of R are orthonormal eigenvectors; Λ holds the variances along them.
The k-sigma covariance ellipse
ellipse of size k:{x:d2=k2},semi-axes kλi along vi\text{ellipse of size } k:\quad \{\mathbf{x} : d^2 = k^2\}, \quad \text{semi-axes } k\sqrt{\lambda_i} \text{ along } \mathbf{v}_i
In two dimensions the long and short semi-axes are k√λ₁ and k√λ₂, and the angle of the long one is that of v₁.
Probability inside the ellipse, two dimensions
P(d2≤k2)=1−e−k2/2(n=2)P(d^2 \le k^2) = 1 - e^{-k^2/2} \qquad (n = 2)
For other n the probability is the chi-square distribution function with n degrees of freedom: robotprob.chi2_cdf(k², n).

Derivation: the ellipse and the probability inside it

Why the contours are ellipses with those axes

  1. y=R⊤(x−μ)\mathbf{y} = R^{\top}(\mathbf{x} - \boldsymbol\mu)

    Rotate the coordinates to the principal axes of the cloud, centred on the mean. The rotation R⊤R^{\top} does not change distances.

  2. Σ−1=R Λ−1R⊤    ⇒    d2=y⊤Λ−1y=∑iyi2λi\Sigma^{-1} = R\,\Lambda^{-1}R^{\top} \;\;\Rightarrow\;\; d^2 = \mathbf{y}^{\top}\Lambda^{-1}\mathbf{y} = \sum_{i} \dfrac{y_i^2}{\lambda_i}

    Substitute the decomposition. In the principal coordinates the quadratic form has no cross terms: each coordinate is divided by its own variance.

  3. d2=k2  ⟺  ∑iyi2k2λi=1d^2 = k^2 \;\Longleftrightarrow\; \sum_i \dfrac{y_i^2}{k^2\lambda_i} = 1

    This is the equation of an ellipse (ellipsoid) with semi-axes kλik\sqrt{\lambda_i} along the axes yiy_i, that is, along the eigenvectors vi\mathbf{v}_i.

  4. Cov(y)=R⊤ΣR=Λ\mathrm{Cov}(\mathbf{y}) = R^{\top}\Sigma R = \Lambda

    In the principal coordinates the covariance is diagonal: the components yiy_i are uncorrelated and, being jointly Gaussian, independent, with variances λi\lambda_i.

The normalizing constant

  1. ∫exp⁡ ⁣(−12y⊤Λ−1y) dy=∏i∫e−yi2/(2λi) dyi=∏i2πλi=(2π)n/2∣Λ∣\int \exp\!\bigl(-\tfrac12 \mathbf{y}^{\top}\Lambda^{-1}\mathbf{y}\bigr)\,d\mathbf{y} = \prod_{i}\int e^{-y_i^2/(2\lambda_i)}\,dy_i = \prod_i \sqrt{2\pi\lambda_i} = (2\pi)^{n/2}\sqrt{|\Lambda|}

    The integral factors into one-dimensional Gaussian integrals (the last module), one per principal axis.

  2. ∣Λ∣=∣R⊤ΣR∣=∣Σ∣|\Lambda| = |R^{\top}\Sigma R| = |\Sigma|

    A rotation does not change the determinant. Dividing by this constant gives the density above.

The probability inside the ellipse, in two dimensions

Standardize each principal coordinate, zi=yi/λiz_i = y_i/\sqrt{\lambda_i}: then d2=z12+z22d^2 = z_1^2 + z_2^2, the squared distance from the origin of a point with two independent standard normal coordinates. Its density is rotation-symmetric, so switch to polar coordinates, as in the derivation of the Gaussian constant:

  1. P(d≤k)=∫02π ⁣∫0k12π e−r2/2 r dr dθP(d \le k) = \int_0^{2\pi}\!\int_0^{k} \dfrac{1}{2\pi}\, e^{-r^2/2}\, r\,dr\,d\theta

    The standard bivariate normal density is 12πe−(z12+z22)/2\tfrac{1}{2\pi}e^{-(z_1^2+z_2^2)/2}, and the area element in polar coordinates is r dr dθr\,dr\,d\theta.

  2. =∫0kr e−r2/2 dr=1−e−k2/2= \int_0^{k} r\,e^{-r^2/2}\,dr = 1 - e^{-k^2/2}

    The angle integral cancels the 1/(2π)1/(2\pi); the radial integral has the antiderivative −e−r2/2-e^{-r^2/2}.

  3. k=1:0.393k=2:0.865k=3:0.989P=0.95  ⇒  k=−2ln⁡0.05=2.448k = 1: 0.393 \qquad k = 2: 0.865 \qquad k = 3: 0.989 \qquad P = 0.95 \;\Rightarrow\; k = \sqrt{-2\ln 0.05} = 2.448

    The numbers behind the figure. Solving for the 95% ellipse inverts the formula.

In general d2d^2 is a sum of nn squared independent standard normals, which has the chi-square distribution with nn degrees of freedom. The threshold d2≤χn, p2d^2 \le \chi^2_{n,\,p} that contains a probability pp is available as chi2_ppf(p, n): 3.84, 5.99 and 7.81 for n=1,2,3n = 1, 2, 3 at p=0.95p = 0.95, which are the squares of 1.96, 2.45 and 2.80.

Use the chi-square quantile, not a fixed number of sigmas, to gate in more than one dimension: the 95% gate is 1.96σ in one dimension, 2.45σ in two and 2.80σ in three.

A worked example

Take the covariance matrix of the previous lesson, Σ=(13121213)\Sigma = \begin{pmatrix} 13 & 12 \\ 12 & 13 \end{pmatrix} cm², with mean at the origin.

  1. Eigenvalues and axes. det⁡(Σ−λI)=(13−λ)2−144=0\det(\Sigma - \lambda I) = (13 - \lambda)^2 - 144 = 0 gives λ=13±12=25,  1\lambda = 13 \pm 12 = 25,\; 1. The eigenvector of 25 is (1,1)/2(1, 1)/\sqrt{2}, at 45°; that of 1 is (−1,1)/2(-1, 1)/\sqrt{2}. The 1σ ellipse has semi-axes 25=5\sqrt{25} = 5 cm and 1=1\sqrt{1} = 1 cm. The 2σ ellipse is 10 by 2 cm.
  2. Density at the mean. ∣Σ∣=169−144=25|\Sigma| = 169 - 144 = 25, so f(0)=1/(2π25)=0.0318f(\mathbf{0}) = 1/(2\pi\sqrt{25}) = 0.0318 per cm².
  3. Two points, two distances. The inverse is Σ−1=125(13−12−1213)\Sigma^{-1} = \tfrac{1}{25}\begin{pmatrix} 13 & -12 \\ -12 & 13 \end{pmatrix}. For (4,0)(4, 0): d2=13×16/25=8.32d^2 = 13 \times 16/25 = 8.32, d=2.88d = 2.88σ. For (3,3)(3, 3): d2=(117−216+117)/25=0.72d^2 = (117 - 216 + 117)/25 = 0.72, d=0.85d = 0.85σ. The Euclidean distances, 4.00 and 4.24 cm, would have ranked them the other way round.
  4. Gate. A 95% gate in two dimensions is d2≤5.99d^2 \le 5.99. The point (4, 0) fails it (8.32) although it is close in the ordinary sense; (3, 3) passes comfortably.
  5. Check the shares by simulation. 20 000 samples: 39.6%, 86.6% and 98.9% lie inside the 1σ, 2σ and 3σ ellipses, against 39.35%, 86.47% and 98.89% from 1−e−k2/21 - e^{-k^2/2}.
  6. Other dimensions. The 95% radius is 1.96σ in one dimension, 2.448σ in two, 2.795σ in three.
import math
from robotprob import Rng, sample_mvn, mahalanobis2, eig_sym2, covariance_ellipse, chi2_ppf, mvn_pdf

S = [[13.0, 12.0], [12.0, 13.0]]
l1, l2, ang = eig_sym2(S)
print('eigenvalues', round(l1, 3), round(l2, 3), ' long axis at', round(math.degrees(ang), 1), 'degrees')
a, b, _ = covariance_ellipse(S, 1.0)
print('1-sigma semi-axes =', round(a, 2), round(b, 2), 'cm')

mu = [0.0, 0.0]
for p in ([4.0, 0.0], [3.0, 3.0]):
    d2 = mahalanobis2(p, mu, S)
    print(p, 'Euclidean', round(math.hypot(*p), 2), 'cm   Mahalanobis', round(math.sqrt(d2), 2), 'sigma   d^2 =', round(d2, 2))
print('density at the mean =', round(mvn_pdf(mu, mu, S), 4), ' (1 / (2 pi sqrt(det)) =', round(1 / (2 * math.pi * 5), 4), ')')

rng = Rng(12)
samples = [sample_mvn(rng, mu, S) for _ in range(20000)]
d2s = [mahalanobis2(p, mu, S) for p in samples]
for k in (1, 2, 3):
    inside = sum(1 for d in d2s if d <= k * k) / len(d2s)
    print(k, 'sigma ellipse holds', round(inside, 4), ' formula 1 - exp(-k^2/2) =', round(1 - math.exp(-k * k / 2), 4))
print('95% gate: d^2 <=', round(chi2_ppf(0.95, 2), 3), '=', round(math.sqrt(chi2_ppf(0.95, 2)), 3), 'sigma;  in 1D it is 1.96 sigma, in 3D', round(math.sqrt(chi2_ppf(0.95, 3)), 3))
eigenvalues 25.0 1.0  long axis at 45.0 degrees
1-sigma semi-axes = 5.0 1.0 cm
[4.0, 0.0] Euclidean 4.0 cm   Mahalanobis 2.88 sigma   d^2 = 8.32
[3.0, 3.0] Euclidean 4.24 cm   Mahalanobis 0.85 sigma   d^2 = 0.72
density at the mean = 0.0318  (1 / (2 pi sqrt(det)) = 0.0318 )
1 sigma ellipse holds 0.3963  formula 1 - exp(-k^2/2) = 0.3935
2 sigma ellipse holds 0.8661  formula 1 - exp(-k^2/2) = 0.8647
3 sigma ellipse holds 0.9891  formula 1 - exp(-k^2/2) = 0.9889
95% gate: d^2 <= 5.991 = 2.448 sigma;  in 1D it is 1.96 sigma, in 3D 2.795
eig_sym2 gives the eigenvalues and the angle of the long axis; covariance_ellipse(S, k) the semi-axes of the k-sigma ellipse; mahalanobis2 the squared Mahalanobis distance.

In robotics

Drawing and reading uncertainty

The ellipse that RViz draws around a robot's pose, the “covariance ellipse” in SLAM visualizations and every plot of a Kalman filter's position estimate is one of the contours above, usually the 1σ or 2σ one. Read the axes and the tilt: a long thin ellipse means one direction is poorly known, a round ellipse means the filter has no preferred direction. Always check which k is drawn, and remember that a 1σ ellipse holds 39% of the probability, not 68%. The SLAM course draws these in Understand Pose Uncertainty.

Gating measurements

Before a filter uses a measurement it asks how plausible it is: is the Mahalanobis distance between the measurement and its prediction below a threshold? The threshold comes from the chi-square distribution with as many degrees of freedom as the measurement has components, so a 95% gate is d² ≤ 3.84 for one number, 5.99 for a range and a bearing, 7.81 for three numbers. Using 1.96σ in every dimension would reject far too many good measurements as the dimension grows. M8-T2: EKF Localization with Landmarks applies this to landmark observations, and the UAV course to innovation monitoring (Normalized Estimation Error Squared).

Data association

When a robot sees an object that might be one of several known landmarks, the one with the smallest Mahalanobis distance is the best match, because the distance measures the observation in the units of its own uncertainty. A match by Euclidean distance would prefer a landmark that is close in the direction in which the observation is least reliable (data association, Data Association).

Comparing two estimators

Two filters that report the same variance of x can have very different covariance matrices. Compare the determinants (the volumes) for an overall measure, the eigenvalues for the worst direction, and the ellipses overlaid on a plot for the geometry. The largest eigenvalue is the worst-case standard deviation, the number that determines whether a robot fits through a door.

Plausibility checks

For a ground-truth experiment, the fraction of true errors that fall inside the filter's own k-sigma ellipse should match the figure above (39%, 86%, 99%). A filter whose 2σ ellipse contains the truth only 50% of the time is overconfident. This is the idea behind the NEES test of module 7.

Common misconceptions

“The one-sigma ellipse contains 68% of the probability.”

That is the one-dimensional figure. In two dimensions the 1σ ellipse holds 39%, the 2σ ellipse 86% and the 3σ ellipse 98.9%; the 95% ellipse is at 2.45σ. Quoting “2σ = 95%” for a 2D or 3D ellipse overstates the confidence.

“The ellipse axes are the x and y standard deviations.”

Only when the covariance is diagonal. In general the axes lie along the eigenvectors and their lengths are the square roots of the eigenvalues, which can differ a lot from σx and σy (here σx = σy = 3.6 cm, while the axes are 5 cm and 1 cm).

“The Mahalanobis distance is just a scaled Euclidean distance.”

It rescales each direction by its own spread, so two points at the same Euclidean distance can be at very different Mahalanobis distances (2.88σ and 0.85σ above). It is invariant to the choice of units and to rotating the coordinates.

“A larger determinant means a worse estimate in every direction.”

The determinant is a volume. Two estimators can have the same determinant and differ in which direction they are uncertain. For a safety margin the largest eigenvalue, or the variance along the direction of the nearest obstacle, is the number that matters.

Key takeaways

  1. A multivariate Gaussian N(μ, Σ) has contours that are ellipses centred on μ; its density falls with the squared Mahalanobis distance d² = (x − μ)ᵀΣ⁻¹(x − μ).
  2. The ellipse axes lie along the eigenvectors of Σ, with semi-axes k√λᵢ. The eigenvalues are the variances along the principal axes, and the determinant measures the volume.
  3. Mahalanobis distance counts distance in units of the standard deviation in the direction of the point, and so differs from the Euclidean distance whenever the covariance is not round.
  4. In two dimensions the 1σ, 2σ, 3σ ellipses hold 39%, 86% and 98.9%, from 1 − e^(−k²/2). The 95% ellipse is 1.96σ, 2.45σ, 2.80σ in 1, 2, 3 dimensions.
  5. Gate with the chi-square quantile for the dimension of the measurement, not a fixed number of sigmas.

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 pose estimate has covariance [[4, 0], [0, 1]] cm². Where is the 2σ ellipse’s long axis, how long are its axes, and what is the Mahalanobis distance of the point (2, 1) from the mean? Is it inside the 95% gate?

Explanation

The covariance is diagonal, so the axes lie along x and y: the standard deviations are 2 cm along x and 1 cm along y, and the 2σ ellipse has semi-axes 4 cm (along x, the long axis) and 2 cm (along y). For the point (2, 1): d² = 2²/4 + 1²/1 = 1 + 1 = 2, so d = 1.41σ. The 95% gate in two dimensions is d² ≤ 5.99, so it is comfortably inside. Notice that its Euclidean distance is 2.24 cm, larger than the y standard deviation but a modest 1.41σ overall.

Question 2

A tracker gates detections with “within 2σ” in each of x, y and z separately (a box). A colleague says that this keeps about 95% of true detections. Estimate the actual fraction if the three errors are independent, and say what ellipsoid would give 95%.

Explanation

Each coordinate is within 2σ with probability 0.9545, so a box of ±2σ in all three keeps 0.9545³ = 0.870 of true detections: about 87%, not 95%. An ellipsoid with exactly 95% needs the chi-square threshold with 3 degrees of freedom: d² ≤ 7.81, that is a radius of 2.80σ. Boxes also have corners that accept points at a Mahalanobis distance of up to 3.46σ (2σ in each of the three axes at once), which are very unlikely to be true detections.

Question 3

Two robots report the same standard deviation of 3.6 cm in both x and y. One has covariance [[13, 12], [12, 13]] and the other [[13, 0], [0, 13]]. Compare their ellipses and determinants. Which one would you prefer for a task that needs accuracy across the 45° diagonal, and which for a task that needs accuracy along it?

Explanation

The first has eigenvalues 25 and 1: a thin 1σ ellipse 5 cm by 1 cm along the 45° diagonal, determinant 25. The second has eigenvalues 13 and 13: a round 1σ circle of radius 3.6 cm, determinant 169. The first is far more certain overall (the area of its ellipse is about 2.6 times smaller, since the area scales with the square root of the determinant). Across the diagonal it is much better (1 cm against 3.6 cm); along the diagonal it is worse (5 cm against 3.6 cm). So prefer the first robot for accuracy across the diagonal and the second for accuracy along it. The variances of x and y alone are identical and could not reveal any of this.

What’s next

We can now describe the uncertainty of a vector. The next lesson asks what happens to that description when the vector is transformed: rotated, scaled, converted from polar to Cartesian coordinates, or moved by the robot.

Practice this lesson

Robot Uncertainty Visualizer

The position estimate comes with a covariance that nobody on the team can read. Compute it from samples, draw its ellipse, and push it through a rotation and a range-bearing conversion.

Next lesson

M4-T4 — Propagating Uncertainty Through Transformations

Propagate a mean and covariance through a linear map, and through a nonlinear map with a Jacobian, and say when the linear result is wrong.

Nothing below is required to finish this lesson.

  • Before
    M4-T2: Covariance and Correlation

    Compute covariance and correlation from data, read their signs and sizes physically, and separate correlation from dependence.

  • Lab
    M4-L1: Robot Uncertainty Visualizer

    The position estimate comes with a covariance that nobody on the team can read. Compute it from samples, draw its ellipse, and push it through a rotation and a range-bearing conversion.

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