Module contents
Lesson 8 of 24Review 85 min

Moments: variance, covariance and correlation

A geometric review: covariance is an inner product in L² and correlation a cosine. Study covariance matrices and linear transformations, variance of sums with correlation and why averaging correlated data helps less than expected, and Markov and Chebyshev tail bounds. Implement numerically stable streaming moments.

After this lesson you can

  • Calculate variances, covariances and covariance matrices, including under linear transformations AΣAᵀ.
  • Interpret covariance and correlation as an inner product and cosine in L².
  • Calculate variance of averages of correlated variables and effective sample size.
  • Distinguish uncorrelatedness from independence using counterexamples.
  • Prove and apply Markov's and Chebyshev's inequalities.

Before you start

Motivation: noise in a stochastic gradient

You train a network with stochastic gradient descent. At each step you calculate the average per-example gradient for a batch of BB examples, g^=1B∑i=1Bgi\hat{\vb{g}} = \frac{1}{B}\sum_{i=1}^B \vb{g}_i and take a step with it. This average is random: if examples are selected well, its expectation is the true gradient, but each batch deviates from it. A covariance matrix measures how much, determining the step size you can afford, the number of steps needed, and how much doubling the batch helps.

The introductory answer is that if gi\vb{g}_i are independent with covariance Σ\mat{\Sigma}, their average has covariance Σ/B\mat{\Sigma}/B: doubling the batch halves the noise. True, but no longer true as soon as examples resemble one another. With B=100B = 100 variables of variance 11 and pairwise correlation only 0.10.1 (for example, augmented copies of the same images or overlapping windows of the same text), variance of the average is not 1/100=0.011/100 = 0.01 but 0.1090.109: eleven times larger. And however much BB grows, it never falls below 0.10.1.

This lesson collects the tools to reason about such effects, all based on second-order moments:

  1. Variance and moments. What variance measures (distance to the best constant predictor), what skewness and kurtosis add, and when a moment ceases to exist.
  2. Covariance and correlation as geometry. In L2L^2, covariance is an inner product and correlation a cosine. Everything that follows is geometry of angles and lengths.
  3. The covariance matrix as a quadratic form: its behavior under linear maps and variance in each direction.
  4. Variance of sums and averages, its correlation floor, and effective sample size.
  5. Uncorrelatedness versus independence, and what Pearson correlation misses.
  6. Markov and Chebyshev, the first tail bounds and why they cannot be improved without more assumptions.
  7. Stable computation of moments in one pass (Welford), because the classroom formula fails in floating point.

Variance and moments

Work on a probability space (Ω,F,P)(\Omega, \mathcal{F}, \Pr). Variance requires more than integrability: the variable must lie in L2L^2, meaning E[X2]<∞\E[X^2] < \infty (spaces LpL^p and their structure appear in the lesson on the integral and LpL^p spaces). Every X∈L2X \in L^2 lies in L1L^1 because E∣X∣≤E[X2]\E\abs{X} \le \sqrt{\E[X^2]} by Cauchy–Schwarz, so μ=E[X]\mu = \E[X] makes sense.

Proof

(1) Expand (X−μ)2=X2−2μX+μ2(X - \mu)^2 = X^2 - 2\mu X + \mu^2 and take expectations, using linearity: Var⁡(X)=E[X2]−2μ2+μ2\Var(X) = \E[X^2] - 2\mu^2 + \mu^2. Variance is the expectation of a nonnegative variable and thus nonnegative; a nonnegative variable has zero expectation only if zero almost surely: (X−μ)2=0(X - \mu)^2 = 0 almost surely. (2) aX+b−E[aX+b]=a(X−μ)aX + b - \E[aX + b] = a(X - \mu); square and take expectations. (3) Add and subtract μ\mu: (X−c)2=(X−μ)2+2(X−μ)(μ−c)+(μ−c)2(X - c)^2 = (X - \mu)^2 + 2(X - \mu)(\mu - c) + (\mu - c)^2. The cross term has expectation 2(μ−c) E[X−μ]=02(\mu - c)\,\E[X - \mu] = 0.

∎

Part (3) gives variance its operational meaning. If you must summarize XX by one number cc and are penalized by squared error, expected error is Var⁡(X)+(μ−c)2\Var(X) + (\mu - c)^2: the best choice is c=μc = \mu and unavoidable error is exactly Var⁡(X)\Var(X). This is why regression’s coefficient of determination is R2=1−ECM/Var⁡(Y)R^2 = 1 - \text{ECM}/\Var(Y): it compares your model with the best constant predictor. In the conditional expectation lesson you will see that if a function of another variable is allowed instead of a number, the best predictor is E[Y∣X]\E[Y \given X], by the same projection argument.

Skewness and kurtosis

Third and fourth central moments, normalized to be scale-independent, describe the shape of a law.

As a guideline (not infallible: some asymmetric laws have γ1=0\gamma_1 = 0), skewness is positive when the long tail is on the right and negative when it is on the left, and is 00 for every symmetric law with finite third moment. Kurtosis is the expectation of Z4Z^4 with standardized Z=(X−μ)/σZ = (X - \mu)/\sigma. Since Z4Z^4 grows rapidly, a single distant value contributes greatly, making kurtosis primarily a measure of tail weight, not the peak of the bell.

LawVarianceSkewness γ1\gamma_1Kurtosis κ\kappa
N(0,1)\Normal(0, 1)110033
Uniform on [0,1][0, 1]1/121/12001.81.8
Laplace (double exponential) with scale bb2b22b^20066
Exponential with rate λ\lambda1/λ21/\lambda^22299
Student tt, 55 degrees of freedom5/35/30099
Student tt, 33 degrees of freedom33does not exist∞\infty

The last rows illustrate an important fact: a moment may not exist. The Cauchy law has no mean because E∣X∣=∞\E\abs{X} = \infty; a Pareto law with index α\alpha has finite moment of order pp if and only if p<αp < \alpha; Student tt with 33 degrees of freedom has variance 33 but infinite fourth moment. Moments are nested: if E∣X∣q<∞\E\abs{X}^q < \infty and p<qp < q, then E∣X∣p<∞\E\abs{X}^p < \infty, because ∣x∣p≤1+∣x∣q\abs{x}^p \le 1 + \abs{x}^q for every real number. Finite variance therefore implies a finite mean, but not conversely: Student tt with 22 degrees of freedom has mean 00 and infinite variance. Two practical consequences: sample variance’s variance involves the fourth moment, so for heavy-tailed data like t3t_3 the variance estimator converges with enormous fluctuations. And Pearson correlation, built from second moments, does not exist if either variance is infinite.

Covariance

A vector of dd features rarely has components moving separately. Covariance measures the variability two variables share.

Proof

(1) and (2) follow by expansion and linearity of expectation, as for variance. (3) follows from (2) and the fact that adding a constant leaves the centered variable unchanged. For (4), if X,YX, Y are independent, the joint law of (X,Y)(X, Y) is the product measure PX⊗PYP_X \otimes P_Y. By Tonelli, E∣XY∣=∫∣x∣ dPX∫∣y∣ dPY<∞\E\abs{XY} = \int\abs{x}\,\mathrm{d}P_X \int\abs{y}\,\mathrm{d}P_Y < \infty, so Fubini permits calculating E[XY]=∫ ⁣ ⁣∫xy dPXdPY=E[X]E[Y]\E[XY] = \int\!\!\int xy \,\mathrm{d}P_X\mathrm{d}P_Y = \E[X]\E[Y], and covariance is 00.

∎

Variables with Cov⁡(X,Y)=0\Cov(X, Y) = 0 are called uncorrelated. Part (4) says independence implies uncorrelatedness; the section on both explains why the converse is false. Covariance has a drawback: it changes with units (Cov⁡(aX,bY)=abCov⁡(X,Y)\Cov(aX, bY) = ab\Cov(X, Y)), so its magnitude can only be interpreted relative to standard deviations. Normalization gives a dimensionless number.

Correlation is a cosine

The key to understanding what follows is viewing L2L^2 as a geometric space. Equivalence classes of random variables in L2(Ω,F,P)L^2(\Omega, \mathcal{F}, \Pr) (identifying those equal almost surely) form a Hilbert space with inner product

