Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Covariance and the multivariate Gaussian

P1.D745 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Real data comes in many features at once, and the features are rarely unrelated. The covariance matrix records how they move together, and its eigenvectors give the directions in which the data really varies. The multivariate Gaussian turns that matrix into a full probability model that appears in noise models, latent variables and generative models.

  • PCA finds the eigenvectors of the data's covariance matrix: the directions of largest variance, which are the long axes of the ellipse drawn in this lesson. (P3.C3: Principal Component Analysis, coming soon)
  • A variational autoencoder draws its latent vector as z=μ+σ⊙ϵ\mathbf{z}=\boldsymbol{\mu}+\boldsymbol{\sigma}\odot\boldsymbol{\epsilon} with ϵ∼N(0,I)\boldsymbol{\epsilon}\sim\mathcal{N}(\mathbf{0},\mathbf{I}) (the reparameterization trick), a Gaussian sample of the kind built here. (P8.3: Variational Autoencoders, coming soon)
  • Diffusion models corrupt an image with Gaussian noise in many small steps, and learn to remove it. (P8.7: Diffusion: intuition, coming soon)
  • A Gaussian mixture model describes each cluster by its own mean and covariance matrix, which is a fitted ellipse per cluster. (P3.C2: Gaussian mixtures and EM, coming soon)
  • Density-based anomaly detection can flag a point that is far from the mean in Mahalanobis distance, because that distance accounts for the spreads and the correlations of the features. (P3.C5: Anomaly detection, coming soon)
  • Strongly correlated features make X⊤X\mathbf{X}^\top\mathbf{X} nearly singular, so least-squares weights become unstable, and ridge regularization is the standard repair. (P3.A6: Regularization: L1 and L2, coming soon)
  • Batch normalization computes a mean and a variance for each feature over a batch; it standardizes the features one at a time and does not remove correlations between them (that would be whitening). (P4.19: Normalization layers, coming soon)

Before this: Common distributions, Expectation and variance, Joint, marginal and conditional probability, Transpose, symmetric and orthogonal matrices, Eigenvalues and eigenvectors

After this lesson you can

  • Compute the covariance and the correlation of two variables from a small data set by hand, read their signs, and explain why the correlation (unlike the covariance) has no units, stays between −1-1 and 11, and sees only straight-line relations
  • Build the covariance matrix Σ\boldsymbol{\Sigma} of a random vector or of centred data, and use it to get the variance in any direction (w⊤Σw\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}) and the covariance of a linear transform (AΣA⊤\mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top)
  • Read the multivariate Gaussian: the Mahalanobis distance in its exponent, the ellipse whose axes are the eigenvectors of Σ\boldsymbol{\Sigma} with half-lengths proportional to the square roots of the eigenvalues, and the two-variable case written with σx\sigma_x, σy\sigma_y and ρ\rho
  • Get the marginals and conditionals of a two-variable Gaussian (the conditional mean is the regression line), say when uncorrelated means independent, and sample from N(μ,Σ)\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma}) with x=μ+Lz\mathbf{x}=\boldsymbol{\mu}+\mathbf{L}\mathbf{z}

Taller people tend to weigh more. Students who study more tend to score higher. In each pair, the two numbers move together, but not perfectly. How do you put one number on “move together”? And if you plot thousands of such pairs, what shape does the cloud have?

The answers are covariance and an ellipse. This lesson builds both from five students, and then shows that the ellipse is the outline of the most important distribution in machine learning, the multivariate Gaussian.

Covariance: do two numbers move together?

Five students studied for x=1,2,3,4,5x=1,2,3,4,5 hours and scored y=2,1,4,3,5y=2,1,4,3,5 points on a short quiz (invented numbers). Both averages are 33. For each student, measure how far each number is from its average, and multiply the two deviations:

hours xxscore yyx−3x-3y−3y-3product
1122−2-2−1-122
2211−1-1−2-222
3344001100
4433110000
5555222244

A product is positive when both numbers are on the same side of their averages (both above or both below), and negative when they are on opposite sides. The products add up to 88. Treating the five students as equally likely (each has probability 15\frac15), their average is the covariance:

Cov(X,Y)=E[(X−μX)(Y−μY)]=85=1.6.\begin{aligned} \mathrm{Cov}(X,Y)&=\mathbb{E}\bigl[(X-\mu_X)(Y-\mu_Y)\bigr]\\ &=\tfrac85=1.6. \end{aligned}

Compare with the variance (P1.D4), the average of (X−μX)2(X-\mu_X)^2. The variance multiplies a deviation by itself; the covariance multiplies the deviation of one variable by the deviation of another. So Cov(X,X)=Var(X)\mathrm{Cov}(X,X)=\mathrm{Var}(X).

Reading the sign. Draw a cross at the point (μX,μY)(\mu_X,\mu_Y). It cuts the plane into four quadrants. Points in the upper-right and lower-left quadrants have positive products; points in the upper-left and lower-right have negative products. If most points sit in the first pair, the covariance is positive and the cloud leans up to the right. If most sit in the second pair, it is negative and the cloud leans down to the right. If the two kinds balance, the covariance is 00: there is no straight-line tendency.

A shortcut. Expanding the product and using linearity of expectation (P1.D4) gives

Cov(X,Y)=E[XY]−μXμY,\mathrm{Cov}(X,Y)=\mathbb{E}[XY]-\mu_X\mu_Y,

just as Var(X)=E[X2]−μX2\mathrm{Var}(X)=\mathbb{E}[X^2]-\mu_X^2. For the students, E[XY]=2+2+12+12+255=10.6\mathbb{E}[XY]=\frac{2+2+12+12+25}{5}=10.6 and μXμY=9\mu_X\mu_Y=9, so 10.6−9=1.610.6-9=1.6 again.

Units. The unit of a covariance is the unit of XX times the unit of YY (hours times points here). Measure the hours in minutes and every xx and every deviation becomes 6060 times as large, so the covariance becomes 6060 times as large, with no change in how the students relate to each other. So the size of a covariance cannot be judged without the units. The next section fixes this.

Rules for covariance

  • Symmetric. Cov(X,Y)=Cov(Y,X)\mathrm{Cov}(X,Y)=\mathrm{Cov}(Y,X).
  • Shifts do nothing, scaling scales. Cov(aX+b, Y)=a Cov(X,Y)\mathrm{Cov}(aX+b,\,Y)=a\,\mathrm{Cov}(X,Y). Adding a constant moves the mean by the same amount, so the deviations do not change.
  • Splits over sums. Cov(X+Z, Y)=Cov(X,Y)+Cov(Z,Y)\mathrm{Cov}(X+Z,\,Y)=\mathrm{Cov}(X,Y)+\mathrm{Cov}(Z,Y). Together with the rule above, covariance is bilinear: linear in each argument.
  • The cross term of a sum. Var(X+Y)=Var(X)+Var(Y)+2 Cov(X,Y)\mathrm{Var}(X+Y)=\mathrm{Var}(X)+\mathrm{Var}(Y)+2\,\mathrm{Cov}(X,Y), the term P1.D4 left open. For the students, Var(X)=Var(Y)=2\mathrm{Var}(X)=\mathrm{Var}(Y)=2 and Cov=1.6\mathrm{Cov}=1.6, so the variance of x+yx+y is 2+2+3.2=7.22+2+3.2=7.2. For one fair die XX and Y=7−XY=7-X, Cov(X,Y)=−Var(X)=−3512\mathrm{Cov}(X,Y)=-\mathrm{Var}(X)=-\frac{35}{12}, and the sum is always 77: 3512+3512−2⋅3512=0\frac{35}{12}+\frac{35}{12}-2\cdot\frac{35}{12}=0.
  • Independent implies zero covariance. If XX and YY are independent then E[XY]=E[X]E[Y]\mathbb{E}[XY]=\mathbb{E}[X]\mathbb{E}[Y], so Cov(X,Y)=0\mathrm{Cov}(X,Y)=0 (P1.D5). The converse is false: for XX uniform on {−2,−1,0,1,2}\{-2,-1,0,1,2\} and Y=X2Y=X^2, the covariance is 00 but YY is a function of XX.

