AI Wiki中文/EN

Covariance and correlation

协方差与相关性

Distinguish paired linear association from independence and causality, derive sample corrections, and compute exact covariance.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Do two errors move together?

Two models make predictions for the same cases. Knowing each model’s error variance does not tell you how much averaging their predictions will help: their errors might cancel, or both might miss the same cases. Covariance records whether their deviations from their own means tend to have the same sign. The pairing matters; shuffling one model’s errors changes the question.

Use three equally weighted, invented pairs (0,0),(1,2),(2,1)(0,0),(1,2),(2,1). Both coordinate means are 1. The products of the centered coordinates are 1, 0, and 0, so the covariance is 1/31/3. Both variances are 2/32/3, giving correlation 1/21/2. Multiplying the first coordinate by 100 multiplies covariance by 100 but leaves correlation unchanged. Covariance carries units; correlation removes their positive scale.

Center, multiply, then average

For real random variables with finite second moments, the population covariance and Pearson correlation are:

Cov⁡(X,Y)=E[(X−μX)(Y−μY)]=E[XY]−μXμY,ρ=Cov⁡(X,Y)σXσY.\operatorname{Cov}(X,Y)=E[(X-\mu_X)(Y-\mu_Y)]=E[XY]-\mu_X\mu_Y,\qquad \rho=\frac{\operatorname{Cov}(X,Y)}{\sigma_X\sigma_Y}.

Here μX=E[X]\mu_X=E[X] and σX2=Var⁡(X)\sigma_X^2=\operatorname{Var}(X), with corresponding definitions for YY. Correlation additionally requires both variances to be positive. A constant variable has covariance zero with every variable meeting these moment assumptions, but its correlation is undefined. These are properties of a distribution, not estimates computed from a finite sample. MIT, Lecture 12, slides 6–10

The second covariance expression follows by expanding the product and using linearity of expectation. Cauchy–Schwarz applied to the centered variables bounds its absolute value by σXσY\sigma_X\sigma_Y. Consequently −1≤ρ≤1-1\le\rho\le1. Equality means one centered variable is a nonzero constant multiple of the other almost surely; “almost surely” permits a probability-zero exception. Correlation 1 therefore expresses an increasing affine relation, not necessarily equality of the original values.

For constants a,b,c,da,b,c,d, centering cancels shifts and pulls out scales:

Cov⁡(aX+b,cY+d)=acCov⁡(X,Y),Var⁡(X+Y)=σX2+σY2+2Cov⁡(X,Y).\operatorname{Cov}(aX+b,cY+d)=ac\operatorname{Cov}(X,Y),\qquad \operatorname{Var}(X+Y)=\sigma_X^2+\sigma_Y^2+2\operatorname{Cov}(X,Y).

If the transformed variances remain positive, their correlation is sign⁡(ac)ρ\operatorname{sign}(ac)\rho. Multiplying a coordinate by a negative number reverses its direction. For two unbiased errors with common variance vv and correlation ρ\rho, the variance of their average is v(1+ρ)/2v(1+\rho)/2. At correlation 1 it stays vv; at zero it becomes v/2v/2. This calculation explains why model diversity concerns error dependence, not just different model names.

For a random column vector ZZ with finite second moments, let μ=E[Z]\mu=E[Z]. Its covariance matrix is:

Σ=E[(Z−μ)(Z−μ)⊤],u⊤Σu=Var⁡(u⊤Z)≥0.\Sigma=E[(Z-\mu)(Z-\mu)^\top],\qquad u^\top\Sigma u=\operatorname{Var}(u^\top Z)\ge0.

The final equality proves positive semidefiniteness for every fixed vector uu; symmetry follows by transposing each outer product. Positive definiteness is stronger and need not hold. With Z=(X,2X)⊤Z=(X,2X)^\top and Var⁡(X)=1\operatorname{Var}(X)=1, the covariance is (1224)\begin{pmatrix}1&2\\2&4\end{pmatrix}. Direction (−2,1)⊤(-2,1)^\top has zero variance, making the matrix singular. A deterministic affine transformation produces covariance AΣA⊤A\Sigma A^\top. MML, Sections 6.4.1 and 6.4.4

Keep the arithmetic exact on a small example

The complete Python program accepts integer or Fraction values. joint_summary describes a finite probability distribution; sample_summary treats observed pairs as an empirical distribution and optionally changes the covariance and variance denominators. Returned means, variances, and covariance are exact fractions. Only correlation uses an approximate square root; None explicitly denotes an undefined correlation.