⟨X,Y⟩=E[XY],∥X∥2=E[X2].\inner{X}{Y} = \E[XY], \qquad \norm{X}_2 = \sqrt{\E[X^2]}.

This is the exact analogue of the inner product on Rn\R^n, with expectation replacing summation. Constant 11 has norm 11 and ⟨X,1⟩=E[X]\inner{X}{1} = \E[X], so X↦E[X]⋅1X \mapsto \E[X]\cdot 1 is orthogonal projection onto constants, and centering a variable, X~=X−E[X]\tilde{X} = X - \E[X], projects onto the orthogonal complement of constants. The lesson’s three definitions become:

Var⁡(X)=∥X~∥22,σX=∥X~∥2,Cov⁡(X,Y)=⟨X~,Y~⟩.\Var(X) = \norm{\tilde{X}}_2^2, \qquad \sigma_X = \norm{\tilde{X}}_2, \qquad \Cov(X, Y) = \inner{\tilde{X}}{\tilde{Y}}.

Variance is the squared distance of XX to the subspace of constants (part (3) of the variance properties was Pythagoras), standard deviation is a length, and covariance an inner product of centered vectors. An inner product and two lengths give an angle.

The inequality is Cauchy–Schwarz in L2L^2 applied to centered variables; equality means parallel vectors. Details are the lesson’s second proof exercise. Invariance is immediate: changing units or origin does not alter the centered angle, while multiplying by a negative number reverses a vector.

The geometry has immediate consequences. With X~\tilde{X} and Y~\tilde{Y} as sides of a triangle, the cosine law is the variance formula for a sum:

Var⁡(X+Y)=∥X~+Y~∥22=σX2+σY2+2σXσY ρ.\Var(X + Y) = \norm{\tilde{X} + \tilde{Y}}_2^2 = \sigma_X^2 + \sigma_Y^2 + 2\sigma_X\sigma_Y\,\rho.

Uncorrelated variables are orthogonal, and their variances add by Pythagoras. Linear regression is a projection: the best affine predictor of YY from XX is the projection of YY onto the plane generated by 11 and XX.

Proof

Let Y^=μY+bX~\hat{Y} = \mu_Y + b\tilde{X} with that bb. Residual Y~−bX~\tilde{Y} - b\tilde{X} is orthogonal to X~\tilde{X}: ⟨Y~−bX~,X~⟩=Cov⁡(X,Y)−bVar⁡(X)=0\inner{\tilde{Y} - b\tilde{X}}{\tilde{X}} = \Cov(X, Y) - b\Var(X) = 0, and to constants too, because it has zero mean. For any other affine function a′+b′Xa' + b'X, Y−a′−b′X=(Y−Y^)+(Y^−a′−b′X)Y - a' - b'X = (Y - \hat{Y}) + (\hat{Y} - a' - b'X), where the first term is orthogonal to the plane generated by 11 and XX, which contains the second. By Pythagoras E[(Y−a′−b′X)2]=∥Y−Y^∥22+∥Y^−a′−b′X∥22≥∥Y−Y^∥22\E[(Y - a' - b'X)^2] = \norm{Y - \hat{Y}}_2^2 + \norm{\hat{Y} - a' - b'X}_2^2 \ge \norm{Y - \hat{Y}}_2^2. Finally ∥Y~−bX~∥22=σY2−2bCov⁡(X,Y)+b2σX2=σY2−Cov⁡(X,Y)2/σX2=σY2(1−ρ2)\norm{\tilde{Y} - b\tilde{X}}_2^2 = \sigma_Y^2 - 2b\Cov(X, Y) + b^2\sigma_X^2 = \sigma_Y^2 - \Cov(X, Y)^2/\sigma_X^2 = \sigma_Y^2(1 - \rho^2).

∎

Thus ρ2\rho^2 is the fraction of variance of YY explained by the best line, and 1−ρ21 - \rho^2 is the unexplained fraction. In trigonometry, cos⁡2θ\cos^2\theta versus sin⁡2θ\sin^2\theta.

Data have the same geometry

None of this requires abstract variables. If you have nn observations (xi,yi)(x_i, y_i), the empirical measure (mass 1/n1/n on each observation) is a law on Ω={1,…,n}\Omega = \{1, \dots, n\}, and L2L^2 is simply Rn\R^n. Centered variables are vectors x~=x−xˉ1\tilde{\vb{x}} = \vb{x} - \bar{x}\vb{1} and y~\tilde{\vb{y}} in hyperplane 1⊥\vb{1}^\perp, and the sample correlation coefficient is the cosine of their angle:

r=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2 ∑i(yi−yˉ)2=⟨x~,y~⟩∥x~∥ ∥y~∥.r = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_i (x_i - \bar{x})^2}\,\sqrt{\sum_i (y_i - \bar{y})^2}} = \frac{\inner{\tilde{\vb{x}}}{\tilde{\vb{y}}}}{\norm{\tilde{\vb{x}}}\,\norm{\tilde{\vb{y}}}}.

Two nonparallel vectors span a plane, so the angle can be drawn even for large nn. With n=3n = 3, the hyperplane 1⊥\vb{1}^\perp of centered vectors is already a plane, and the one spanned by x~\tilde{\vb{x}} and y~\tilde{\vb{y}} is the whole plane.

InteractiveCorrelation is a cosine
Data: 7 observations (xi,yi)(x_i, y_i)
XY
The same centered variables as vectors in Rn\R^n, in their spanning plane
θ = 33°
  • observations
  • XX and its centered vector X~\tilde X
  • YY and its centered vector Y~\tilde Y
  • regression, projection and sum
  • residuals
7
r=cos⁡θr = \cos\theta0.839
Angle θ\theta33.0°
Cov⁡(X,Y)\operatorname{Cov}(X, Y)1.575
σX\sigma_X (length of X~\tilde X)1.600
σY\sigma_Y (length of Y~\tilde Y)1.173
R2=cos⁡2θR^2 = \cos^2\theta0.704
Left: nn draggable observations. Right: centered variables X~\tilde X and Y~\tilde Y as vectors in Rn\R^n drawn in their spanning plane, with length equal to standard deviation. Their angle is θ\theta and r=cos⁡θr = \cos\theta. Start with positive dependence: drag a point up and down; what happens to the angle? Choose Orthogonal vectors and observe how r=0r = 0 does not force a round cloud. With One outlier, move the distant point: how much correlation depends on it? With regression enabled (the default), the projection residual is perpendicular to X~\tilde X and cos⁡2θ=R2\cos^2\theta = R^2. Enable the sum and compare Var⁡(X+Y)\operatorname{Var}(X + Y) with σX2+σY2\sigma_X^2 + \sigma_Y^2: when do they agree?

Three readings of the figure. First, rr depends only on angle: stretching or shrinking a vector (changing a variable’s scale) does not move it. Second, the regression line of YY on XX is the projection of y~\tilde{\vb{y}} onto x~\tilde{\vb{x}}, with error the remaining leg of length σYsin⁡θ\sigma_Y\sin\theta. Third, the outlier illustrates how fragile a cosine becomes when one vector is dominated by one coordinate: six points with correlation −0.07-0.07 become 0.810.81 after adding a distant seventh point.

The covariance matrix

For a random vector X=(X1,…,Xd)⊤\vb{X} = (X_1, \dots, X_d)\T with every component in L2L^2 (the joint law makes cross-covariances meaningful), there are dd variances and d(d−1)/2d(d-1)/2 distinct covariances. Arrange them in a matrix.

One identity tells us which matrices can be covariances and how they transform.

Proof

Expectation of a random matrix is linear: E[AMB]=AE[M]B\E[\mat{A}\mat{M}\mat{B}] = \mat{A}\E[\mat{M}]\mat{B} for constant matrices A,B\mat{A}, \mat{B}. The centered variable of Y=AX+b\vb{Y} = \mat{A}\vb{X} + \vb{b} is Y−E[Y]=A(X−μ)\vb{Y} - \E[\vb{Y}] = \mat{A}(\vb{X} - \vb{\mu}), and hence Cov⁡(Y)=E[A(X−μ)(X−μ)⊤A⊤]=A Σ A⊤\Cov(\vb{Y}) = \E\big[\mat{A}(\vb{X} - \vb{\mu})(\vb{X} - \vb{\mu})\T\mat{A}\T\big] = \mat{A}\,\mat{\Sigma}\,\mat{A}\T. Symmetry is that of Cov⁡(Xi,Xj)\Cov(X_i, X_j). Positive semidefiniteness of Σ\mat{\Sigma} and the characterization of positive definiteness follow by applying the formula with A=a⊤\mat{A} = \vb{a}\T and noting variance is always ≥0\ge 0 and equals 00 only for a constant: the first proof exercise.