Correlation: covariance without units

Divide the covariance by the two standard deviations. The result is the correlation coefficient

ρ=Cov(X,Y)σX σY\rho=\frac{\mathrm{Cov}(X,Y)}{\sigma_X\,\sigma_Y}

(defined when both standard deviations are positive). For the students, σX=σY=2\sigma_X=\sigma_Y=\sqrt2, so ρ=1.62=0.8\rho=\frac{1.6}{2}=0.8. The units cancel, so minutes instead of hours give the same 0.80.8. Replacing XX by aX+baX+b with a>0a>0 changes nothing; with a<0a<0 it flips the sign of ρ\rho (reversing the hours gives −0.8-0.8).

Three facts about ρ\rho:

  • It always lies between −1-1 and 11. This follows from the Cauchy–Schwarz inequality (the box below).
  • It equals 11 or −1-1 exactly when YY is an exact straight-line function of XX, Y=aX+bY=aX+b with a>0a\gt0 for ρ=1\rho=1 and a<0a\lt0 for ρ=−1\rho=-1 (and a≠0a\ne0).
  • It is a cosine. Write the centred data as two vectors, (−2,−1,0,1,2)(-2,-1,0,1,2) and (−1,−2,1,0,2)(-1,-2,1,0,2). Their dot product is 88 and each has length 10\sqrt{10}, so the cosine of the angle between them is 810=0.8\frac{8}{10}=0.8, an angle of about 36.9∘36.9^\circ. Correlation is the cosine similarity of P1.B3 applied to centred data, so the geometry carries over: a small angle means a high correlation, and perpendicular centred vectors mean ρ=0\rho=0.
Go deeper Why correlation never leaves the range from −1 to 1

For any number tt, a variance is never negative, so

0≤Var(Y−tX)=Var(Y)−2t Cov(X,Y)+t2 Var(X).\begin{aligned} 0&\le\mathrm{Var}(Y-tX)\\ &=\mathrm{Var}(Y)-2t\,\mathrm{Cov}(X,Y)\\ &\quad+t^2\,\mathrm{Var}(X). \end{aligned}

Take t=Cov(X,Y)/Var(X)t=\mathrm{Cov}(X,Y)/\mathrm{Var}(X). The right side becomes Var(Y)−Cov(X,Y)2/Var(X)\mathrm{Var}(Y)-\mathrm{Cov}(X,Y)^2/\mathrm{Var}(X), which gives Cov(X,Y)2≤Var(X) Var(Y)\mathrm{Cov}(X,Y)^2\le\mathrm{Var}(X)\,\mathrm{Var}(Y), that is ρ2≤1\rho^2\le1. This is the Cauchy–Schwarz inequality for random variables. Equality needs Var(Y−tX)=0\mathrm{Var}(Y-tX)=0, which means Y−tXY-tX is a constant: YY is an exact straight-line function of XX.

The same calculation is useful on its own: Var(Y)−Cov(X,Y)2/Var(X)=σY2(1−ρ2)\mathrm{Var}(Y)-\mathrm{Cov}(X,Y)^2/\mathrm{Var}(X)=\sigma_Y^2(1-\rho^2) is the smallest mean squared error that any straight-line prediction a+bXa+bX of YY can reach (the best line is b=tb=t). For the students, ρ2=0.64\rho^2=0.64 of the variance of yy is accounted for by the best line, and 0.360.36 is left over.

What correlation cannot see

Correlation measures only straight-line association.

  • For XX uniform on {−2,−1,0,1,2}\{-2,-1,0,1,2\} and Y=X2Y=X^2 (the table of P1.D5), ρ=0\rho=0, although YY is completely determined by XX. A perfect curve is invisible to it.
  • Anscombe’s quartet (Anscombe, 1973) is four small data sets with almost identical means and variances, the same correlation (ρ≈0.816\rho\approx0.816) and the same best line (y≈3+0.5xy\approx3+0.5x), yet one is a noisy straight-line trend, one is a curve, one has a single outlier and one is a vertical stack with a single far-away point. Always plot the data.
  • Outliers can dominate. Add one student who studied 2020 hours and scored 00 to the five above and ρ\rho drops from 0.80.8 to −0.52-0.52.
  • Correlation is not causation. A third quantity can drive both (hot weather raises both ice-cream sales and swimming), or the direction can be the opposite of what you assume. P1.D13 returns to this.

From data: the sample covariance

With data, you do not know the expectation, so you average over the examples. The sample covariance of nn pairs is

c^=1n−1∑i=1n(xi−xˉ)(yi−yˉ),\hat{c}=\frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar x)(y_i-\bar y),

with the same “divide by n−1n-1” as the sample variance in P1.D4. For the five students the sum is 88, so c^=84=2\hat c=\frac84=2; the sample variances are 104=2.5\frac{10}{4}=2.5 each; and ρ\rho is 22.5=0.8\frac{2}{2.5}=0.8 once more. The factor cancels in the correlation, so the choice of nn or n−1n-1 does not matter for ρ\rho. Dividing by nn instead gives the maximum-likelihood estimate for a Gaussian (P1.D10); both agree for large nn.

In NumPy, np.cov(x, y) returns the whole matrix, here (2.5222.5)\begin{pmatrix}2.5&2\\2&2.5\end{pmatrix}, and np.corrcoef(x, y) returns the correlations. By default np.cov treats each row as one variable, so for a data matrix with one example per row you must pass rowvar=False, or you get an N×NN\times N matrix instead of a d×dd\times d one.

The covariance matrix

A random vector x=(x1,…,xd)\mathbf{x}=(x_1,\dots,x_d) has dd variances and d(d−1)/2d(d-1)/2 different covariances. Collect them in one matrix Σ\boldsymbol{\Sigma} with entries Σij=Cov(xi,xj)\Sigma_{ij}=\mathrm{Cov}(x_i,x_j). In one line:

Σ=E[(x−μ)(x−μ)⊤].\boldsymbol{\Sigma}=\mathbb{E}\bigl[(\mathbf{x}-\boldsymbol{\mu})(\mathbf{x}-\boldsymbol{\mu})^\top\bigr].

The product of a column with a row is a d×dd\times d matrix whose (i,j)(i,j) entry is the deviation of xix_i times the deviation of xjx_j; Σ\boldsymbol{\Sigma} is its average. Three properties:

  • The diagonal holds the variances, Σii=Var(xi)\Sigma_{ii}=\mathrm{Var}(x_i). Their sum, the trace, is the total variance.
  • Σ\boldsymbol{\Sigma} is symmetric, because Cov(xi,xj)=Cov(xj,xi)\mathrm{Cov}(x_i,x_j)=\mathrm{Cov}(x_j,x_i) (P1.B10).
  • Σ\boldsymbol{\Sigma} is positive semi-definite: w⊤Σw≥0\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}\ge0 for every vector w\mathbf{w}. The next subsection explains why.

From data. Put the data in an N×dN\times d matrix X\mathbf{X} with one example per row, and subtract each column’s mean to centre it. Then the sample covariance matrix is X⊤X/(N−1)\mathbf{X}^\top\mathbf{X}/(N-1) (or /N/N). For the four points (−2,−1)(-2,-1), (1,2)(1,2), (1,−1)(1,-1), (0,0)(0,0) of P1.B13, which have mean (0,0)(0,0), X⊤X=(6336)\mathbf{X}^\top\mathbf{X}=\begin{pmatrix}6&3\\3&6\end{pmatrix}, so

