Covariance and correlation
协方差与相关性
Distinguish paired linear association from independence and causality, derive sample corrections, and compute exact covariance.
covariance-correlationDo 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 . Both coordinate means are 1. The products of the centered coordinates are 1, 0, and 0, so the covariance is . Both variances are , giving correlation . 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:
Here and , with corresponding definitions for . 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 . Consequently . 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 , centering cancels shifts and pulls out scales:
If the transformed variances remain positive, their correlation is . Multiplying a coordinate by a negative number reverses its direction. For two unbiased errors with common variance and correlation , the variance of their average is . At correlation 1 it stays ; at zero it becomes . This calculation explains why model diversity concerns error dependence, not just different model names.
For a random column vector with finite second moments, let . Its covariance matrix is:
The final equality proves positive semidefiniteness for every fixed vector ; symmetry follows by transposing each outer product. Positive definiteness is stronger and need not hold. With and , the covariance is . Direction has zero variance, making the matrix singular. A deterministic affine transformation produces covariance . 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 rational arithmetic operations and 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 be uniform on and set . Then , so covariance and correlation are zero. Yet observing determines . 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 equal probabilities on . Covariance is , while exceeds . 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 of variance 1 and define , . Their covariance is 1 and correlation is , caused in this model by the shared input . The equations contain no arrow from to . MIT, Lecture 12, slide 12
For observed pairs, denominator describes their empirical distribution. Under i.i.d. sampling of pairs with finite second moments and , denominator gives an unbiased population covariance estimator. To see the correction, expand around the population means:
The expected terms on the right are and , respectively. Their difference explains . Independence is across sampled pairs, not between and 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 rows its rank is at most , so its covariance is necessarily singular when the number of features exceeds that bound.
Try to break the interpretation
- For the three opening pairs, what changes with denominator ? Answer: covariance becomes and both variances become 1. Correlation stays .
- Replace with in that example. What are covariance and correlation? Answer: and with denominator ; the shift cancels and the negative scale reverses direction.
- If for the uniform three-point , compute and . Answer: 1 and . Their inequality proves dependence despite zero correlation.
- 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 , projected variance is . 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?
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
- Expectation and variance
- Independence and conditional independence
- Inner products and angles
- Matrix multiplication
References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - 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:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, sections 6.4.1–6.4.5, printed pp. 190–195 / PDF pp. 196–201: population covariance, correlation normalization, empirical denominator n versus corrected n−1, symmetric PSD covariance, affine propagation and non-independence counterexample. Read local author PDF. The article does not repeat the book’s overbroad positive-correlation ⇒ increasing-conditional-mean wording or its simplifying positive-definite restriction.
- Introduction to Probability — Lecture 12: Sums of Independent Random Variables; Covariance and Correlation · Lecture 12, PDF slides 6–12: covariance definition and bilinearity, variance of sums, correlation bounds and equality, common-input example and correlation versus causation; author credit on PDF slide 14.
Related topics