∎

Positive semidefiniteness makes everything meaningful: Σ\mat{\Sigma} defines quadratic form v(a)=a⊤Σav(\vb{a}) = \vb{a}\T\mat{\Sigma}\vb{a} (quadratic form), which is projection variance along a\vb{a}. Every symmetric positive semidefinite matrix is a covariance matrix: if Z\vb{Z} has covariance I\mat{I} (for example, independent components of variance 11) and Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T, then X=LZ\vb{X} = \mat{L}\vb{Z} has covariance LIL⊤=Σ\mat{L}\mat{I}\mat{L}\T = \mat{\Sigma}. This is the recipe for multivariate Gaussian sampling using Cholesky.

Variance in every direction

Given the quadratic form, which directions maximize and minimize variance? Diagonalize Σ=QΛQ⊤\mat{\Sigma} = \mat{Q}\mat{\Lambda}\mat{Q}\T with λ1≥⋯≥λd≥0\lambda_1 \ge \cdots \ge \lambda_d \ge 0 and orthonormal eigenvectors qi\vb{q}_i (spectral theorem). For a unit vector u\vb{u},

u⊤Σu=∑i=1dλi (qi⊤u)2,∑i=1d(qi⊤u)2=1.\vb{u}\T\mat{\Sigma}\vb{u} = \sum_{i=1}^d \lambda_i\,(\vb{q}_i\T\vb{u})^2, \qquad \sum_{i=1}^d (\vb{q}_i\T\vb{u})^2 = 1.

This is a weighted average of eigenvalues, with weights cos⁡2\cos^2 from the angle to each axis. Thus λd≤u⊤Σu≤λ1\lambda_d \le \vb{u}\T\mat{\Sigma}\vb{u} \le \lambda_1, with equality at the extreme eigenvectors. In the plane, with u=(cos⁡θ,sin⁡θ)\vb{u} = (\cos\theta, \sin\theta) and major axis at angle θ1\theta_1,

v(θ)=λ1+λ22+λ1−λ22cos⁡(2(θ−θ1)),v(\theta) = \frac{\lambda_1 + \lambda_2}{2} + \frac{\lambda_1 - \lambda_2}{2}\cos\big(2(\theta - \theta_1)\big),

an oscillation of period 180°180° between λ2\lambda_2 and λ1\lambda_1. The set {x:x⊤Σ−1x=1}\{\vb{x} : \vb{x}\T\mat{\Sigma}\inv\vb{x} = 1\} is the covariance ellipse (the unit circle’s image under L\mat{L}), and its shadow on the line of u\vb{u} has half-width exactly u⊤Σu\sqrt{\vb{u}\T\mat{\Sigma}\vb{u}}.

InteractiveVariance in each direction
Cloud, covariance ellipse and projection onto u\vb{u}
v(θ)=uθ⊤Σuθv(\theta) = \vb{u}_\theta\T\mat{\Sigma}\vb{u}_\theta versus angle of u\vb{u}
0°45°90°135°180°λ maxλ min
  • unit vector u\vb{u}
  • cloud and level-1 and level-2 ellipses
  • major axis: eigenvector of λmax⁡\lambda_{\max}
  • minor axis: eigenvector of λmin⁡\lambda_{\min}
  • variance along u\vb{u}
11°
u⊤Σu\vb{u}\T\mat{\Sigma}\vb{u}3.137
Variance of projections (the cloud)3.137
u⊤Σu\sqrt{\vb{u}\T\mat{\Sigma}\vb{u}}1.771
Fraction of total variance76.5 %
Σ11, Σ22, Σ12\Sigma_{11},\ \Sigma_{22},\ \Sigma_{12}2.62, 1.48, 1.45
ρ=Σ12/Σ11Σ22\rho = \Sigma_{12}/\sqrt{\Sigma_{11}\Sigma_{22}}0.738
λmax⁡, λmin⁡\lambda_{\max},\ \lambda_{\min}3.610, 0.490
The cloud has sample covariance exactly equal to Σ\Sigma. Drag the orange endpoint (major axis: orientation and length) and turquoise endpoint (minor axis) to change Σ\Sigma. Rotate u\vb{u} (red arrow) around the dashed unit circle using its slider, or click the v(θ)v(\theta) curve. The magenta bar is the ellipse's shadow on the line of u\vb{u}, with half-length equal to projection standard deviation. Both variance readouts (formula u⊤Σu\vb{u}\T\Sigma\vb{u} and variance of projected points) agree. Find the curve's maxima and minima: at what angles are they, and how do they relate to the ellipse axes? With Round, what happens to the curve? With Nearly degenerate, what fraction of total variance lies on the major axis?

What you manipulated anticipates principal component analysis: the first principal component is the direction of maximal variance, the second the maximum orthogonal to the first, and so on. Total variance tr⁡Σ=∑iλi\tr\mat{\Sigma} = \sum_i\lambda_i does not change as axes rotate, and fraction λ1/tr⁡Σ\lambda_1/\tr\mat{\Sigma} is what the first component explains. Rotating into the eigenvector basis, Y=Q⊤(X−μ)\vb{Y} = \mat{Q}\T(\vb{X} - \vb{\mu}), gives through formula AΣA⊤\mat{A}\mat{\Sigma}\mat{A}\T a diagonal covariance Λ\mat{\Lambda}: uncorrelated coordinates. Additional scaling by Λ−1/2\mat{\Lambda}^{-1/2} yields covariance I\mat{I}, the whitening seen with the Gaussian.

Variance of sums and averages

Bilinearity of covariance immediately gives the variance of a sum.

Proof

Apply bilinearity of Cov⁡\Cov to Cov⁡(∑iXi,∑jXj)=∑i,jCov⁡(Xi,Xj)\Cov(\sum_i X_i, \sum_j X_j) = \sum_{i,j}\Cov(X_i, X_j), separating the diagonal. The matrix form is the case a=1\vb{a} = \vb{1} of the previous theorem.

∎

The most important statistical case is the average. Suppose n≥2n \ge 2 variables have common variance σ2\sigma^2 and common pairwise correlation ρ\rho. Then ∑i,jCov⁡(Xi,Xj)=nσ2+n(n−1)ρσ2\sum_{i,j}\Cov(X_i, X_j) = n\sigma^2 + n(n-1)\rho\sigma^2, and dividing by n2n^2,

Var⁡(Xˉn)=σ2n+n−1nρσ2=σ2(ρ+1−ρn).\Var(\bar{X}_n) = \frac{\sigma^2}{n} + \frac{n - 1}{n}\rho\sigma^2 = \sigma^2\left(\rho + \frac{1 - \rho}{n}\right).

With ρ=0\rho = 0 this recovers σ2/n\sigma^2/n. But with ρ>0\rho > 0 the second term, divided by nn, vanishes as nn grows, leaving a floor: Var⁡(Xˉn)→ρσ2\Var(\bar{X}_n) \to \rho\sigma^2. With the opening values (σ2=1\sigma^2 = 1, ρ=0.1\rho = 0.1, n=100n = 100), 0.1+0.9/100=0.1090.1 + 0.9/100 = 0.109.

A useful measure asks how many independent observations your nn correlated observations are worth. The effective sample size is the nefn_{\mathrm{ef}} yielding the same variance under independence, σ2/nef=Var⁡(Xˉn)\sigma^2/n_{\mathrm{ef}} = \Var(\bar{X}_n):

nef=n1+(n−1)ρ  →n→∞  1ρ.n_{\mathrm{ef}} = \frac{n}{1 + (n - 1)\rho} \;\xrightarrow[n \to \infty]{}\; \frac{1}{\rho}.