Σ=13(6336)=(2112),\boldsymbol{\Sigma}=\frac13\begin{pmatrix}6&3\\3&6\end{pmatrix}=\begin{pmatrix}2&1\\1&2\end{pmatrix},

the matrix of P1.B12. Its variances are 22 and 22, its correlation is 12⋅2=0.5\frac{1}{\sqrt{2\cdot2}}=0.5, its trace is 44 and its determinant is 33. We reuse it below.

Variance in any direction

Take a fixed vector w\mathbf{w} and look at the single number w⊤x\mathbf{w}^\top\mathbf{x} for each example: the amount of x\mathbf{x} along w\mathbf{w} (for a unit vector, its coordinate in that direction). Its variance is

Var(w⊤x)=w⊤Σ w.\mathrm{Var}(\mathbf{w}^\top\mathbf{x})=\mathbf{w}^\top\boldsymbol{\Sigma}\,\mathbf{w}.

For Σ=(2112)\boldsymbol{\Sigma}=\begin{pmatrix}2&1\\1&2\end{pmatrix}:

  • w=(1,0)\mathbf{w}=(1,0) gives 22, the variance of x1x_1.
  • w=(1,1)\mathbf{w}=(1,1) gives 2+2+2⋅1=62+2+2\cdot1=6. This is Var(x1+x2)\mathrm{Var}(x_1+x_2), the sum rule above, now as a special case of a general rule.
  • w=(1,−1)\mathbf{w}=(1,-1) gives 2+2−2=22+2-2=2. The difference of two positively correlated variables varies less than their sum.
  • The unit directions 12(1,1)\frac{1}{\sqrt2}(1,1) and 12(1,−1)\frac{1}{\sqrt2}(1,-1) give 33 and 11: the eigenvalues of P1.B12. Over all unit directions the variance is largest along the top eigenvector, and smallest along the other.

Since a variance cannot be negative, w⊤Σw≥0\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}\ge0 for every w\mathbf{w}, which is the definition of positive semi-definite. This is also a test: (1221)\begin{pmatrix}1&2\\2&1\end{pmatrix} is symmetric but cannot be a covariance matrix, because w=(1,−1)\mathbf{w}=(1,-1) gives 1+1−4=−21+1-4=-2. If w⊤Σw=0\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}=0 for some non-zero w\mathbf{w}, the data have no spread in that direction: they lie on a line (or a plane, and so on) and Σ\boldsymbol{\Sigma} is singular.

Go deeper Why the variance in a direction is wᵀΣw, and what a linear map does to Σ

The number w⊤x\mathbf{w}^\top\mathbf{x} has mean w⊤μ\mathbf{w}^\top\boldsymbol{\mu}, so

Var(w⊤x)=E[(w⊤(x−μ))2]=E[w⊤(x−μ)×(x−μ)⊤w]=w⊤Σ w.\begin{aligned} \mathrm{Var}(\mathbf{w}^\top\mathbf{x})&=\mathbb{E}\bigl[(\mathbf{w}^\top(\mathbf{x}-\boldsymbol{\mu}))^2\bigr]\\ &=\mathbb{E}\bigl[\mathbf{w}^\top(\mathbf{x}-\boldsymbol{\mu})\\ &\qquad\times(\mathbf{x}-\boldsymbol{\mu})^\top\mathbf{w}\bigr]\\ &=\mathbf{w}^\top\boldsymbol{\Sigma}\,\mathbf{w}. \end{aligned}

The same steps for a matrix A\mathbf{A} give a rule for a whole linear transform: y=Ax+b\mathbf{y}=\mathbf{A}\mathbf{x}+\mathbf{b} has mean Aμ+b\mathbf{A}\boldsymbol{\mu}+\mathbf{b} and covariance matrix

Cov(y)=AΣA⊤.\mathrm{Cov}(\mathbf{y})=\mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top.

If A\mathbf{A} is a single row w⊤\mathbf{w}^\top, this is the formula above. Example: take A=12(111−1)\mathbf{A}=\frac1{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix}, whose rows are the two eigenvectors of (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}. Then AΣA⊤=(3001)\mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top=\begin{pmatrix}3&0\\0&1\end{pmatrix}. The new coordinates are uncorrelated, with variances 33 and 11. Rotating the data onto the eigenvectors of its covariance matrix decorrelates it, and this is what PCA (P3.C3) does.

The multivariate Gaussian

In one variable the Gaussian density (P1.D3) is proportional to e−z2/2\mathrm{e}^{-z^2/2} with z=(x−μ)/σz=(x-\mu)/\sigma: the number of standard deviations from the mean. To go to several variables, keep the same shape and replace z2z^2 by a squared distance that accounts for the spreads and the correlations. It is the squared Mahalanobis distance

d2=(x−μ)⊤Σ−1(x−μ).d^2=(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}).

For one variable, Σ=σ2\boldsymbol{\Sigma}=\sigma^2 and d2=z2d^2=z^2. The density of x∼N(μ,Σ)\mathbf{x}\sim\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma}), for a dd-dimensional x\mathbf{x} and a Σ\boldsymbol{\Sigma} with det⁡Σ>0\det\boldsymbol{\Sigma}\gt0, is

p(x)=1(2π)ddet⁡Σexp⁡(−12d2).p(\mathbf{x})=\frac{1}{\sqrt{(2\pi)^d\det\boldsymbol{\Sigma}}}\exp\Bigl(-\frac12d^2\Bigr).

The factor in front makes the total probability 11. It uses the determinant (P1.B8): a wider spread means a larger det⁡Σ\det\boldsymbol{\Sigma}, so the same probability is spread over more volume and the peak is lower. For Σ=(4001)\boldsymbol{\Sigma}=\begin{pmatrix}4&0\\0&1\end{pmatrix}, det⁡Σ=4\det\boldsymbol{\Sigma}=4 and the peak height in two variables is 12π4=14π≈0.0796\frac{1}{2\pi\sqrt4}=\frac1{4\pi}\approx0.0796. For (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}, det⁡Σ=3\det\boldsymbol{\Sigma}=3 and the peak is 12π3≈0.0919\frac{1}{2\pi\sqrt3}\approx0.0919. The inverse Σ−1\boldsymbol{\Sigma}^{-1} is found as in P1.B9; here it is 13(2−1−12)\frac13\begin{pmatrix}2&-1\\-1&2\end{pmatrix}. In code, Σ−1v\boldsymbol{\Sigma}^{-1}\mathbf{v} is computed by solving Σu=v\boldsymbol{\Sigma}\mathbf{u}=\mathbf{v} (np.linalg.solve), not by forming the inverse.

What dd measures. Take μ=0\boldsymbol{\mu}=\mathbf{0} and Σ=(2112)\boldsymbol{\Sigma}=\begin{pmatrix}2&1\\1&2\end{pmatrix}. The points (1,1)(1,1) and (1,−1)(1,-1) are equally far from the mean in the ordinary sense, 2\sqrt2. But d2=23d^2=\frac23 for (1,1)(1,1) and d2=2d^2=2 for (1,−1)(1,-1): the first lies along the cloud’s long direction, where points are common, and the second lies across it, where they are rare. The Mahalanobis distance is d=0.82d=0.82 for the first and d=1.41d=1.41 for the second. It is a distance in units of the cloud’s own spread.

The outline is an ellipse

