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 examples, 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 are independent with covariance , their average has covariance : doubling the batch halves the noise. True, but no longer true as soon as examples resemble one another. With variables of variance and pairwise correlation only (for example, augmented copies of the same images or overlapping windows of the same text), variance of the average is not but : eleven times larger. And however much grows, it never falls below .
This lesson collects the tools to reason about such effects, all based on second-order moments:
- Variance and moments. What variance measures (distance to the best constant predictor), what skewness and kurtosis add, and when a moment ceases to exist.
- Covariance and correlation as geometry. In , covariance is an inner product and correlation a cosine. Everything that follows is geometry of angles and lengths.
- The covariance matrix as a quadratic form: its behavior under linear maps and variance in each direction.
- Variance of sums and averages, its correlation floor, and effective sample size.
- Uncorrelatedness versus independence, and what Pearson correlation misses.
- Markov and Chebyshev, the first tail bounds and why they cannot be improved without more assumptions.
- Stable computation of moments in one pass (Welford), because the classroom formula fails in floating point.
Variance and moments
Work on a probability space . Variance requires more than integrability: the variable must lie in , meaning (spaces and their structure appear in the lesson on the integral and spaces). Every lies in because by Cauchy–Schwarz, so makes sense.
Proof
(1) Expand and take expectations, using linearity: . Variance is the expectation of a nonnegative variable and thus nonnegative; a nonnegative variable has zero expectation only if zero almost surely: almost surely. (2) ; square and take expectations. (3) Add and subtract : . The cross term has expectation .
∎Part (3) gives variance its operational meaning. If you must summarize by one number and are penalized by squared error, expected error is : the best choice is and unavoidable error is exactly . This is why regression’s coefficient of determination is : 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 , 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 ), skewness is positive when the long tail is on the right and negative when it is on the left, and is for every symmetric law with finite third moment. Kurtosis is the expectation of with standardized . Since grows rapidly, a single distant value contributes greatly, making kurtosis primarily a measure of tail weight, not the peak of the bell.
| Law | Variance | Skewness | Kurtosis |
|---|---|---|---|
| Uniform on | |||
| Laplace (double exponential) with scale | |||
| Exponential with rate | |||
| Student , degrees of freedom | |||
| Student , degrees of freedom | does not exist |
The last rows illustrate an important fact: a moment may not exist. The Cauchy law has no mean because ; a Pareto law with index has finite moment of order if and only if ; Student with degrees of freedom has variance but infinite fourth moment. Moments are nested: if and , then , because for every real number. Finite variance therefore implies a finite mean, but not conversely: Student with degrees of freedom has mean and infinite variance. Two practical consequences: sample variance’s variance involves the fourth moment, so for heavy-tailed data like 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 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 are independent, the joint law of is the product measure . By Tonelli, , so Fubini permits calculating , and covariance is .
∎Variables with 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 (), 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 as a geometric space. Equivalence classes of random variables in (identifying those equal almost surely) form a Hilbert space with inner product
This is the exact analogue of the inner product on , with expectation replacing summation. Constant has norm and , so is orthogonal projection onto constants, and centering a variable, , projects onto the orthogonal complement of constants. The lesson’s three definitions become:
Variance is the squared distance of 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 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 and as sides of a triangle, the cosine law is the variance formula for a sum:
Uncorrelated variables are orthogonal, and their variances add by Pythagoras. Linear regression is a projection: the best affine predictor of from is the projection of onto the plane generated by and .
Proof
Let with that . Residual is orthogonal to : , and to constants too, because it has zero mean. For any other affine function , , where the first term is orthogonal to the plane generated by and , which contains the second. By Pythagoras . Finally .
∎Thus is the fraction of variance of explained by the best line, and is the unexplained fraction. In trigonometry, versus .
Data have the same geometry
None of this requires abstract variables. If you have observations , the empirical measure (mass on each observation) is a law on , and is simply . Centered variables are vectors and in hyperplane , and the sample correlation coefficient is the cosine of their angle:
Two nonparallel vectors span a plane, so the angle can be drawn even for large . With , the hyperplane of centered vectors is already a plane, and the one spanned by and is the whole plane.
Three readings of the figure. First, depends only on angle: stretching or shrinking a vector (changing a variable’s scale) does not move it. Second, the regression line of on is the projection of onto , with error the remaining leg of length . Third, the outlier illustrates how fragile a cosine becomes when one vector is dominated by one coordinate: six points with correlation become after adding a distant seventh point.
The covariance matrix
For a random vector with every component in (the joint law makes cross-covariances meaningful), there are variances and 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: for constant matrices . The centered variable of is , and hence . Symmetry is that of . Positive semidefiniteness of and the characterization of positive definiteness follow by applying the formula with and noting variance is always and equals only for a constant: the first proof exercise.
∎Positive semidefiniteness makes everything meaningful: defines quadratic form (quadratic form), which is projection variance along . Every symmetric positive semidefinite matrix is a covariance matrix: if has covariance (for example, independent components of variance ) and , then has covariance . 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 with and orthonormal eigenvectors (spectral theorem). For a unit vector ,
This is a weighted average of eigenvalues, with weights from the angle to each axis. Thus , with equality at the extreme eigenvectors. In the plane, with and major axis at angle ,
an oscillation of period between and . The set is the covariance ellipse (the unit circle’s image under ), and its shadow on the line of has half-width exactly .
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 does not change as axes rotate, and fraction is what the first component explains. Rotating into the eigenvector basis, , gives through formula a diagonal covariance : uncorrelated coordinates. Additional scaling by yields covariance , 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 to , separating the diagonal. The matrix form is the case of the previous theorem.
∎The most important statistical case is the average. Suppose variables have common variance and common pairwise correlation . Then , and dividing by ,
With this recovers . But with the second term, divided by , vanishes as grows, leaving a floor: . With the opening values (, , ), .
A useful measure asks how many independent observations your correlated observations are worth. The effective sample size is the yielding the same variance under independence, :
The earlier observations are worth independent ones, and no amount of data with is worth more than . The cause is structural. For , the model with independent of variance has exactly that covariance, and its average is : the idiosyncratic part averages away, but the common factor appears in full in every variable and never averages away. The same calculation limits portfolio diversification: equal capital across assets with volatility and correlation gives return variance , eliminating each asset’s individual risk but never falling below common market risk .
Correlation may also be negative, within limits. Since mean variance cannot be negative, , that is ; with variables there is no way for every pair to have correlation . This is exactly the condition for equicorrelation matrix , with eigenvalues and , to be positive semidefinite. The limiting case occurs in a concrete setting: sampling without replacement elements from a finite population of values with population variance gives variables with pairwise correlation , so
The second factor is the finite-population correction: with and , variance is lower than a batch sampled with replacement ( versus ), and with equals because the whole population has been averaged.
In time series, correlations decay with distance instead of being equal. For a stationary process with correlation at lag , tends to (the long-run variance) when that sum converges. For a first-order autoregression , the sum is and : with , every observations are worth approximately one. This is covered in the time-series lesson and explains why MCMC confidence intervals use , not .
The proof is one line. Expanding the square gives ; taking expectations gives . Bessel’s divisor 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 has a law symmetric around with and is an even function with , then because is odd. Other examples with this pattern: a uniform point on the unit circle, , has yet ; and if is independent of , then is also , uncorrelated with and . 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 and each take only two values, uncorrelatedness is equivalent to independence too (check with indicators: ). But these are special cases; generally orthogonality says nothing about independence.
The underlying reason is geometric. Correlation is the cosine of the angle between and in , whereas independence is a condition on all functions: for every pair of bounded functions. Pearson sees only and . Thus is the variance fraction explained by the best line, and nonlinear dependence can pass unnoticed.
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 ). The widget therefore compares distance correlation with its value after shuffling , 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 , holds pointwise: if , the left side is , and if it is . Taking expectations gives . Equality requires almost surely, that is, when and when .
∎The assumption bears repeating because it is forgotten: . With it, the inequality says a nonnegative response time averaging ms exceeds s with probability at most , without further information. Applied to with nondecreasing and it gives , where may now be negative. With in , applied to , we obtain Chebyshev; with , the Chernoff method (later) gives exponential tails.
Proof
Apply Markov to with : . To see sharpness, take and the law with each and . Its variance is and exactly.
∎For the bound is or more and says nothing. For it gives and for , without any shape assumption. This universality is both strength and weakness: the three-point law shows no improvement is possible using only and , but few real laws resemble it. For a normal variable, probability beyond is (the bound overstates it by ) and beyond it is (by ). For an exponential at from the mean, . The true tail depends on information Chebyshev ignores, while the Hoeffding and sub-Gaussian lesson uses it for exponential tails.
Two applications recur later. First, the weak law of large numbers: for independent with variance , Chebyshev gives at an explicit rate (see the weak law lesson). With correlation the same argument gives , which does not tend to : the previous section’s floor also limits concentration. Second, the second-moment method: for a count with , event is contained in , so . If variance is small relative to squared mean, 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 . 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 , , the value of is , and float64 relative rounding of gives absolute error of order : the entire variance. It can even become negative. With float32, which has mantissa bits, a mean of suffices.
Welford’s algorithm (1962) maintains mean and centered sum of squares , updating one observation at a time without subtracting large numbers.
Stability appears in the result. Factors and have the same sign, so every increment of is nonnegative: no large quantity is subtracted from another. The only subtraction is , 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 with , which also keeps symmetric positive semidefinite by construction, and . An important consequence: two data groups with and can be merged without revisiting the data (Chan, Golub and LeVeque, 1983):
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 applied to data.
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 , and is the sample covariance of (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.
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 : at correlation data appear 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.
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 , gives instead of with , and a negative variance with , while Welford agrees with the reference in every row. In float32 the problem arrives much earlier: already noticeable at mean , with the classroom formula returns (a negative variance) and with , ; float32 Welford preserves the result to that point with error of order . (The data themselves lose resolution as the mean grows: with and float32, the gap between representable numbers is , so the reference already reflects rounded data.) The vector version remains, with matrix recurrence and Chan merger checked against np.cov.
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 ), and can return matrices not even positive semidefinite. Welford’s error is and preserves structure: all eigenvalues are positive. Finally compare Markov and Chebyshev with reality by simulating four laws with known mean and variance.
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 , is the only one reaching at (and at it also gives , because its atoms lie beyond and bound is not sharp there); the rest lie well below, especially the normal. At the heavier-tailed exponential and come closest, yet the bound is about ten times reality.
The professional version
| Task | NumPy | PyTorch |
|---|---|---|
| Sample variance (divisor ) | np.var(x, ddof=1) | torch.var(x) (default correction ) |
| Population variance (divisor ) | np.var(x) (default) | torch.var(x, correction=0) |
| Covariance matrix | np.cov(X, rowvar=False) (rows = observations) | torch.cov(X.T) (variables in rows) |
| Correlation | np.corrcoef(X, rowvar=False) | torch.corrcoef(X.T) |
| Skewness and kurtosis | scipy.stats.skew, scipy.stats.kurtosis | by hand |
The most common confusion is conventions. np.cov expects variables in rows by default (rowvar=True), opposite to Oryon Learn’s design matrix , and uses divisor ; np.var uses . scipy.stats.kurtosis returns excess by default (subtracts ). And torch.var has always corrected using , but the current API expresses this with correction, not unbiased.
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 in the forward pass (in PyTorch the running variance instead uses divisor ). This is an engineering choice, not an unbiased estimate, and matters when comparing implementations.
Common mistakes
Exercises
Step 1 of 3. How do you obtain symmetry and the variance formula for a linear combination?
Step 1 of 4. To which vectors in do you apply Cauchy–Schwarz?
More than one answer may be correct.
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 of sums of centered products), without storing data or calculating , and always accumulate in float64 even for float32 input. It must work with mean 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, MSummary
- Variance is the squared distance of to constants: irreducible error of the best constant predictor. Skewness and kurtosis are moments of orders and and need not exist.
- and , with only for exact affine dependence. is the fraction of variance explained by the best line.
- A covariance matrix is symmetric positive semidefinite and transforms as ; variance in direction is , maximal and minimal along eigenvectors (a preview of PCA).
- with pairwise correlation : the floor is and effective size cannot exceed . Sampling without replacement corresponds to .
- 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 (): . Chebyshev: , sharp for a three-atom law but very conservative for nearly all real laws.
- Compute moments using Welford (one pass, stable, mergeable), not , which destroys variance in floating point when the mean is large.