The earlier 100100 observations are worth nef=9.17n_{\mathrm{ef}} = 9.17 independent ones, and no amount of data with ρ=0.1\rho = 0.1 is worth more than 1010. The cause is structural. For ρ≥0\rho \ge 0, the model Xi=ρ Z+1−ρ εiX_i = \sqrt{\rho}\,Z + \sqrt{1 - \rho}\,\varepsilon_i with independent Z,εiZ, \varepsilon_i of variance 11 has exactly that covariance, and its average is ρ Z+1−ρ εˉ\sqrt{\rho}\,Z + \sqrt{1-\rho}\,\bar{\varepsilon}: the idiosyncratic part εˉ\bar{\varepsilon} averages away, but the common factor ZZ appears in full in every variable and never averages away. The same calculation limits portfolio diversification: equal capital across nn assets with volatility σ\sigma and correlation ρ\rho gives return variance σ2(ρ+(1−ρ)/n)\sigma^2(\rho + (1-\rho)/n), eliminating each asset’s individual risk but never falling below common market risk ρσ2\rho\sigma^2.

InteractiveThe correlation floor
Variance of the mean versus nn (log–log, horizontal: nn)
124816326412825610.10.01σ²/nfloor ρσ²
  • ρ+(1−ρ)/n\rho + (1-\rho)/n
  • simulation
  • 1/n1/n (independent)
  • floor ρ\rho
Running means Xˉk\bar X_k from 10 repetitions, with band ±2\pm 2 standard deviations (horizontal: kk)
1248163264128256−202
0.10
64
Var⁡(Xˉ)/σ2\operatorname{Var}(\bar X)/\sigma^2 exact0.1141
Simulation (400 repetitions)0.1241
If independent, 1/n1/n0.0156
Floor ρ\rho (as n→∞n \to \infty)0.1000
Effective sample size nefn_{\mathrm{ef}}8.77
Maximum possible nefn_{\mathrm{ef}}, 1/ρ1/\rho10.0
You have reached the floor ρσ2\rho\sigma^2: adding correlated data barely helps. Trajectories have settled at different levels.
Left: variance of the mean of nn variables with pairwise correlation ρ\rho, on log–log axes: theoretical curve ρ+(1−ρ)/n\rho + (1-\rho)/n, points from 400 simulated repetitions, and the independent 1/n1/n line. Right: running means Xˉk\bar X_k from 10 repetitions, with a ±2\pm 2 standard-deviation band. First lower ρ\rho to 00: trajectories converge to 00. Raise it to 0.10.1: the curve bends toward the floor and trajectories stop joining at 00, settling at different levels. Which level, in terms of the common-factor model? At how many observations is mean variance twice the floor? Set ρ\rho to 0.50.5 and read nefn_{\mathrm{ef}} for n=256n = 256.

Correlation may also be negative, within limits. Since mean variance cannot be negative, ρ+(1−ρ)/n≥0\rho + (1 - \rho)/n \ge 0, that is ρ≥−1/(n−1)\rho \ge -1/(n - 1); with n=10n = 10 variables there is no way for every pair to have correlation −0.2-0.2. This is exactly the condition for equicorrelation matrix (1−ρ)I+ρ11⊤(1 - \rho)\mat{I} + \rho\vb{1}\vb{1}\T, with eigenvalues 1+(n−1)ρ1 + (n-1)\rho and 1−ρ1 - \rho, to be positive semidefinite. The limiting case occurs in a concrete setting: sampling without replacement BB elements from a finite population of NN values with population variance σ2\sigma^2 gives variables with pairwise correlation ρ=−1/(N−1)\rho = -1/(N-1), so

Var⁡(XˉB)=σ2B⋅N−BN−1.\Var(\bar{X}_B) = \frac{\sigma^2}{B}\cdot\frac{N - B}{N - 1}.

The second factor is the finite-population correction: with N=1000N = 1000 and B=100B = 100, variance is 10 %10\,\% lower than a batch sampled with replacement (0.00901 σ20.00901\,\sigma^2 versus 0.01 σ20.01\,\sigma^2), and with B=NB = N equals 00 because the whole population has been averaged.

In time series, correlations decay with distance instead of being equal. For a stationary process with correlation ρ(h)\rho(h) at lag hh, nVar⁡(Xˉn)/σ2n\Var(\bar{X}_n)/\sigma^2 tends to ∑h∈Zρ(h)\sum_{h\in\mathbb{Z}}\rho(h) (the long-run variance) when that sum converges. For a first-order autoregression ρ(h)=φ∣h∣\rho(h) = \varphi^{\abs{h}}, the sum is (1+φ)/(1−φ)(1 + \varphi)/(1 - \varphi) and nef≈n(1−φ)/(1+φ)n_{\mathrm{ef}} \approx n(1 - \varphi)/(1 + \varphi): with φ=0.9\varphi = 0.9, every 1919 observations are worth approximately one. This is covered in the time-series lesson and explains why MCMC confidence intervals use nefn_{\mathrm{ef}}, not nn.

The proof is one line. Expanding the square gives ∑i(Xi−Xˉ)2=∑i(Xi−μ)2−n(Xˉ−μ)2\sum_i(X_i - \bar{X})^2 = \sum_i(X_i - \mu)^2 - n(\bar{X} - \mu)^2; taking expectations gives nσ2−nVar⁡(Xˉ)=nσ2(1−ρ−(1−ρ)/n)=(n−1)(1−ρ)σ2n\sigma^2 - n\Var(\bar{X}) = n\sigma^2\big(1 - \rho - (1 - \rho)/n\big) = (n-1)(1 - \rho)\sigma^2. Bessel’s divisor n−1n - 1 compensates for fitting the sample mean to the same data; correlation additionally makes observed variability less than actual variability because observations resemble each other too much.

Uncorrelatedness versus independence

We already saw that independence implies uncorrelatedness. The converse is false, and confusing the two is common.

The mechanism is general: if XX has a law symmetric around 00 with E[X2]<∞\E[X^2] < \infty and gg is an even function with g(X)∈L2g(X) \in L^2, then Cov⁡(X,g(X))=E[Xg(X)]=0\Cov(X, g(X)) = \E[X g(X)] = 0 because x g(x)x\,g(x) is odd. Other examples with this pattern: a uniform point on the unit circle, (X,Y)=(cos⁡Θ,sin⁡Θ)(X, Y) = (\cos\Theta, \sin\Theta), has Cov⁡(X,Y)=0\Cov(X, Y) = 0 yet X2+Y2=1X^2 + Y^2 = 1; and if S=±1S = \pm 1 is independent of X∼N(0,1)X \sim \Normal(0,1), then Y=SXY = SX is also N(0,1)\Normal(0, 1), uncorrelated with XX and ∣Y∣=∣X∣\abs{Y} = \abs{X}. This last example has two normal marginals but is not jointly Gaussian: for a jointly Gaussian vector, uncorrelatedness does imply independence (uncorrelatedness and independence in jointly Gaussian vectors), making joint Gaussianity the most important context where the distinction can be set aside. It is not the only one: if XX and YY each take only two values, uncorrelatedness is equivalent to independence too (check with indicators: Cov⁡(1A,1B)=P(A∩B)−P(A)P(B)\Cov(\ind_A, \ind_B) = \Pr(A \cap B) - \Pr(A)\Pr(B)). But these are special cases; generally orthogonality says nothing about independence.

The underlying reason is geometric. Correlation is the cosine of the angle between X~\tilde{X} and Y~\tilde{Y} in L2L^2, whereas independence is a condition on all functions: Cov⁡(f(X),g(Y))=0\Cov(f(X), g(Y)) = 0 for every pair of bounded functions. Pearson sees only f(x)=xf(x) = x and g(y)=yg(y) = y. Thus ρ2\rho^2 is the variance fraction explained by the best line, and nonlinear dependence can pass unnoticed.

InteractiveZero correlation, total dependence
Sample of Y=X2Y = X^2 plus noise and slope
  • samples
  • mean of YY by bins of XX
  • best line (what Pearson sees)
All six families with the same noise and slope
  • Pearson ∣r∣\abs{r}
  • distance correlation