The points at the same density are those with the same dd. A level set d2=k2d^2=k^2 is an ellipse. To see why, use P1.B12: a symmetric Σ\boldsymbol{\Sigma} can be written Σ=UΛU⊤\boldsymbol{\Sigma}=\mathbf{U}\boldsymbol{\Lambda}\mathbf{U}^\top, with orthonormal eigenvectors ui\mathbf{u}_i as the columns of U\mathbf{U} and eigenvalues λi\lambda_i on the diagonal of Λ\boldsymbol{\Lambda}. Then Σ−1=UΛ−1U⊤\boldsymbol{\Sigma}^{-1}=\mathbf{U}\boldsymbol{\Lambda}^{-1}\mathbf{U}^\top, and

d2=∑i(ui⊤(x−μ))2λi.d^2=\sum_{i}\frac{\bigl(\mathbf{u}_i^\top(\mathbf{x}-\boldsymbol{\mu})\bigr)^2}{\lambda_i}.

In coordinates measured along the eigenvectors, d2d^2 is a sum of squares, each divided by the variance in that direction. The set where the sum equals k2k^2 is an ellipse centred at μ\boldsymbol{\mu}, with its axes along the eigenvectors and half-lengths kλik\sqrt{\lambda_i}.

For (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}, the eigenvalues are 33 and 11 with eigenvectors 12(1,1)\frac{1}{\sqrt2}(1,1) and 12(1,−1)\frac1{\sqrt2}(1,-1). The 1σ1\sigma ellipse (k=1k=1) has half-length 3≈1.73\sqrt3\approx1.73 along (1,1)(1,1) and 11 along (1,−1)(1,-1); the 2σ2\sigma ellipse (k=2k=2) has 3.463.46 and 22. Check: the tip 3/2 (1,1)=(1.22,1.22)\sqrt{3/2}\,(1,1)=(1.22,1.22) has d2=23⋅1.5=1d^2=\frac23\cdot1.5=1. In general, the long axis shows the direction of largest variance, and the ratio of the two half-lengths shows how stretched the cloud is.

A common trap: the 1σ1\sigma ellipse does not hold 68%68\% of the points. In two variables it holds 1−e−1/2≈39%1-\mathrm{e}^{-1/2}\approx39\%, the 2σ2\sigma ellipse holds 1−e−2≈86%1-\mathrm{e}^{-2}\approx86\% and the 3σ3\sigma ellipse 1−e−9/2≈99%1-\mathrm{e}^{-9/2}\approx99\% (the box below explains). The familiar 6868–9595–99.799.7 rule of P1.D3 is for one variable.

Go deeper Why the 1σ ellipse holds only about 39%

Whiten the variable: z=L−1(x−μ)\mathbf{z}=\mathbf{L}^{-1}(\mathbf{x}-\boldsymbol{\mu}) (the sampling section below shows how) has independent standard Gaussian entries, and d2=z12+z22d^2=z_1^2+z_2^2 is the squared distance from the origin in the z\mathbf{z} plane. The density of z\mathbf{z} depends only on that distance rr, and the probability of a ring between rr and r+drr+\mathrm{d}r is 12πe−r2/2⋅2πr dr=r e−r2/2dr\frac{1}{2\pi}\mathrm{e}^{-r^2/2}\cdot2\pi r\,\mathrm{d}r=r\,\mathrm{e}^{-r^2/2}\mathrm{d}r. Integrating from 00 to kk gives P(d≤k)=1−e−k2/2\mathbb{P}(d\le k)=1-\mathrm{e}^{-k^2/2}. A simulation of two million points from the example above agrees: 0.39360.3936, 0.86480.8648, 0.98890.9889 inside the 1σ1\sigma, 2σ2\sigma and 3σ3\sigma ellipses. In more variables the fraction inside the 1σ1\sigma ellipsoid is smaller still, so most of the probability is farther out than 1σ1\sigma.

Two variables: σx\sigma_x, σy\sigma_y and ρ\rho

In two variables, write

Σ=(σx2ρ σxσyρ σxσyσy2),\boldsymbol{\Sigma}=\begin{pmatrix}\sigma_x^2&\rho\,\sigma_x\sigma_y\\\rho\,\sigma_x\sigma_y&\sigma_y^2\end{pmatrix}, det⁡Σ=σx2σy2(1−ρ2).\det\boldsymbol{\Sigma}=\sigma_x^2\sigma_y^2(1-\rho^2).

The matrix is positive definite (so the density exists) exactly when −1<ρ<1-1\lt\rho\lt1. With zx=(x−μx)/σxz_x=(x-\mu_x)/\sigma_x and zy=(y−μy)/σyz_y=(y-\mu_y)/\sigma_y, the density is

p(x,y)=12πσxσy1−ρ2×exp⁡(−zx2−2ρzxzy+zy22(1−ρ2)).\begin{aligned} p(x,y)&=\frac{1}{2\pi\sigma_x\sigma_y\sqrt{1-\rho^2}}\\ &\times\exp\Bigl(-\frac{z_x^2-2\rho z_xz_y+z_y^2}{2(1-\rho^2)}\Bigr). \end{aligned}

Three cases to keep in mind:

  • ρ=0\rho=0, σx=σy\sigma_x=\sigma_y: Σ\boldsymbol{\Sigma} is a multiple of the identity and the outline is a circle. Every direction is an eigenvector.
  • ρ=0\rho=0, σx≠σy\sigma_x\ne\sigma_y: the outline is an ellipse with axes along the xx and yy axes.
  • ρ≠0\rho\ne0: the ellipse is tilted. Positive ρ\rho tilts it up to the right, negative ρ\rho down to the right, and larger ∣ρ∣|\rho| makes it thinner.

When ρ=±1\rho=\pm1, det⁡Σ=0\det\boldsymbol{\Sigma}=0: the matrix is singular, Σ−1\boldsymbol{\Sigma}^{-1} does not exist, and the formula above divides by 00. All the probability lies on one straight line, so there is no density in the plane (the ellipse has collapsed to a segment). When ∣ρ∣|\rho| is close to 11, the entries of Σ−1\boldsymbol{\Sigma}^{-1} are huge and the numbers become unstable, and a common remedy is to add a tiny multiple of the identity to Σ\boldsymbol{\Sigma}.

Drag the ellipse

The widget draws 400400 points from a Gaussian with mean (0,0)(0,0), together with the 1σ1\sigma ellipse (solid) and the 2σ2\sigma ellipse (dashed). The green lines are the eigenvector axes. Drag the open circle on the long axis to rotate and stretch the ellipse, drag the other one to make it thinner or fatter, or use the sliders. The matrix Σ\boldsymbol{\Sigma}, the sample matrix Σ^\hat{\boldsymbol{\Sigma}} of the drawn points, the eigenvalues and the eigenvectors update as you go.

Drag the ellipse: one covariance matrix, one cloud

−6−4−2246−6−4−2246xyλ₁ = 3λ₂ = 11σ2σ
Cloud shape:
Σ = 2112
sample Σ = 2.211.021.021.93
ρ = 0.5, σx = 1.41, σy = 1.41
sample ρ = 0.49 (400 drawn points)
det Σ = 3, trace = 4
λ₁ = 3, λ₂ = 1
u₁ = (0.707, 0.707), half-length of the 1σ ellipse √λ₁ = 1.732
u₂ = (−0.707, 0.707), half-length √λ₂ = 1

ρ = 0.5: positive correlation. The cloud leans up to the right, along the first eigenvector u₁ (the long axis).

Dots: 400 points drawn from a distribution with mean (0, 0). Solid ring: the 1σ ellipse; dashed ring: the 2σ ellipse. Green lines: the eigenvector axes of Σ (dashed green: the short one). Drag the two open circles (or focus one and use the arrow keys; hold Shift for finer steps), or use the sliders. Pink: the line E[y | x] and the slice. Points outside the frame still count in the sample Σ.

