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 hours and scored points on a short quiz (invented numbers). Both averages are . For each student, measure how far each number is from its average, and multiply the two deviations:
| hours | score | product | ||
|---|---|---|---|---|
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 . Treating the five students as equally likely (each has probability ), their average is the covariance:
Compare with the variance (P1.D4), the average of . The variance multiplies a deviation by itself; the covariance multiplies the deviation of one variable by the deviation of another. So .
Reading the sign. Draw a cross at the point . 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 : there is no straight-line tendency.
A shortcut. Expanding the product and using linearity of expectation (P1.D4) gives
just as . For the students, and , so again.
Units. The unit of a covariance is the unit of times the unit of (hours times points here). Measure the hours in minutes and every and every deviation becomes times as large, so the covariance becomes 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. .
- Shifts do nothing, scaling scales. . Adding a constant moves the mean by the same amount, so the deviations do not change.
- Splits over sums. . Together with the rule above, covariance is bilinear: linear in each argument.
- The cross term of a sum. , the term P1.D4 left open. For the students, and , so the variance of is . For one fair die and , , and the sum is always : .
- Independent implies zero covariance. If and are independent then , so (P1.D5). The converse is false: for uniform on and , the covariance is but is a function of .
Correlation: covariance without units
Divide the covariance by the two standard deviations. The result is the correlation coefficient
(defined when both standard deviations are positive). For the students, , so . The units cancel, so minutes instead of hours give the same . Replacing by with changes nothing; with it flips the sign of (reversing the hours gives ).
Three facts about :
- It always lies between and . This follows from the Cauchy–Schwarz inequality (the box below).
- It equals or exactly when is an exact straight-line function of , with for and for (and ).
- It is a cosine. Write the centred data as two vectors, and . Their dot product is and each has length , so the cosine of the angle between them is , an angle of about . 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 .
Go deeper Why correlation never leaves the range from −1 to 1
For any number , a variance is never negative, so
Take . The right side becomes , which gives , that is . This is the Cauchy–Schwarz inequality for random variables. Equality needs , which means is a constant: is an exact straight-line function of .
The same calculation is useful on its own: is the smallest mean squared error that any straight-line prediction of can reach (the best line is ). For the students, of the variance of is accounted for by the best line, and is left over.
What correlation cannot see
Correlation measures only straight-line association.
- For uniform on and (the table of P1.D5), , although is completely determined by . 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 () and the same best line (), 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 hours and scored to the five above and drops from to .
- 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 pairs is
with the same “divide by ” as the sample variance in P1.D4. For the five students the sum is , so ; the sample variances are each; and is once more. The factor cancels in the correlation, so the choice of or does not matter for . Dividing by instead gives the maximum-likelihood estimate for a Gaussian (P1.D10); both agree for large .
In NumPy, np.cov(x, y) returns the whole matrix, here , 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 matrix instead of a one.
The covariance matrix
A random vector has variances and different covariances. Collect them in one matrix with entries . In one line:
The product of a column with a row is a matrix whose entry is the deviation of times the deviation of ; is its average. Three properties:
- The diagonal holds the variances, . Their sum, the trace, is the total variance.
- is symmetric, because (P1.B10).
- is positive semi-definite: for every vector . The next subsection explains why.
From data. Put the data in an matrix with one example per row, and subtract each column’s mean to centre it. Then the sample covariance matrix is (or ). For the four points , , , of P1.B13, which have mean , , so
the matrix of P1.B12. Its variances are and , its correlation is , its trace is and its determinant is . We reuse it below.
Variance in any direction
Take a fixed vector and look at the single number for each example: the amount of along (for a unit vector, its coordinate in that direction). Its variance is
For :
- gives , the variance of .
- gives . This is , the sum rule above, now as a special case of a general rule.
- gives . The difference of two positively correlated variables varies less than their sum.
- The unit directions and give and : 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, for every , which is the definition of positive semi-definite. This is also a test: is symmetric but cannot be a covariance matrix, because gives . If for some non-zero , the data have no spread in that direction: they lie on a line (or a plane, and so on) and is singular.
Go deeper Why the variance in a direction is wᵀΣw, and what a linear map does to Σ
The number has mean , so
The same steps for a matrix give a rule for a whole linear transform: has mean and covariance matrix
If is a single row , this is the formula above. Example: take , whose rows are the two eigenvectors of . Then . The new coordinates are uncorrelated, with variances and . 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 with : the number of standard deviations from the mean. To go to several variables, keep the same shape and replace by a squared distance that accounts for the spreads and the correlations. It is the squared Mahalanobis distance
For one variable, and . The density of , for a -dimensional and a with , is
The factor in front makes the total probability . It uses the determinant (P1.B8): a wider spread means a larger , so the same probability is spread over more volume and the peak is lower. For , and the peak height in two variables is . For , and the peak is . The inverse is found as in P1.B9; here it is . In code, is computed by solving (np.linalg.solve), not by forming the inverse.
What measures. Take and . The points and are equally far from the mean in the ordinary sense, . But for and for : 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 for the first and 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 . A level set is an ellipse. To see why, use P1.B12: a symmetric can be written , with orthonormal eigenvectors as the columns of and eigenvalues on the diagonal of . Then , and
In coordinates measured along the eigenvectors, is a sum of squares, each divided by the variance in that direction. The set where the sum equals is an ellipse centred at , with its axes along the eigenvectors and half-lengths .
For , the eigenvalues are and with eigenvectors and . The ellipse () has half-length along and along ; the ellipse () has and . Check: the tip has . 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 ellipse does not hold of the points. In two variables it holds , the ellipse holds and the ellipse (the box below explains). The familiar –– rule of P1.D3 is for one variable.
Go deeper Why the 1σ ellipse holds only about 39%
Whiten the variable: (the sampling section below shows how) has independent standard Gaussian entries, and is the squared distance from the origin in the plane. The density of depends only on that distance , and the probability of a ring between and is . Integrating from to gives . A simulation of two million points from the example above agrees: , , inside the , and ellipses. In more variables the fraction inside the ellipsoid is smaller still, so most of the probability is farther out than .
Two variables: , and
In two variables, write
The matrix is positive definite (so the density exists) exactly when . With and , the density is
Three cases to keep in mind:
- , : is a multiple of the identity and the outline is a circle. Every direction is an eigenvector.
- , : the outline is an ellipse with axes along the and axes.
- : the ellipse is tilted. Positive tilts it up to the right, negative down to the right, and larger makes it thinner.
When , : the matrix is singular, does not exist, and the formula above divides by . All the probability lies on one straight line, so there is no density in the plane (the ellipse has collapsed to a segment). When is close to , the entries of are huge and the numbers become unstable, and a common remedy is to add a tiny multiple of the identity to .
Drag the ellipse
The widget draws points from a Gaussian with mean , together with the ellipse (solid) and the 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 , the sample matrix of the drawn points, the eigenvalues and the eigenvectors update as you go.
Try these:
- Press Example (ρ = 0.5). The matrix is , the eigenvalues are and , and (the two eigenvectors may be shown with a different sign). The long half-length is , and the sample matrix (labelled “sample Σ”) is close to but not equal to it.
- Drag the long-axis circle around the origin. When the long axis lies on the axis (and ), . When it passes through the second and fourth quadrants, is negative.
- Slide to . The ellipse collapses to a segment, the determinant is , and the status says the density is undefined. Move back to and watch the short half-length and the determinant.
- Choose Ring or Uniform square. The ellipses and do not change and stays close to , although the cloud looks nothing like a Gaussian. The covariance matrix does not determine the shape.
- Tick Condition on x with the example matrix and set . The pink line is , so the conditional mean is , and the conditional standard deviation is , smaller than the 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 , any subset of its entries is Gaussian, with the matching entries of and the matching rows and columns of . In two variables, and , whatever is. This is P1.D5’s warning again: the marginals do not contain , so they cannot tell a thin tilted ellipse from a circle.
Conditionals: slice, then read off. Fix and look at the vertical slice of the cloud. Given , is Gaussian with
Two things to notice:
- The conditional mean is a straight line in , the regression line, with slope . This is the conditional expectation 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 the long axis has slope and the regression line has slope .
- The conditional variance is the same for every , and it is smaller than whenever . Knowing removes the fraction of the variance of . With , : the slope is , the conditional variance is , and at the conditional distribution is . A simulation of points with near gives a mean near and a variance near .
Regression to the mean. With , a value of that is two standard deviations above its mean predicts a only standard deviation above its mean. The prediction is pulled back toward the mean unless .
The two regression lines differ. Predicting from has slope in the coordinates. The product of the two slopes is , which is only for a perfect straight line. So the line for from and the line for from are different lines whenever .
Uncorrelated and independent. If , is diagonal, , 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 example), and two variables that are each Gaussian need not be jointly Gaussian.
Go deeper Two Gaussians that are uncorrelated but not independent
Let , and let be a fair coin giving or , independent of . Define . Then is also , because flipping the sign of a symmetric variable at random does not change its distribution. The covariance is . But always, so the two are as dependent as can be (knowing leaves only two possible values of ). The pair is not a bivariate Gaussian: equals with probability , 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 into two blocks and , with and split to match: blocks , , , . Given , the vector is Gaussian with
It is the formula for predicting some coordinates from the others. In two variables with and , gives the slope above, and gives the variance. For : .
Sampling:
How does the widget draw its points? Start from , a vector of independent standard Gaussians (mean , variance each), so . Find a matrix with , and set
A linear map of a Gaussian vector is Gaussian, and the rule gives its covariance, . So .
The standard choice of is the Cholesky factor, a lower-triangular matrix (it exists when is positive definite). In two variables,
which means and : the value is a share of the first noise plus fresh noise. For , , and . The factor is not unique: from the eigen-decomposition also works, and it turns the picture into “stretch by along each eigenvector”.
Running it backwards: whitening. The vector has covariance : the correlations and the unequal spreads are gone. This is called whitening. Since , the Mahalanobis distance 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 with . This is the recipe above with a diagonal (a common choice), and it is called the reparameterization trick: the randomness sits in , which does not depend on the parameters, so a gradient can flow through and . 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 independent draws, each with variance , has variance . If every pair of draws has correlation , the variance of the average is
For and it is , not , and for large it approaches rather than . Averaging many models, or many near-duplicate examples, helps less than independence would suggest.
Multicollinearity. Two features with correlation (each standardized to variance ) have the correlation matrix (for standardized features, is this matrix), with eigenvalues and . Their ratio is , the inverse has entries of about , 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
Code
NumPy computes all of this. Remember that np.cov treats rows as variables, so pass rowvar=False for an 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 , 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 and , and the conditional mean and variance at . Predict each output before you run it.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
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 becomes and , and predict the signs of , of the conditional mean at , and which direction now has variance .
Common mistakes
Check your understanding
A covariance matrix is . What is the correlation between the two variables?
The correlation divides the covariance by the two standard deviations: . The value is the covariance itself, which still carries units. The value divides by the variance only, and divides by the variance only. Neither takes both square roots.
Which of these is NOT a valid covariance matrix?
A covariance cannot exceed the product of the two standard deviations in size, here , and is larger. Equivalently its determinant is negative, so some direction would have a negative variance. The matrix with has determinant : it is a valid covariance matrix of data on a line (). The diagonal matrix has no correlation, and the matrix with has ; both are valid.
is symmetric around and . Which statement is correct?
For symmetric the products of deviations cancel: and , so the covariance is (when the moments exist). Zero covariance does not imply independence. A correlation of needs a straight-line function, and is a curve. The sign of alone does not decide the sign of the covariance, which compares deviations from the means.
A Gaussian pair has , and . Given , what are the mean and standard deviation of ?
The mean is and the standard deviation is . Keeping forgets that knowing narrows the spread. A mean of forgets the pull toward the mean (). The value multiplies by instead of .
About what fraction of the points of a two-variable Gaussian lies inside its ellipse?
In two variables the fraction inside the ellipse is , which is for . The value is the one-variable rule for ; it does not carry over to a plane. The value is the one-variable rule for ; in two variables the ellipse holds . The value would be the fraction inside a smaller ellipse, with .
Exercises
- Compute the sample covariance (dividing by ) and the correlation of and .
Show answer
The means are and . The deviations are and , with products , summing to . So . The sample variances are and , so . - . Find , and say whether the correlation changes.
Show answer
(the constants and do nothing). The correlation does not change, because both scale factors are positive. - , and . Find , and .
Show answer
. and : a negative covariance makes sums steadier and differences wilder. - For find the variance of .
Show answer
: . Directly: . - Show that is not a covariance matrix.
Show answer
With , , a negative variance. (The correlation would be , outside .) - For and , find the Mahalanobis distance of and of .
Show answer
. For : . For : . Both are away in the ordinary sense, but is much more unusual because has a smaller spread. - A Gaussian pair has means , , and . Find the mean and standard deviation of given .
Show answer
The mean is and the standard deviation is . - Find the Cholesky factor for the pair in the previous exercise and check it.
Show answer
. Then , and . - has (two uncorrelated variables of variance ). Find the covariance matrix and the correlation of .
Show answer
(here and ). The correlation is . - Find the eigenvalues and the half-lengths of the sample covariance matrix of the five students.
Show answer
The eigenvalues are , that is and , with eigenvectors along and . The half-lengths are and . - measurements each have variance , and every pair has correlation . Find the variance of their average.
Show answer
, compared with for independent measurements. - Code: a data matrix has shape . What are the shapes of
np.cov(X)andnp.cov(X, rowvar=False)?Show answer
and . The default treats each of the rows as a variable, which is rarely what you want. - and have . Are they independent?
Show answer
Not necessarily. They are independent if is jointly Gaussian. The pair with a fair coin has Gaussian marginals and zero covariance but .
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 and from data, P1.D13 returns to correlation and cause, and P3.C3 builds PCA on the eigenvectors of the covariance matrix.