0.15
0.00
200
Pearson rr−0.032
Spearman (ranks)0.047
Distance correlation0.462
…shuffling YY (baseline)0.118
Variance of YY explained by bins of XX87 %
Pearson says almost nothing while dependence is total (or nearly so). Distance correlation, with its baseline, detects it.
Six data families and four dependence measures. Pearson rr measures linear correlation; Spearman is Pearson on ranks (detecting monotone relations); distance correlation (Székely, Rizzo and Bakirov, 2007) is 00 in the population if and only if independent; the final readout is the fraction of YY variance explained by its means across bins of XX. With the parabola and little noise, Pearson and Spearman are near 00 (the parabola is not monotone), while the other two are not. Increase noise until distance correlation falls toward its shuffled baseline: at what noise level does the parabola stop being visible? Add linear slope to the sinusoid: what does Pearson capture, and what does it miss? Press New sample several times: how much does rr fluctuate when the family has no linear component? With small nn, why is the shuffled distance-correlation baseline nonzero?

Two qualifications for interpreting the numbers. Distance correlation and variance fraction explained by bins are never negative and with few samples are biased upward even under independence (the second on the order of (tramos−1)/n(\text{tramos} - 1)/n). The widget therefore compares distance correlation with its value after shuffling YY, which breaks dependence while preserving marginals. Rank correlations, Spearman and Kendall, solve another problem: detecting any monotone relation, not necessarily linear, while resisting outliers. They still miss a symmetric parabola.

Markov and Chebyshev inequalities

If little is known about a variable, perhaps only its mean or its mean and variance, what can be guaranteed about the probability of a large deviation? The simplest answer is Markov’s inequality.

Proof

Since X≥0X \ge 0, a 1[X≥a]≤Xa\,\ind[X \ge a] \le X holds pointwise: if X≥aX \ge a, the left side is a≤Xa \le X, and if X<aX < a it is 0≤X0 \le X. Taking expectations gives aP(X≥a)≤E[X]a\Pr(X \ge a) \le \E[X]. Equality requires a 1[X≥a]=Xa\,\ind[X \ge a] = X almost surely, that is, X=aX = a when X≥aX \ge a and X=0X = 0 when X<aX < a.

∎

The assumption bears repeating because it is forgotten: X≥0X \ge 0. With it, the inequality says a nonnegative response time averaging 200200 ms exceeds 11 s with probability at most 0.20.2, without further information. Applied to φ(X)\varphi(X) with nondecreasing φ≥0\varphi \ge 0 and φ(a)>0\varphi(a) > 0 it gives P(X≥a)≤P(φ(X)≥φ(a))≤E[φ(X)]/φ(a)\Pr(X \ge a) \le \Pr(\varphi(X) \ge \varphi(a)) \le \E[\varphi(X)]/\varphi(a), where XX may now be negative. With φ(x)=x2\varphi(x) = x^2 in [0,∞)[0, \infty), applied to ∣X−μ∣\abs{X - \mu}, we obtain Chebyshev; with φ(x)=etx\varphi(x) = e^{tx}, the Chernoff method (later) gives exponential tails.

Proof

Apply Markov to Y=(X−μ)2≥0Y = (X - \mu)^2 \ge 0 with a=t2a = t^2: P(∣X−μ∣≥t)=P(Y≥t2)≤E[Y]/t2=σ2/t2\Pr(\abs{X - \mu} \ge t) = \Pr(Y \ge t^2) \le \E[Y]/t^2 = \sigma^2/t^2. To see sharpness, take k>1k > 1 and the law with P(X=μ±kσ)=12k2\Pr(X = \mu \pm k\sigma) = \tfrac{1}{2k^2} each and P(X=μ)=1−1/k2\Pr(X = \mu) = 1 - 1/k^2. Its variance is 2⋅12k2⋅k2σ2=σ22\cdot\tfrac{1}{2k^2}\cdot k^2\sigma^2 = \sigma^2 and P(∣X−μ∣≥kσ)=1/k2\Pr(\abs{X - \mu} \ge k\sigma) = 1/k^2 exactly.

∎

For k≤1k \le 1 the bound is 11 or more and says nothing. For k=2k = 2 it gives 25 %25\,\% and for k=3k = 3, 11.1 %11.1\,\% without any shape assumption. This universality is both strength and weakness: the three-point law shows no improvement is possible using only μ\mu and σ\sigma, but few real laws resemble it. For a normal variable, probability beyond 2σ2\sigma is 4.55 %4.55\,\% (the bound overstates it by 5.55.5) and beyond 3σ3\sigma it is 0.27 %0.27\,\% (by 4141). For an exponential at 3σ3\sigma from the mean, P(X−1≥3)=e−4≈1.8 %\Pr(X - 1 \ge 3) = e^{-4} \approx 1.8\,\%. The true tail depends on information Chebyshev ignores, while the Hoeffding and sub-Gaussian lesson uses it for exponential tails.

InteractiveTail bounds versus reality
The law of Z=(X−μ)/σZ = (X - \mu)/\sigma and its tails beyond kk
−4σ−2σμ2σ4σ
Exact tail P(∣Z∣≥k)\Pr(\abs{Z} \ge k) versus bound 1/k21/k^2 (log scale, horizontal: kk)
0123456110⁻¹10⁻²10⁻³10⁻⁴10⁻⁵
  • exact tail of selected law
  • Chebyshev bound 1/k21/k^2
2.00
P(∣X−μ∣≥kσ)\Pr(\abs{X - \mu} \ge k\sigma) exact0.0455
Chebyshev bound min⁡(1,1/k2)\min(1, 1/k^2)0.2500
Bound / actual×5.49
Kurtosis m4/σ4m_4/\sigma^43.00
Characterlight tails
Left: the standardized law of XX, with tails beyond kk standard deviations in red. Right: exact tail versus the 1/k21/k^2 bound on a logarithmic scale. The bound is an envelope respected by every law and almost no reasonable law comes close to touching it. Choose the normal with k=2k = 2: by what factor is the bound wrong? Move to k=4k = 4. Compare tails of the normal, Laplace and Student tt with 3 degrees of freedom: which decays most slowly and how does this relate to its moments? Choose the extreme law and move kk (with k≥1k \ge 1): the tail touches the bound at the selected kk, then drops to 00. Choose the uniform: why is its tail exactly 00 beyond a certain kk?

Two applications recur later. First, the weak law of large numbers: for independent X1,…,XnX_1, \dots, X_n with variance σ2\sigma^2, Chebyshev gives P(∣Xˉn−μ∣≥ε)≤σ2/(nε2)→0\Pr(\abs{\bar{X}_n - \mu} \ge \varepsilon) \le \sigma^2/(n\varepsilon^2) \to 0 at an explicit rate (see the weak law lesson). With correlation ρ>0\rho > 0 the same argument gives σ2(ρ+(1−ρ)/n)/ε2\sigma^2(\rho + (1-\rho)/n)/\varepsilon^2, which does not tend to 00: the previous section’s floor also limits concentration. Second, the second-moment method: for a count N≥0N \ge 0 with EN>0\E N > 0, event N=0N = 0 is contained in ∣N−EN∣≥EN\abs{N - \E N} \ge \E N, so P(N=0)≤Var⁡(N)/(EN)2\Pr(N = 0) \le \Var(N)/(\E N)^2. If variance is small relative to squared mean, NN is positive with high probability (Paley–Zygmund refines this).

Stable computation: Welford versus the classroom formula

Every identity in this lesson has a version that can compute poorly. The most common is variance as E[X2]−(E[X])2\E[X^2] - (\E[X])^2. It is correct in exact arithmetic; in floating point, when the mean is large relative to standard deviation, it subtracts two enormous nearly equal numbers. With data X=108+εX = 10^8 + \varepsilon, ε∼N(0,1)\varepsilon \sim \Normal(0, 1), the value of E[X2]\E[X^2] is 101610^{16}, and float64 relative rounding of ≈1.1×10−16\approx 1.1\times 10^{-16} gives absolute error of order 11: the entire variance. It can even become negative. With float32, which has 2424 mantissa bits, a mean of 10410^4 suffices.

Welford’s algorithm (1962) maintains mean and centered sum of squares M2=∑i(xi−xˉn)2M_2 = \sum_i(x_i - \bar{x}_n)^2, updating one observation at a time without subtracting large numbers.

xn−xˉn=δ−δn=n−1n δx_n - \bar{x}_n = \delta - \frac{\delta}{n} = \frac{n-1}{n}\,\delta
The first recurrence updates the mean. It gives the new observation’s contribution, the second factor.
1/4