A cloud of 400 points drawn from a distribution with mean (0, 0), the 1σ ellipse (solid) and the 2σ ellipse (dashed) of a covariance matrix Σ. The green lines are the eigenvector axes of Σ; the open circles at the tips of the 1σ axes are handles. Drag them (or focus one and use the arrow keys) to rotate and stretch the ellipse, or use the three sliders for σx, σy and ρ. The readouts show Σ, the sample covariance matrix of the drawn points, the correlation, the determinant, the eigenvalues and the eigenvectors. The cloud-shape buttons replace the Gaussian cloud by a uniform square or a ring that has the same covariance matrix, and New sample draws different random points. Tick Condition on x to see the slice of the cloud at one value of x, the line E[y | x] in pink, and the conditional mean and spread there. At ρ = 1 or −1 the matrix is singular and the ellipse collapses to a segment.

Try these:

  1. Press Example (ρ = 0.5). The matrix is (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}, the eigenvalues are 33 and 11, and u1=(0.707,0.707)\mathbf{u}_1=(0.707,0.707) (the two eigenvectors may be shown with a different sign). The long half-length is 3=1.73\sqrt3=1.73, and the sample matrix Σ^\hat{\boldsymbol{\Sigma}} (labelled “sample Σ”) is close to Σ\boldsymbol{\Sigma} but not equal to it.
  2. Drag the long-axis circle around the origin. When the long axis lies on the xx axis (and σx>σy\sigma_x\gt\sigma_y), ρ=0\rho=0. When it passes through the second and fourth quadrants, ρ\rho is negative.
  3. Slide ρ\rho to 11. The ellipse collapses to a segment, the determinant is 00, and the status says the density is undefined. Move ρ\rho back to 0.990.99 and watch the short half-length and the determinant.
  4. Choose Ring or Uniform square. The ellipses and Σ\boldsymbol{\Sigma} do not change and Σ^\hat{\boldsymbol{\Sigma}} stays close to Σ\boldsymbol{\Sigma}, although the cloud looks nothing like a Gaussian. The covariance matrix does not determine the shape.
  5. Tick Condition on x with the example matrix and set x=2x=2. The pink line is E[y∣x]=0.5x\mathbb{E}[y\mid x]=0.5x, so the conditional mean is 11, and the conditional standard deviation is 1.5=1.22\sqrt{1.5}=1.22, smaller than the 2=1.41\sqrt2=1.41 of the whole cloud. The points in the strip give similar numbers. Notice that the pink line is flatter than the long axis.

Marginals and conditionals of a Gaussian

P1.D5 showed how to get marginals and conditionals from a joint table. For a Gaussian, the answers stay Gaussian and have formulas.

Marginals: drop rows and columns. If x∼N(μ,Σ)\mathbf{x}\sim\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma}), any subset of its entries is Gaussian, with the matching entries of μ\boldsymbol{\mu} and the matching rows and columns of Σ\boldsymbol{\Sigma}. In two variables, x∼N(μx,σx2)x\sim\mathcal{N}(\mu_x,\sigma_x^2) and y∼N(μy,σy2)y\sim\mathcal{N}(\mu_y,\sigma_y^2), whatever ρ\rho is. This is P1.D5’s warning again: the marginals do not contain ρ\rho, so they cannot tell a thin tilted ellipse from a circle.

Conditionals: slice, then read off. Fix xx and look at the vertical slice of the cloud. Given X=xX=x, YY is Gaussian with

μy∣x=μy+ρσyσx(x−μx),σy∣x2=σy2 (1−ρ2).\begin{aligned} \mu_{y\mid x}&=\mu_y+\rho\frac{\sigma_y}{\sigma_x}(x-\mu_x),\\ \sigma_{y\mid x}^2&=\sigma_y^2\,(1-\rho^2). \end{aligned}

Two things to notice:

  • The conditional mean is a straight line in xx, the regression line, with slope ρ σy/σx\rho\,\sigma_y/\sigma_x. This is the conditional expectation E[Y∣X=x]\mathbb{E}[Y\mid X=x] of P1.D5, and fitting this line to data is linear regression (P3.A2). The line goes through the midpoint of every vertical chord of the ellipse. It is not the long axis: for the matrix (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix} the long axis has slope 11 and the regression line has slope 0.50.5.
  • The conditional variance is the same for every xx, and it is smaller than σy2\sigma_y^2 whenever ρ≠0\rho\ne0. Knowing xx removes the fraction ρ2\rho^2 of the variance of yy. With ρ=0.5\rho=0.5, σx=σy=2\sigma_x=\sigma_y=\sqrt2: the slope is 0.50.5, the conditional variance is 2(1−0.25)=1.52(1-0.25)=1.5, and at x=2x=2 the conditional distribution is N(1, 1.5)\mathcal{N}(1,\,1.5). A simulation of points with xx near 22 gives a mean near 11 and a variance near 1.51.5.

Regression to the mean. With ρ=0.5\rho=0.5, a value of xx that is two standard deviations above its mean predicts a yy only ρ⋅2=1\rho\cdot2=1 standard deviation above its mean. The prediction is pulled back toward the mean unless ∣ρ∣=1|\rho|=1.

The two regression lines differ. Predicting xx from yy has slope ρ σx/σy\rho\,\sigma_x/\sigma_y in the (y,x)(y,x) coordinates. The product of the two slopes is ρ2\rho^2, which is 11 only for a perfect straight line. So the line for yy from xx and the line for xx from yy are different lines whenever ∣ρ∣<1|\rho|\lt1.

Uncorrelated and independent. If ρ=0\rho=0, Σ\boldsymbol{\Sigma} is diagonal, d2=zx2+zy2d^2=z_x^2+z_y^2, and the density is the product of two one-variable Gaussians. So for a jointly Gaussian pair, uncorrelated means independent. This is special to the Gaussian: in general, zero covariance is weaker than independence (the Y=X2Y=X^2 example), and two variables that are each Gaussian need not be jointly Gaussian.

Go deeper Two Gaussians that are uncorrelated but not independent

Let X∼N(0,1)X\sim\mathcal{N}(0,1), and let SS be a fair coin giving +1+1 or −1-1, independent of XX. Define Y=SXY=SX. Then YY is also N(0,1)\mathcal{N}(0,1), because flipping the sign of a symmetric variable at random does not change its distribution. The covariance is E[XY]=E[S] E[X2]=0⋅1=0\mathbb{E}[XY]=\mathbb{E}[S]\,\mathbb{E}[X^2]=0\cdot1=0. But ∣Y∣=∣X∣|Y|=|X| always, so the two are as dependent as can be (knowing XX leaves only two possible values of YY). The pair (X,Y)(X,Y) is not a bivariate Gaussian: X+YX+Y equals 00 with probability 12\frac12, which no Gaussian does. Each marginal being Gaussian is not enough; the joint must be Gaussian too.

Go deeper The conditional of a Gaussian in any dimension

Split x\mathbf{x} into two blocks a\mathbf{a} and b\mathbf{b}, with μ\boldsymbol{\mu} and Σ\boldsymbol{\Sigma} split to match: blocks Σaa\boldsymbol{\Sigma}_{aa}, Σab\boldsymbol{\Sigma}_{ab}, Σba\boldsymbol{\Sigma}_{ba}, Σbb\boldsymbol{\Sigma}_{bb}. Given b\mathbf{b}, the vector a\mathbf{a} is Gaussian with