from fractions import Fraction as F
import math

def rational(x):
    if type(x) is not int and not isinstance(x, F):
        raise ValueError("use integers or Fraction values")
    return F(x)

def joint_summary(points):
    points = [tuple(rational(v) for v in row) for row in points]
    if not points or any(len(row) != 3 for row in points):
        raise ValueError("nonempty (x, y, probability) rows required")
    if any(p < 0 for x, y, p in points) or sum(p for x, y, p in points) != 1:
        raise ValueError("nonnegative probabilities must sum to one")
    mx = sum(x*p for x, y, p in points)
    my = sum(y*p for x, y, p in points)
    vx = sum(p*(x-mx)**2 for x, y, p in points)
    vy = sum(p*(y-my)**2 for x, y, p in points)
    cov = sum(p*(x-mx)*(y-my) for x, y, p in points)
    # Form a bounded exact ratio before the only float conversion.
    r = None if vx == 0 or vy == 0 else math.sqrt(float(cov*cov/(vx*vy)))
    if r is not None and cov < 0:
        r = -r
    return {"mean": (mx,my), "variance": (vx,vy), "covariance": cov, "r": r}

def sample_summary(rows, ddof=0):
    if type(ddof) is not int or ddof not in (0,1):
        raise ValueError("ddof must be 0 or 1")
    rows = [tuple(row) for row in rows]
    n = len(rows)
    if n <= ddof or any(len(row) != 2 for row in rows):
        raise ValueError("paired observations and n > ddof required")
    result = joint_summary([(x,y,F(1,n)) for x,y in rows])
    correction = F(n,n-ddof)
    result["covariance"] *= correction
    result["variance"] = tuple(v*correction for v in result["variance"])
    return result

rows = [(0,0),(1,2),(2,1)]
a = sample_summary(rows)
b = sample_summary(rows, ddof=1)
assert a["mean"] == (1,1)
assert a["covariance"] == F(1,3) and a["r"] == .5
assert b["covariance"] == F(1,2) and b["r"] == .5
assert sample_summary([(100*x,y) for x,y in rows])["covariance"] == F(100,3)
assert joint_summary([(-1,1,F(1,3)),(0,0,F(1,3)),(1,1,F(1,3))])["r"] == 0
assert sample_summary([(0,1),(0,3)])["r"] is None

There are O(n)O(n) rational arithmetic operations and O(n)O(n) additional storage because the program copies its inputs. Fraction bit costs grow with the numerators and denominators. The bounded ratio avoids overflowing a float conversion of a large covariance, but extremely tiny correlations can still round to zero. For large floating-point datasets, use a tested centered or online covariance implementation; subtracting nearly equal raw second moments can lose precision. The sample API does not accept missing values or silently discard unpaired rows.

A correlation is not a dependence model

Let XX be uniform on {−1,0,1}\{-1,0,1\} and set Y=X2Y=X^2. Then E[X]=E[XY]=0E[X]=E[XY]=0, so covariance and correlation are zero. Yet observing Y=0Y=0 determines X=0X=0. Thus uncorrelated does not imply independent. Conversely, independence and finite second moments do imply zero covariance. MML, Section 6.4.5

Even positive correlation does not imply that the conditional mean grows at every step. Give (X,Y)(X,Y) equal probabilities on (0,0),(1,3),(2,2)(0,0),(1,3),(2,2). Covariance is 2/3>02/3>0, while E[Y∣X=1]=3E[Y\mid X=1]=3 exceeds E[Y∣X=2]=2E[Y\mid X=2]=2. Pearson correlation summarizes linear association across the distribution; it is not a monotonicity theorem.

Nor does it determine a causal direction. Take independent, zero-mean variables Z,U,VZ,U,V of variance 1 and define X=Z+UX=Z+U, Y=Z+VY=Z+V. Their covariance is 1 and correlation is 1/21/2, caused in this model by the shared input ZZ. The equations contain no arrow from XX to YY. MIT, Lecture 12, slide 12

For observed pairs, denominator nn describes their empirical distribution. Under i.i.d. sampling of pairs with finite second moments and n≥2n\ge2, denominator n−1n-1 gives an unbiased population covariance estimator. To see the correction, expand around the population means:

∑i=1n(Xi−Xˉ)(Yi−Yˉ)=∑i=1n(Xi−μX)(Yi−μY)−n(Xˉ−μX)(Yˉ−μY).\sum_{i=1}^n(X_i-\bar X)(Y_i-\bar Y)=\sum_{i=1}^n(X_i-\mu_X)(Y_i-\mu_Y)-n(\bar X-\mu_X)(\bar Y-\mu_Y).

The expected terms on the right are nCov⁡(X,Y)n\operatorname{Cov}(X,Y) and Cov⁡(X,Y)\operatorname{Cov}(X,Y), respectively. Their difference explains n−1n-1. Independence is across sampled pairs, not between XiX_i and YiY_i within a pair. The correction does not make sample correlation unbiased, and common denominator factors cancel from the correlation ratio. MML, Section 6.4.2

Outliers, selection, and mixing distinct groups can change the statistic sharply. Inspect paired plots and the sampling process before interpreting a coefficient. Rank correlations address a different question about ordered association; they still do not establish causality. In high dimension, the rows of a centered sample matrix sum to zero and therefore are linearly dependent. With nn rows its rank is at most n−1n-1, so its covariance is necessarily singular when the number of features exceeds that bound.

Try to break the interpretation

  1. For the three opening pairs, what changes with denominator n−1n-1? Answer: covariance becomes 1/21/2 and both variances become 1. Correlation stays 1/21/2.
  2. Replace XX with −2X+7-2X+7 in that example. What are covariance and correlation? Answer: −2/3-2/3 and −1/2-1/2 with denominator nn; the shift cancels and the negative scale reverses direction.
  3. If Y=X2Y=X^2 for the uniform three-point XX, compute P(X=0∣Y=0)P(X=0\mid Y=0) and P(X=0)P(X=0). Answer: 1 and 1/31/3. Their inequality proves dependence despite zero correlation.
  4. Can four observations of six features produce an invertible centered sample covariance? Answer: no. Its rank is at most 3, whether the denominator is 4 or 3. Changing the denominator cannot restore missing directions.

Follow the matrix into other methods

Covariance gives PCA a precise objective: for a unit direction uu, projected variance is u⊤Σuu^\top\Sigma u. Maximizing it leads to a leading eigenvector of the symmetric covariance matrix. That direction depends on measurement units, so standardizing features changes the optimization problem. It also explains why covariance regularization can be useful when empirical estimates are noisy or singular: adding a positive multiple of the identity changes the estimate to make every direction have positive variance. Choosing that amount requires validation, not an assumption that invertibility guarantees accuracy.

A useful next experiment is to add a single extreme pair to the three-point dataset and recompute the summaries. Then inspect whether the new coefficient describes most pairs or mostly the added point. The number is easy to calculate; deciding which distribution it represents is the harder task.

Make a prediction, then check

X is uniform on −1, 0, 1 and Y=X², with zero correlation. What follows?

Choose one answer

Learning objectives

  • Derive covariance and correlation from centered products and state finite-second-moment and positive-variance conditions.
  • Explain covariance-matrix semidefiniteness, singularity, and the sampling assumptions behind the n−1 correction.
  • Use explicit counterexamples to separate linear association, conditional-mean monotonicity, independence, and causality.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. Introduction to Probability — Lecture 12: Sums of Independent Random Variables; Covariance and Correlation
    John Tsitsiklis; Patrick Jaillet; MIT OpenCourseWare · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Compared inspected MIT and MML sections, preserving finite second moments, positive variances, almost-sure affine equality and i.i.d. sampling across pairs.
  • Re-derived the n−1 correction and PSD quadratic form; checked random finite distributions by an independent exact pair-difference identity and exhaustively verified unbiasedness at sample sizes 2, 3 and 4.
  • Executed nonlinear-dependence, nonmonotone-conditional-mean, common-cause, zero-variance and invalid-input checks; compared bilingual arguments, equations, code and four answers.
  • A second Codex agent performed read-only review of finite second moments, positive variances, sample-unbiasedness conditions, the nonmonotone positive-correlation counterexample, and bilingual consistency.
  • The parent executed all 25 independent probability checks; bilingual code, display equations, main anchors, sources and exercises were additionally compared.
  • Static rendering found unprocessed answer emphasis adjacent to Chinese text; explicit strong tags now preserve all answer text, values and formulas.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.