Stability appears in the result. Factors δ\delta and xn−xˉnx_n - \bar{x}_n have the same sign, so every increment of M2M_2 is nonnegative: no large quantity is subtracted from another. The only subtraction is x−xˉx - \bar{x}, between similar numbers and thus almost always exact, with magnitudes of the order of data dispersion rather than position. For vectors the same calculation gives matrix recurrence Mn=Mn−1+n−1n δδ⊤\mat{M}_n = \mat{M}_{n-1} + \frac{n-1}{n}\,\vb{\delta}\vb{\delta}\T with δ=xn−xˉn−1\vb{\delta} = \vb{x}_n - \bar{\vb{x}}_{n-1}, which also keeps Mn\mat{M}_n symmetric positive semidefinite by construction, and S=Mn/(n−1)\mat{S} = \mat{M}_n/(n-1). An important consequence: two data groups with (na,xˉa,Ma)(n_a, \bar{\vb{x}}_a, \mat{M}_a) and (nb,xˉb,Mb)(n_b, \bar{\vb{x}}_b, \mat{M}_b) can be merged without revisiting the data (Chan, Golub and LeVeque, 1983):

xˉ=xˉa+nbn δ,M=Ma+Mb+nanbn δδ⊤,n=na+nb,  δ=xˉb−xˉa.\bar{\vb{x}} = \bar{\vb{x}}_a + \frac{n_b}{n}\,\vb{\delta}, \qquad \mat{M} = \mat{M}_a + \mat{M}_b + \frac{n_a n_b}{n}\,\vb{\delta}\vb{\delta}\T, \qquad n = n_a + n_b,\; \vb{\delta} = \bar{\vb{x}}_b - \bar{\vb{x}}_a.

This formula distributes computation across processes or devices and combines partial summaries.

Implementation from scratch

First, moments and relations from the lesson using NumPy without statistical functions: skewness and kurtosis, covariance and correlation as inner product and cosine, and transformation AΣA⊤\mat{A}\mat{\Sigma}\mat{A}\T applied to data.

[ ]Moments, covariance and cosineBrowser
import numpy as np

rng = np.random.default_rng(0)

def momentos(x):
    """Media, varianza (divisor n), asimetría y curtosis, con los datos como medida empírica."""
    x = np.asarray(x, dtype=float)
    mu = x.mean()
    z = x - mu
    var = np.mean(z**2)
    return mu, var, np.mean(z**3) / var**1.5, np.mean(z**4) / var**2

for nombre, x in [("normal", rng.normal(size=200_000)),
                  ("exponencial", rng.exponential(size=200_000)),
                  ("uniforme", rng.uniform(size=200_000)),
                  ("Laplace", rng.laplace(size=200_000))]:
    mu, var, g1, kap = momentos(x)
    print(f"{nombre:12s} media {mu:6.3f}  var {var:6.3f}  asimetría {g1:6.3f}  curtosis {kap:6.3f}")

# covarianza y correlación como producto escalar y coseno de vectores centrados
x = rng.normal(size=500)
y = 0.6 * x + 0.8 * rng.normal(size=500)
xc, yc = x - x.mean(), y - y.mean()
cov = xc @ yc / len(x)
r = xc @ yc / (np.linalg.norm(xc) * np.linalg.norm(yc))
print(f"\nCov = {cov:.4f}   r = coseno = {r:.4f}   ángulo = {np.degrees(np.arccos(r)):.2f}°")
print("np.corrcoef:", round(np.corrcoef(x, y)[0, 1], 4))

# matriz de covarianzas y transformación lineal
def cov_matriz(X):
    """Matriz de covarianzas muestral (divisor n - 1) de las filas de X."""
    Xc = X - X.mean(axis=0)
    return Xc.T @ Xc / (len(X) - 1)

X = rng.multivariate_normal([0, 0, 0], [[4, 1.2, 0], [1.2, 1, 0.5], [0, 0.5, 2]], size=2000)
S = cov_matriz(X)
A = np.array([[1.0, -1.0, 0.0], [0.5, 0.5, 1.0]])
print("\nS =\n", np.round(S, 3))
print("cov(AX) - A S A^T, máxima diferencia:", np.abs(cov_matriz(X @ A.T) - A @ S @ A.T).max())
print("Var(X1 - X2) =", round((A @ S @ A.T)[0, 0], 3), "  (4 + 1 - 2 * 1.2 = 2.6 en la población)")

# varianza en cada dirección: autovalores de S y su máximo
lam, Q = np.linalg.eigh(S)
u = Q[:, -1]
print("\nautovalores:", np.round(lam, 3), "  tr S =", round(np.trace(S), 3), " suma =", round(lam.sum(), 3))
print("varianza de la proyección sobre el autovector mayor:", round(np.var(X @ u, ddof=1), 3), " lambda_max:", round(lam[-1], 3))

The code shows projection variance on the major eigenvector equals λmax⁡\lambda_{\max}, and ASA⊤\mat{A}\mat{S}\mat{A}\T is the sample covariance of Ax\mat{A}\vb{x} (for sample covariance equality is algebraic, not merely asymptotic). Now correlated averages: simulate the common-factor model and compare with the formulas, including Bessel correction with correlation and the autoregression.

[ ]Correlated averages and effective sample sizeBrowser
import numpy as np

rng = np.random.default_rng(1)
n, rho, reps = 100, 0.1, 20_000

# modelo de factor común: X_i = sqrt(rho) Z + sqrt(1 - rho) eps_i
Z = rng.normal(size=(reps, 1))
X = np.sqrt(rho) * Z + np.sqrt(1 - rho) * rng.normal(size=(reps, n))
medias = X.mean(axis=1)

teo = rho + (1 - rho) / n
print(f"Var(media): simulada {medias.var():.4f}   teórica {teo:.4f}   si fuesen independientes {1/n:.4f}")
print(f"n_ef = {n / (1 + (n - 1) * rho):.2f}   techo 1/rho = {1/rho:.0f}")
print(f"E[S^2] simulada (divisor n-1): {X.var(axis=1, ddof=1).mean():.4f}   teórica (1 - rho) = {1 - rho:.4f}")

# la media no converge a 0: se pega a sqrt(rho) Z
corr_media_Z = np.corrcoef(medias, Z[:, 0])[0, 1]
print(f"correlación entre la media y el factor común Z: {corr_media_Z:.3f}   (teórica {np.sqrt(rho / teo):.3f})")

# muestreo sin reemplazo de una población finita: rho = -1/(N-1)
N, B = 1000, 100
pob = rng.normal(size=N)
var_pob = pob.var()                                   # varianza poblacional (divisor N)
lotes = np.array([rng.choice(pob, size=B, replace=False).mean() for _ in range(6000)])
print(f"\nsin reemplazo (N={N}, B={B}): Var simulada {lotes.var():.5f}   teórica {var_pob / B * (N - B) / (N - 1):.5f}   con reemplazo {var_pob / B:.5f}")

# autorregresivo de primer orden: n_ef = n^2 / suma de todas las covarianzas (varianza 1)
phi, m = 0.9, 400
idx = np.arange(m)
C = phi ** np.abs(idx[:, None] - idx[None, :])
print(f"\nAR(1) con phi = {phi}: n_ef exacto = {m**2 / C.sum():.1f}   aproximación n(1-phi)/(1+phi) = {m * (1 - phi) / (1 + phi):.1f}")

The most striking result is the bias of S2S^2: at correlation 0.10.1 data appear 10 %10\,\% less dispersed than they are. Now stable computation: first mean and variance in one pass compared with the classroom formula, then the vector covariance version and merger of two groups.

[ ]Welford versus E[X²] - E[X]²Browser
import numpy as np

def welford(x):
    """Media y varianza (divisor n - 1) en una sola pasada, sin guardar los datos."""
    n, media, M2 = 0, 0.0, 0.0
    for v in x:
        n += 1
        delta = v - media
        media += delta / n
        M2 += delta * (v - media)
    return media, M2 / (n - 1)

def ingenua(x):
    x = np.asarray(x)
    return x.mean(), (np.mean(x**2) - np.mean(x) ** 2) * len(x) / (len(x) - 1)