μa∣b=μa+ΣabΣbb−1(b−μb),Σa∣b=Σaa−ΣabΣbb−1Σba.\begin{aligned} \boldsymbol{\mu}_{a\mid b}&=\boldsymbol{\mu}_a+\boldsymbol{\Sigma}_{ab}\boldsymbol{\Sigma}_{bb}^{-1}(\mathbf{b}-\boldsymbol{\mu}_b),\\ \boldsymbol{\Sigma}_{a\mid b}&=\boldsymbol{\Sigma}_{aa}-\boldsymbol{\Sigma}_{ab}\boldsymbol{\Sigma}_{bb}^{-1}\boldsymbol{\Sigma}_{ba}. \end{aligned}

It is the formula for predicting some coordinates from the others. In two variables with a=y\mathbf{a}=y and b=x\mathbf{b}=x, Σyx/Σxx=ρσyσx/σx2=ρσy/σx\Sigma_{yx}/\Sigma_{xx}=\rho\sigma_y\sigma_x/\sigma_x^2=\rho\sigma_y/\sigma_x gives the slope above, and σy2−ρ2σy2σx2/σx2=σy2(1−ρ2)\sigma_y^2-\rho^2\sigma_y^2\sigma_x^2/\sigma_x^2=\sigma_y^2(1-\rho^2) gives the variance. For (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}: 2−1⋅12⋅1=1.52-1\cdot\frac12\cdot1=1.5.

Sampling: x=μ+Lz\mathbf{x}=\boldsymbol{\mu}+\mathbf{L}\mathbf{z}

How does the widget draw its points? Start from z\mathbf{z}, a vector of independent standard Gaussians (mean 00, variance 11 each), so Cov(z)=I\mathrm{Cov}(\mathbf{z})=\mathbf{I}. Find a matrix L\mathbf{L} with LL⊤=Σ\mathbf{L}\mathbf{L}^\top=\boldsymbol{\Sigma}, and set

x=μ+Lz.\mathbf{x}=\boldsymbol{\mu}+\mathbf{L}\mathbf{z}.

A linear map of a Gaussian vector is Gaussian, and the rule AΣA⊤\mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top gives its covariance, L I L⊤=Σ\mathbf{L}\,\mathbf{I}\,\mathbf{L}^\top=\boldsymbol{\Sigma}. So x∼N(μ,Σ)\mathbf{x}\sim\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma}).

The standard choice of L\mathbf{L} is the Cholesky factor, a lower-triangular matrix (it exists when Σ\boldsymbol{\Sigma} is positive definite). In two variables,

L=(σx0ρ σyσy1−ρ2),\mathbf{L}=\begin{pmatrix}\sigma_x&0\\\rho\,\sigma_y&\sigma_y\sqrt{1-\rho^2}\end{pmatrix},

which means x=σxz1x=\sigma_xz_1 and y=ρσyz1+σy1−ρ2 z2y=\rho\sigma_yz_1+\sigma_y\sqrt{1-\rho^2}\,z_2: the yy value is a share ρ\rho of the first noise plus fresh noise. For (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}, L=(1.41400.7071.225)\mathbf{L}=\begin{pmatrix}1.414&0\\0.707&1.225\end{pmatrix}, and LL⊤=(2112)\mathbf{L}\mathbf{L}^\top=\begin{pmatrix}2&1\\1&2\end{pmatrix}. The factor is not unique: UΛ\mathbf{U}\sqrt{\boldsymbol{\Lambda}} from the eigen-decomposition also works, and it turns the picture into “stretch by λi\sqrt{\lambda_i} along each eigenvector”.

Running it backwards: whitening. The vector L−1(x−μ)\mathbf{L}^{-1}(\mathbf{x}-\boldsymbol{\mu}) has covariance I\mathbf{I}: the correlations and the unequal spreads are gone. This is called whitening. Since Σ−1=L−⊤L−1\boldsymbol{\Sigma}^{-1}=\mathbf{L}^{-\top}\mathbf{L}^{-1}, the Mahalanobis distance dd is the ordinary length of the whitened vector. Batch normalization (P4.19) standardizes each feature separately using batch statistics, which is not whitening; neither it nor the other normalization layers remove correlations between features.

Where this is used. A variational autoencoder (P8.3) draws a latent vector as z=μ+σ⊙ϵ\mathbf{z}=\boldsymbol{\mu}+\boldsymbol{\sigma}\odot\boldsymbol{\epsilon} with ϵ∼N(0,I)\boldsymbol{\epsilon}\sim\mathcal{N}(\mathbf{0},\mathbf{I}). This is the recipe above with a diagonal L\mathbf{L} (a common choice), and it is called the reparameterization trick: the randomness sits in ϵ\boldsymbol{\epsilon}, which does not depend on the parameters, so a gradient can flow through μ\boldsymbol{\mu} and σ\boldsymbol{\sigma}. Diffusion models (P8.7) also corrupt data with Gaussian noise drawn this way.

Two warnings about correlated features

Averages of correlated quantities. P1.D4 said that the average of nn independent draws, each with variance σ2\sigma^2, has variance σ2/n\sigma^2/n. If every pair of draws has correlation ρ\rho, the variance of the average is

σ2n(1+(n−1)ρ).\frac{\sigma^2}{n}\bigl(1+(n-1)\rho\bigr).

For n=10n=10 and ρ=0.5\rho=0.5 it is 0.55σ20.55\sigma^2, not 0.1σ20.1\sigma^2, and for large nn it approaches ρσ2\rho\sigma^2 rather than 00. Averaging many models, or many near-duplicate examples, helps less than independence would suggest.

Multicollinearity. Two features with correlation 0.990.99 (each standardized to variance 11) have the correlation matrix (10.990.991)\begin{pmatrix}1&0.99\\0.99&1\end{pmatrix} (for standardized features, X⊤X/(N−1)\mathbf{X}^\top\mathbf{X}/(N-1) is this matrix), with eigenvalues 1.991.99 and 0.010.01. Their ratio is 199199, the inverse has entries of about 5050, and a least-squares fit that must split credit between the two features can become unstable. Ridge regularization (P3.A6) adds a multiple of the identity to repair this, as in P1.B12.

Intuition

Covariance asks, for each example, whether both numbers are on the same side of their averages, and averages the answer. A positive covariance is a cloud leaning up, a negative one a cloud leaning down. Correlation is the same idea with the units divided out, so it can be compared between data sets.

A covariance matrix is the same story for every pair of features, and it is an ellipse: the long axis is the direction in which the data vary most, the short axis the direction in which they vary least. The Gaussian is the bell curve whose outline is that ellipse, and the Mahalanobis distance counts steps across it.

The picture breaks down when the cloud is not elliptical. A curve, two clumps or a ring can have exactly the same covariance matrix as a Gaussian cloud, and then the matrix describes only the straight-line part of the story.

Math

Cov(X,Y)=E[(X−μX)×(Y−μY)]=E[XY]−μXμYρ=Cov(X,Y)σXσY∈[−1,1]\begin{aligned} \mathrm{Cov}(X,Y)&=\mathbb{E}[(X-\mu_X)\\ &\qquad\times(Y-\mu_Y)]\\ &=\mathbb{E}[XY]-\mu_X\mu_Y\\ \rho&=\frac{\mathrm{Cov}(X,Y)}{\sigma_X\sigma_Y}\\ &\in[-1,1] \end{aligned}Σ=E[(x−μ)×(x−μ)⊤]Var(w⊤x)=w⊤ΣwCov(Ax)=AΣA⊤\begin{aligned} \boldsymbol{\Sigma}&=\mathbb{E}[(\mathbf{x}-\boldsymbol{\mu})\\ &\qquad\times(\mathbf{x}-\boldsymbol{\mu})^\top]\\ \mathrm{Var}(\mathbf{w}^\top\mathbf{x})&=\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}\\ \mathrm{Cov}(\mathbf{A}\mathbf{x})&=\mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top \end{aligned}p(x)=exp⁡(−12d2)(2π)ddet⁡Σd2=(x−μ)⊤Σ−1(x−μ)\begin{aligned} p(\mathbf{x})&=\frac{\exp(-\tfrac12d^2)}{\sqrt{(2\pi)^d\det\boldsymbol{\Sigma}}}\\ d^2&=(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}) \end{aligned}μy∣x=μy+ρσyσx(x−μx)σy∣x2=σy2(1−ρ2)x=μ+Lz, LL⊤=Σ\begin{aligned} \mu_{y\mid x}&=\mu_y+\rho\tfrac{\sigma_y}{\sigma_x}(x-\mu_x)\\ \sigma^2_{y\mid x}&=\sigma_y^2(1-\rho^2)\\ \mathbf{x}&=\boldsymbol{\mu}+\mathbf{L}\mathbf{z},\ \mathbf{L}\mathbf{L}^\top=\boldsymbol{\Sigma} \end{aligned}

Code

NumPy computes all of this. Remember that np.cov treats rows as variables, so pass rowvar=False for an N×dN\times d data matrix.

import numpy as np

X = np.random.default_rng(0).normal(size=(500, 3))   # 500 examples, 3 features
Sigma = np.cov(X, rowvar=False)                      # 3 x 3 sample covariance
R = np.corrcoef(X, rowvar=False)                     # 3 x 3 correlations
vals, vecs = np.linalg.eigh(Sigma)                   # variances and directions
L = np.linalg.cholesky(Sigma)                        # L @ L.T == Sigma
samples = np.random.default_rng(1).standard_normal((1000, 3)) @ L.T
# or: np.random.default_rng(1).multivariate_normal(np.zeros(3), Sigma, size=1000)

Try it: covariance and the multivariate Gaussian in code

The first cell repeats the five-student calculation with NumPy: the covariance by hand and with np.cov, the correlation, the cosine of the centred vectors, the zero correlation of Y=X2Y=X^2, the effect of one outlier, and the rowvar default. The second cell takes the four points of P1.B13: the covariance matrix, the variance in two directions, its eigenvalues, a Cholesky factor, a large sample and its covariance, the Mahalanobis distances of (1,1)(1,1) and (1,−1)(1,-1), and the conditional mean and variance at x=2x=2. Predict each output before you run it.

Try it: covariance and correlation of five students

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: the covariance matrix, sampling and conditioning

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Challenge: negate the second coordinate of every point in P in the second cell, so that Σ\boldsymbol{\Sigma} becomes (2−1−12)\begin{pmatrix}2&-1\\-1&2\end{pmatrix} and ρ=−0.5\rho=-0.5, and predict the signs of L\mathbf{L}, of the conditional mean at x=2x=2, and which direction now has variance 33.

Common mistakes

Check your understanding

  1. A covariance matrix is (4339)\begin{pmatrix}4&3\\3&9\end{pmatrix}. What is the correlation between the two variables?

  2. Which of these is NOT a valid covariance matrix?

  3. XX is symmetric around 00 and Y=X2Y=X^2. Which statement is correct?

  4. A Gaussian pair has μx=μy=0\mu_x=\mu_y=0, σx=σy=5\sigma_x=\sigma_y=5 and ρ=0.6\rho=0.6. Given x=10x=10, what are the mean and standard deviation of yy?

  5. About what fraction of the points of a two-variable Gaussian lies inside its 1σ1\sigma ellipse?

Exercises

  1. Compute the sample covariance (dividing by n−1n-1) and the correlation of x=(0,2,4)x=(0,2,4) and y=(1,5,6)y=(1,5,6).
    Show answerThe means are 22 and 44. The deviations are (−2,0,2)(-2,0,2) and (−3,1,2)(-3,1,2), with products 6,0,46,0,4, summing to 1010. So c^=102=5\hat c=\frac{10}{2}=5. The sample variances are 82=4\frac82=4 and 142=7\frac{14}{2}=7, so ρ=528≈0.945\rho=\frac{5}{\sqrt{28}}\approx0.945.
  2. Cov(X,Y)=1.5\mathrm{Cov}(X,Y)=1.5. Find Cov(2X+1, 3Y−4)\mathrm{Cov}(2X+1,\,3Y-4), and say whether the correlation changes.
    Show answer2⋅3⋅1.5=92\cdot3\cdot1.5=9 (the constants 11 and −4-4 do nothing). The correlation does not change, because both scale factors are positive.
  3. Var(X)=9\mathrm{Var}(X)=9, Var(Y)=16\mathrm{Var}(Y)=16 and Cov(X,Y)=−6\mathrm{Cov}(X,Y)=-6. Find ρ\rho, Var(X+Y)\mathrm{Var}(X+Y) and Var(X−Y)\mathrm{Var}(X-Y).
    Show answerρ=−63⋅4=−0.5\rho=\frac{-6}{3\cdot4}=-0.5. Var(X+Y)=9+16−12=13\mathrm{Var}(X+Y)=9+16-12=13 and Var(X−Y)=9+16+12=37\mathrm{Var}(X-Y)=9+16+12=37: a negative covariance makes sums steadier and differences wilder.
  4. For Σ=(5221)\boldsymbol{\Sigma}=\begin{pmatrix}5&2\\2&1\end{pmatrix} find the variance of x1−2x2x_1-2x_2.
    Show answerw=(1,−2)\mathbf{w}=(1,-2): w⊤Σw=5+4⋅1−2⋅2⋅2=1\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}=5+4\cdot1-2\cdot2\cdot2=1. Directly: Var(x1)+4Var(x2)−4Cov=5+4−8=1\mathrm{Var}(x_1)+4\mathrm{Var}(x_2)-4\mathrm{Cov}=5+4-8=1.
  5. Show that (1221)\begin{pmatrix}1&2\\2&1\end{pmatrix} is not a covariance matrix.
    Show answerWith w=(1,−1)\mathbf{w}=(1,-1), w⊤Σw=1+1−4=−2\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w}=1+1-4=-2, a negative variance. (The correlation would be 22, outside [−1,1][-1,1].)
  6. For Σ=(4001)\boldsymbol{\Sigma}=\begin{pmatrix}4&0\\0&1\end{pmatrix} and μ=0\boldsymbol{\mu}=\mathbf{0}, find the Mahalanobis distance of (2,0)(2,0) and of (0,2)(0,2).
    Show answerd2=x24+y2d^2=\frac{x^2}{4}+y^2. For (2,0)(2,0): d=1d=1. For (0,2)(0,2): d=2d=2. Both are 22 away in the ordinary sense, but (0,2)(0,2) is much more unusual because yy has a smaller spread.
  7. A Gaussian pair has means 00, σx=2\sigma_x=2, σy=1\sigma_y=1 and ρ=0.8\rho=0.8. Find the mean and standard deviation of yy given x=3x=3.
    Show answerThe mean is 0.8⋅12⋅3=1.20.8\cdot\frac12\cdot3=1.2 and the standard deviation is 1⋅1−0.64=0.61\cdot\sqrt{1-0.64}=0.6.
  8. Find the Cholesky factor for the pair in the previous exercise and check it.
    Show answerL=(200.80.6)\mathbf{L}=\begin{pmatrix}2&0\\0.8&0.6\end{pmatrix}. Then LL⊤=(41.61.60.64+0.36)=(41.61.61)\mathbf{L}\mathbf{L}^\top=\begin{pmatrix}4&1.6\\1.6&0.64+0.36\end{pmatrix}=\begin{pmatrix}4&1.6\\1.6&1\end{pmatrix}, and ρσxσy=0.8⋅2⋅1=1.6\rho\sigma_x\sigma_y=0.8\cdot2\cdot1=1.6.
  9. x\mathbf{x} has Σ=I\boldsymbol{\Sigma}=\mathbf{I} (two uncorrelated variables of variance 11). Find the covariance matrix and the correlation of y=(1011)x\mathbf{y}=\begin{pmatrix}1&0\\1&1\end{pmatrix}\mathbf{x}.
    Show answerAA⊤=(1112)\mathbf{A}\mathbf{A}^\top=\begin{pmatrix}1&1\\1&2\end{pmatrix} (here y1=x1y_1=x_1 and y2=x1+x2y_2=x_1+x_2). The correlation is 11⋅2≈0.707\frac{1}{\sqrt{1\cdot2}}\approx0.707.
  10. Find the eigenvalues and the 1σ1\sigma half-lengths of the sample covariance matrix (2.5222.5)\begin{pmatrix}2.5&2\\2&2.5\end{pmatrix} of the five students.
    Show answerThe eigenvalues are 2.5±22.5\pm2, that is 4.54.5 and 0.50.5, with eigenvectors along (1,1)(1,1) and (1,−1)(1,-1). The half-lengths are 4.5≈2.12\sqrt{4.5}\approx2.12 and 0.5≈0.71\sqrt{0.5}\approx0.71.
  11. n=4n=4 measurements each have variance 11, and every pair has correlation 0.50.5. Find the variance of their average.
    Show answer14(1+3⋅0.5)=0.625\frac14(1+3\cdot0.5)=0.625, compared with 0.250.25 for independent measurements.
  12. Code: a data matrix has shape (100,3)(100,3). What are the shapes of np.cov(X) and np.cov(X, rowvar=False)?
    Show answer(100,100)(100,100) and (3,3)(3,3). The default treats each of the 100100 rows as a variable, which is rarely what you want.
  13. X∼N(0,1)X\sim\mathcal{N}(0,1) and Y∼N(0,1)Y\sim\mathcal{N}(0,1) have Cov(X,Y)=0\mathrm{Cov}(X,Y)=0. Are they independent?
    Show answerNot necessarily. They are independent if (X,Y)(X,Y) is jointly Gaussian. The pair (X,SX)(X,SX) with S=±1S=\pm1 a fair coin has Gaussian marginals and zero covariance but ∣Y∣=∣X∣|Y|=|X|.