rng = np.random.default_rng(2)
ruido = rng.normal(size=4000)                      # varianza verdadera ~ 1

print("float64, desviación típica 1:")
for centro in [0.0, 1e4, 1e8, 1e9]:
    x = centro + ruido
    ref = np.var(x - np.mean(x), ddof=1)           # referencia: restar la media antes de elevar
    print(f"  media {centro:8.0e}:  referencia {ref:8.5f}   Welford {welford(x)[1]:8.5f}   fórmula de clase {ingenua(x)[1]:10.4f}")

print("float32, desviación típica 1:")
for centro in [0.0, 1e3, 1e4, 1e5]:
    x = (centro + ruido).astype(np.float32)
    ref = np.var(x.astype(np.float64) - x.astype(np.float64).mean(), ddof=1)
    media32 = np.float32(0); M2_32 = np.float32(0)
    for i, v in enumerate(x, start=1):
        d = v - media32
        media32 = media32 + d / np.float32(i)
        M2_32 = M2_32 + d * (v - media32)
    clase32 = (np.mean(x**2, dtype=np.float32) - np.mean(x, dtype=np.float32) ** 2) * np.float32(len(x) / (len(x) - 1))
    print(f"  media {centro:8.0e}:  referencia {ref:8.5f}   Welford en float32 {float(M2_32 / np.float32(len(x) - 1)):8.5f}   clase en float32 {float(clase32):12.4f}")

The float64 classroom formula is perfect up to means 10410^4, gives 4.04.0 instead of 1.0061.006 with 10810^8, and a negative variance with 10910^9, while Welford agrees with the reference in every row. In float32 the problem arrives much earlier: already noticeable at mean 10310^3, with 10410^4 the classroom formula returns −16-16 (a negative variance) and with 10510^5, 00; float32 Welford preserves the result to that point with error of order 10−310^{-3}. (The data themselves lose resolution as the mean grows: with 10510^5 and float32, the gap between representable numbers is 0.00780.0078, so the reference already reflects rounded data.) The vector version remains, with matrix recurrence and Chan merger checked against np.cov.

[ ]Streaming covariance and merging groupsBrowser
import numpy as np

def welford_cov(filas):
    """Media y covarianza (divisor n - 1) de las filas, una por una."""
    n, media, M = 0, None, None
    for x in filas:
        x = np.asarray(x, dtype=np.float64)
        if media is None:
            media, M = np.zeros_like(x), np.zeros((x.size, x.size))
        n += 1
        delta = x - media
        media = media + delta / n
        M = M + np.outer(delta, x - media)          # = (n-1)/n delta delta^T: simétrica y semidefinida positiva
    return n, media, M

def fusionar(a, b):
    """Combina los resúmenes (n, media, M) de dos grupos de datos (Chan, Golub y LeVeque)."""
    (na, ma, Ma), (nb, mb, Mb) = a, b
    n = na + nb
    delta = mb - ma
    return n, ma + delta * nb / n, Ma + Mb + np.outer(delta, delta) * na * nb / n

rng = np.random.default_rng(3)
Sigma = np.array([[1.0, 0.9, 0.0], [0.9, 1.0, 0.3], [0.0, 0.3, 0.5]])
X = rng.multivariate_normal([1e8, -1e8, 5.0], Sigma, size=3000)      # medias enormes, covarianza pequeña

n, m, M = welford_cov(X)
ref = np.cov(X - X.mean(axis=0), rowvar=False)                       # referencia estable
print("error máximo, Welford:        ", np.abs(M / (n - 1) - ref).max())

naive = (X.T @ X) / len(X) - np.outer(X.mean(axis=0), X.mean(axis=0))
print("error máximo, E[XX^T] - mm^T: ", np.abs(naive * len(X) / (len(X) - 1) - ref).max())

# fusión: tres trozos procesados por separado, combinados en orden arbitrario
trozos = [welford_cov(X[i:j]) for i, j in [(0, 1000), (1000, 2200), (2200, 3000)]]
total = fusionar(fusionar(trozos[2], trozos[0]), trozos[1])
print("error de la fusión (media):   ", np.abs(total[1] - m).max())
print("error de la fusión (cov):     ", np.abs(total[2] / (total[0] - 1) - M / (n - 1)).max())
print("autovalores de la cov de Welford:", np.round(np.linalg.eigvalsh(M / (n - 1)), 4))

The classroom matrix formula has error around ten units, larger than the covariances themselves (less than 22), and can return matrices not even positive semidefinite. Welford’s error is 10−810^{-8} and preserves structure: all eigenvalues are positive. Finally compare Markov and Chebyshev with reality by simulating four laws with known mean and variance.

[ ]Markov and Chebyshev by simulationBrowser
import numpy as np

rng = np.random.default_rng(4)
m = 400_000

def extrema(k, size):
    """Tres átomos: 0 con prob 1 - 1/k^2 y ±k con 1/(2k^2) cada uno (media 0, varianza 1)."""
    u = rng.uniform(size=size)
    return np.where(u < 1 / (k * k), np.where(rng.uniform(size=size) < 0.5, -k, k), 0.0)

leyes = {
    "normal": rng.normal(size=m),
    "Laplace": rng.laplace(size=m) / np.sqrt(2),
    "exponencial": rng.exponential(size=m) - 1.0,
    "t con 3 g.l.": rng.standard_t(3, size=m) / np.sqrt(3),
    "extrema (k=3)": extrema(3, m),
}

print("Cola empírica P(|X - mu| >= k sigma) frente a la cota de Chebyshev 1/k^2")
print(f"{'ley':14s}" + "".join(f"   k={k}: real / cota" for k in (2, 3, 4)))
for nombre, x in leyes.items():
    z = x                                          # todas tienen media 0 y varianza 1 exactas
    fila = "".join(f"   {np.mean(np.abs(z) >= k):6.4f} / {1 / k**2:6.4f}" for k in (2, 3, 4))
    print(f"{nombre:14s}{fila}")

# Markov: X >= 0 con media 1, P(X >= a) <= 1/a
x = rng.exponential(size=m)
print("\nMarkov con X ~ Exp(1):", "  ".join(f"a={a}: {np.mean(x >= a):.4f} <= {1/a:.4f}" for a in (2, 5, 10)))
# y la falla si X puede ser negativa
y = rng.choice([-1.0, 1.0], size=m)
print("X = ±1 con media 0:  P(X >= 1) =", round(np.mean(y >= 1), 3), " y E[X]/1 =", round(y.mean(), 3), " (Markov no se aplica)")

The extreme law, built with k=3k = 3, is the only one reaching 1/9=0.11111/9 = 0.1111 at k=3k = 3 (and at k=2k = 2 it also gives 1/91/9, because its atoms lie beyond 2σ2\sigma and bound 1/41/4 is not sharp there); the rest lie well below, especially the normal. At k=4k = 4 the heavier-tailed exponential and t3t_3 come closest, yet the bound is about ten times reality.

The professional version

TaskNumPyPyTorch
Sample variance (divisor n−1n - 1)np.var(x, ddof=1)torch.var(x) (default correction n−1n - 1)
Population variance (divisor nn)np.var(x) (default)torch.var(x, correction=0)
Covariance matrixnp.cov(X, rowvar=False) (rows = observations)torch.cov(X.T) (variables in rows)
Correlationnp.corrcoef(X, rowvar=False)torch.corrcoef(X.T)
Skewness and kurtosisscipy.stats.skew, scipy.stats.kurtosisby hand

The most common confusion is conventions. np.cov expects variables in rows by default (rowvar=True), opposite to Oryon Learn’s design matrix X∈Rn×d\mat{X} \in \R^{n\times d}, and uses divisor n−1n - 1; np.var uses nn. scipy.stats.kurtosis returns excess by default (subtracts 33). And torch.var has always corrected using n−1n-1, but the current API expresses this with correction, not unbiased.

[ ]NumPy and SciPy conventionsBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(5)
X = rng.multivariate_normal([0, 0], [[1, 0.7], [0.7, 2]], size=500)

print("np.var ddof=0 / ddof=1:", round(np.var(X[:, 0]), 4), round(np.var(X[:, 0], ddof=1), 4))
print("np.cov con rowvar=False:\n", np.round(np.cov(X, rowvar=False), 3))
print("np.cov(X) sin rowvar interpreta cada FILA como una variable: forma", np.cov(X).shape)
print("np.corrcoef:\n", np.round(np.corrcoef(X, rowvar=False), 3))