Next: P1.D8 shows why sums and averages of many independent quantities are nearly Gaussian, which is the reason this distribution is everywhere. P1.D10 uses the Gaussian density to define the likelihood and estimates μ\boldsymbol{\mu} and Σ\boldsymbol{\Sigma} from data, P1.D13 returns to correlation and cause, and P3.C3 builds PCA on the eigenvectors of the covariance matrix.

Key takeaways

  • The covariance Cov(X,Y)=E[(X−μX)(Y−μY)]=E[XY]−μXμY\mathrm{Cov}(X,Y)=\mathbb{E}[(X-\mu_X)(Y-\mu_Y)]=\mathbb{E}[XY]-\mu_X\mu_Y is positive when XX and YY tend to be above their means together, negative when one tends to be high while the other is low, and 00 when there is no straight-line tendency. Its unit is the unit of XX times the unit of YY. Cov(X,X)=Var(X)\mathrm{Cov}(X,X)=\mathrm{Var}(X), Cov(aX+b,Y)=a Cov(X,Y)\mathrm{Cov}(aX+b,Y)=a\,\mathrm{Cov}(X,Y), and Var(X+Y)=Var(X)+Var(Y)+2 Cov(X,Y)\mathrm{Var}(X+Y)=\mathrm{Var}(X)+\mathrm{Var}(Y)+2\,\mathrm{Cov}(X,Y). Independent variables have covariance 00; the converse is false.
  • The correlation ρ=Cov(X,Y)/(σXσY)\rho=\mathrm{Cov}(X,Y)/(\sigma_X\sigma_Y) removes the units and always lies in [−1,1][-1,1] (Cauchy–Schwarz). It equals ±1\pm1 exactly when YY is a straight-line function of XX. For data it is the cosine of the angle between the two centred data vectors (P1.B3). It measures only straight-line association: Y=X2Y=X^2 has ρ=0\rho=0, one far-away point can change its sign, and correlation alone says nothing about cause (P1.D13).
  • From nn data points, the sample covariance divides the sum of products of deviations by n−1n-1 (NumPy's np.cov does, and treats each row as a variable). For the five students of this lesson it is 22, with variances 2.52.5 and correlation 0.80.8.
  • The covariance matrix Σ=E[(x−μ)(x−μ)⊤]\boldsymbol{\Sigma}=\mathbb{E}[(\mathbf{x}-\boldsymbol{\mu})(\mathbf{x}-\boldsymbol{\mu})^\top] has the variances on its diagonal and Cov(xi,xj)\mathrm{Cov}(x_i,x_j) off it. It is symmetric and positive semi-definite, because the variance w⊤Σw\mathbf{w}^\top\boldsymbol{\Sigma}\mathbf{w} in any direction cannot be negative. For centred data, Σ≈X⊤X/(N−1)\boldsymbol{\Sigma}\approx\mathbf{X}^\top\mathbf{X}/(N-1), and Ax\mathbf{A}\mathbf{x} has covariance AΣA⊤\mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^\top. Rotating to the eigenvectors of Σ\boldsymbol{\Sigma} gives uncorrelated coordinates whose variances are the eigenvalues: that is PCA (P3.C3).
  • The multivariate Gaussian N(μ,Σ)\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma}) has density 1(2π)ddet⁡Σexp⁡(−12d2)\frac{1}{\sqrt{(2\pi)^d\det\boldsymbol{\Sigma}}}\exp(-\tfrac12 d^2) with the squared Mahalanobis distance d2=(x−μ)⊤Σ−1(x−μ)d^2=(\mathbf{x}-\boldsymbol{\mu})^\top\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}). Its level sets are ellipses (ellipsoids) with axes along the eigenvectors of Σ\boldsymbol{\Sigma} and half-lengths kλik\sqrt{\lambda_i}. In two variables the 1σ1\sigma ellipse holds about 39%39\% of the probability, not 68%68\%. If det⁡Σ=0\det\boldsymbol{\Sigma}=0 (for example ρ=±1\rho=\pm1) there is no density.
  • Marginals of a Gaussian are Gaussian (drop rows and columns of Σ\boldsymbol{\Sigma}). Conditionals are Gaussian too: in two variables y∣xy\mid x has mean μy+ρσyσx(x−μx)\mu_y+\rho\frac{\sigma_y}{\sigma_x}(x-\mu_x) (the regression line) and variance σy2(1−ρ2)\sigma_y^2(1-\rho^2), which does not depend on xx. For a jointly Gaussian pair, uncorrelated is the same as independent; for two Gaussians that are not jointly Gaussian it is not.
  • To sample from N(μ,Σ)\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma}), draw z\mathbf{z} with independent standard Gaussian entries and compute x=μ+Lz\mathbf{x}=\boldsymbol{\mu}+\mathbf{L}\mathbf{z}, where LL⊤=Σ\mathbf{L}\mathbf{L}^\top=\boldsymbol{\Sigma} (for example the Cholesky factor). Running this backwards, L−1(x−μ)\mathbf{L}^{-1}(\mathbf{x}-\boldsymbol{\mu}), whitens the data. The reparameterization trick of variational autoencoders (P8.3) is this idea.
Found a mistake? Tell us