e = rng.exponential(size=100_000)
print("\nexponencial: asimetría", round(stats.skew(e), 3), " curtosis (exceso)", round(stats.kurtosis(e), 3),
      " curtosis (Pearson)", round(stats.kurtosis(e, fisher=False), 3))

# Pearson frente a Spearman en una relación monótona y en una parábola
x = rng.uniform(-1, 1, 400)
for nombre, y in [("y = x^3", x**3), ("y = x^2", x**2)]:
    print(f"{nombre}:  Pearson {stats.pearsonr(x, y)[0]:6.3f}   Spearman {stats.spearmanr(x, y)[0]:6.3f}")
import torch

X = torch.randn(500, 3)                      # una observación por fila
S = torch.cov(X.T)                           # torch.cov espera las variables en las filas
R = torch.corrcoef(X.T)
v1 = torch.var(X[:, 0])                      # divisor n - 1
v0 = torch.var(X[:, 0], correction=0)        # divisor n

A note on networks: batch normalization layers maintain mean and variance statistics with an exponential moving average and calculate batch variance using divisor nn in the forward pass (in PyTorch the running variance instead uses divisor n−1n - 1). This is an engineering choice, not an unbiased estimate, and matters when comparing implementations.

Common mistakes

Exercises

ProofA covariance matrix is positive semidefinite
Prove: If X∈L2(Ω;Rd)\vb{X} \in L^2(\Omega; \R^d) has covariance matrix Σ\mat{\Sigma}, then Σ\mat{\Sigma} is symmetric and positive semidefinite, and Var⁡(a⊤X)=a⊤Σa\Var(\vb{a}\T\vb{X}) = \vb{a}\T\mat{\Sigma}\vb{a} for every a∈Rd\vb{a} \in \R^d. Also Σ\mat{\Sigma} is positive definite if and only if no nontrivial linear combination a⊤X\vb{a}\T\vb{X} is constant almost surely.
0
First calculate the variance of a⊤X\vb{a}\T\vb{X} in terms of Σ\mat{\Sigma}, then deduce positivity.

Step 1 of 3. How do you obtain symmetry and the variance formula for a linear combination?

ProofCorrelation lies between −1 and 1
Prove: If X,Y∈L2X, Y \in L^2 have positive variance, then ∣ρ(X,Y)∣≤1\abs{\rho(X, Y)} \le 1, and ∣ρ(X,Y)∣=1\abs{\rho(X, Y)} = 1 if and only if Y=aX+bY = aX + b almost surely with a≠0a \neq 0.
0
Apply the Cauchy–Schwarz inequality for inner product ⟨U,V⟩=E[UV]\inner{U}{V} = \E[UV] of L2L^2 to the centered variables.

Step 1 of 4. To which vectors in L2L^2 do you apply Cauchy–Schwarz?

NumericVariance of the mean of one hundred
One hundred random variables have variance 11 and correlation 0.10.1 between each pair. What is the variance of their mean?
NumericEffective sample size
You have n=50n = 50 observations with pairwise correlation ρ=0.2\rho = 0.2. How many independent observations are they worth, i.e. what is effective sample size nefn_{\mathrm{ef}}?
NumericVariance of a difference
Vector X=(X1,X2)⊤\vb{X} = (X_1, X_2)\T has covariance matrix Σ=[41.21.21]\mat{\Sigma} = \begin{bmatrix} 4 & 1.2 \\ 1.2 & 1 \end{bmatrix}. What is Var⁡(X1−X2)\Var(X_1 - X_2)?
NumericCorrelation between sum and difference
With the same Σ=[41.21.21]\mat{\Sigma} = \begin{bmatrix} 4 & 1.2 \\ 1.2 & 1 \end{bmatrix}, let S=X1+X2S = X_1 + X_2 and D=X1−X2D = X_1 - X_2. What is correlation ρ(S,D)\rho(S, D)?
NumericSampling without replacement
A finite population of N=50N = 50 values has population variance σ2=1\sigma^2 = 1 (divisor NN). Choose B=10B = 10 randomly without replacement and average them. What is the variance of the average?
NumericChebyshev at three standard deviations
A variable XX has mean 5050 and standard deviation 55, with unknown law. What bound does Chebyshev give for P(X≤35 o X≥65)\Pr(X \le 35 \text{ o } X \ge 65)?
QuizA normal parabola
Let X∼N(0,1)X \sim \Normal(0, 1) and Y=X2Y = X^2. Which statement is true?
QuizCan this family exist?
Can there be 1010 random variables with variance 11 and pairwise correlation ρ=−0.2\rho = -0.2 for every pair?
QuizWhere can Markov be applied?
Which applications of Markov's inequality are correct?

More than one answer may be correct.

CodeWelford for mean and covariance
Implement welford(X), receiving observations (one per row, any iterable of vectors, including a one-pass iterator) and returning (media, cov): mean of shape (d,) and covariance matrix (d, d) with divisor n - 1. Process one row at a time with Welford's recurrence (mean and matrix M\mat{M} of sums of centered products), without storing data or calculating E[XX⊤]−μμ⊤\E[\vb{X}\vb{X}\T] - \vb{\mu}\vb{\mu}\T, and always accumulate in float64 even for float32 input. It must work with mean 10810^8 data.
import numpy as np

def welford(X):
  """Devuelve (media, cov) de las filas de X, procesando una fila cada vez (X puede ser un iterador)."""
  n = 0
  media = None
  M = None
  for x in X:
      x = np.asarray(x, dtype=np.float64)
      if media is None:
          media = np.zeros_like(x)
          M = np.zeros((x.size, x.size))
      # tu código: actualiza n, media y M con la recurrencia de Welford
      pass
  # recuerda dividir M entre n - 1
  return media, M
Shift+Enter to run

Summary

Key idea
In L2L^2 covariance is an inner product and correlation a cosine: variance, covariance, covariance matrices, sums of variances and linear regression become lengths, angles and projections; correlation in data prevents averaging from reducing variance as 1/n1/n.
  • Variance Var⁡(X)=E[X2]−(E[X])2\Var(X) = \E[X^2] - (\E[X])^2 is the squared distance of XX to constants: irreducible error of the best constant predictor. Skewness and kurtosis are moments of orders 33 and 44 and need not exist.
  • Cov⁡(X,Y)=⟨X~,Y~⟩\Cov(X, Y) = \inner{\tilde{X}}{\tilde{Y}} and ρ=cos⁡θ∈[−1,1]\rho = \cos\theta \in [-1, 1], with ∣ρ∣=1\abs{\rho} = 1 only for exact affine dependence. ρ2\rho^2 is the fraction of variance explained by the best line.
  • A covariance matrix is symmetric positive semidefinite and transforms as AΣA⊤\mat{A}\mat{\Sigma}\mat{A}\T; variance in direction u\vb{u} is u⊤Σu\vb{u}\T\mat{\Sigma}\vb{u}, maximal and minimal along eigenvectors (a preview of PCA).
  • Var⁡(Xˉn)=σ2(ρ+(1−ρ)/n)\Var(\bar{X}_n) = \sigma^2(\rho + (1-\rho)/n) with pairwise correlation ρ\rho: the floor is ρσ2\rho\sigma^2 and effective size n/(1+(n−1)ρ)n/(1 + (n-1)\rho) cannot exceed 1/ρ1/\rho. Sampling without replacement corresponds to ρ=−1/(N−1)\rho = -1/(N-1).
  • Independence implies uncorrelatedness, not conversely: Pearson sees only the linear part. They are equivalent for a jointly Gaussian law, but not for normal marginals alone.
  • Markov (X≥0X \ge 0): P(X≥a)≤E[X]/a\Pr(X \ge a) \le \E[X]/a. Chebyshev: P(∣X−μ∣≥kσ)≤1/k2\Pr(\abs{X - \mu} \ge k\sigma) \le 1/k^2, sharp for a three-atom law but very conservative for nearly all real laws.
  • Compute moments using Welford (one pass, stable, mergeable), not E[X2]−E[X]2\E[X^2] - \E[X]^2, which destroys variance in floating point when the mean is large.