Sub topic 2
Variance, covariance and the covariance matrix
PCA is built from one object: the covariance matrix of your features. This chapter defines it, shows how to compute it, and explains what each entry means. Later chapters take its eigenvectors to get principal components.
This chapter assumes you can use NumPy arrays and matrix multiplication. It also assumes you know the mean and variance of one variable, and that a feature matrix has samples as rows and features as columns.
Variance: spread of one feature
Variance measures how far the values of one feature lie from its mean. For a feature with values x₁, …, xₙ and mean x̄, the sample variance is:
var(x) = (1 / (n - 1)) * sum((xᵢ - x̄)²)Two details matter in practice:
- Deviations are squared, so values above and below the mean both add to the variance.
- The divisor is n - 1 for the sample variance (Bessel's correction). The mean was estimated from the same data, which makes the raw average of squared deviations slightly too small. NumPy's
np.vardivides by n unless you passddof=1.np.covdivides by n - 1 by default.
The units of variance are the squared units of the feature. A feature in metres has variance in square metres. This becomes important in the next chapter.
Covariance: how two features vary together
Covariance measures whether two features move together:
cov(x, y) = (1 / (n - 1)) * sum((xᵢ - x̄)(yᵢ - ȳ))Each term multiplies the two deviations from the mean for one sample.
- If x and y tend to be above their means at the same time, the products are mostly positive, and the covariance is positive.
- If one tends to be high when the other is low, the products are mostly negative, and the covariance is negative.
- If there is no linear relationship, positive and negative products cancel, and the covariance is near zero.
The covariance of a feature with itself is its variance, so variance is a special case of covariance.
The magnitude of a covariance is hard to read on its own. It depends on the scales of both features. A covariance of 8.7 might be a strong relationship or a weak one. Dividing by both standard deviations gives the correlation, which always lies between -1 and 1:
corr(x, y) = cov(x, y) / (std(x) * std(y))Covariance and correlation capture only linear co-movement. Two features can have a strong curved relationship, such as y = x² for x symmetric around zero, and still have zero covariance.
The covariance matrix
With d features, there are d variances and d(d - 1)/2 distinct pairwise covariances. The covariance matrix C collects all of them in a d × d table. Entry C[i, j] is the covariance between feature i and feature j.
| Position | Contains | Meaning |
|---|---|---|
| Diagonal, C[i, i] | var(feature i) | Spread of one feature |
| Off-diagonal, C[i, j] | cov(feature i, feature j) | Linear co-movement of two features |
If you center the data first, the whole matrix is one matrix product. Let X be the n × d feature matrix and let Xc be X with each column's mean subtracted. Then:
C = Xc.T @ Xc / (n - 1)Entry (i, j) of Xc.T @ Xc is the dot product of centered column i with centered column j. That is the sum of products in the covariance formula.
A worked example
Take four samples with two features. The second feature grows roughly with the first.
import numpy as np
X = np.array([[2.0, 1.0],
[4.0, 3.0],
[6.0, 5.0],
[8.0, 9.0]])
n = X.shape[0]
Xc = X - X.mean(axis=0)
C_manual = Xc.T @ Xc / (n - 1)
C_numpy = np.cov(X, rowvar=False)
print(C_manual)
print(np.allclose(C_manual, C_numpy))
std = np.sqrt(np.diag(C_manual))
corr = C_manual / np.outer(std, std)
print(corr)
print(np.allclose(corr, np.corrcoef(X, rowvar=False)))The column means are 5 and 4.5. Working through the sums by hand gives var(feature 0) = 20/3 ≈ 6.67, var(feature 1) = 35/3 ≈ 11.67 and covariance 26/3 ≈ 8.67. The correlation is 26 / √700 ≈ 0.983. Both allclose checks print True.
Properties you will rely on
The covariance matrix has three properties that PCA depends on.
- It is symmetric. C[i, j] = C[j, i], because cov(x, y) = cov(y, x). Symmetric real matrices have real eigenvalues and orthogonal eigenvectors. This is why
np.linalg.eighis the right solver in later chapters. - It is positive semi-definite. For any vector w, the quantity wᵀ C w is never negative. The next section shows why. All eigenvalues of C are therefore zero or positive.
- Its trace is the total variance. The sum of the diagonal entries is the sum of the individual feature variances. It is also the sum of the eigenvalues of C. PCA redistributes this total variance across new axes and does not change it.
For the example, the trace is 20/3 + 35/3 = 55/3 ≈ 18.33.
Variance along any direction
PCA looks for directions in feature space along which the data varies most. Covariance gives the variance along any direction without recomputing from the raw data.
Let w be a unit vector, so its length is 1. Projecting each centered sample onto w gives the scalar Xc @ w. The variance of those scalars is:
var(Xc @ w) = wᵀ C wThis follows from the matrix form of C. Expanding gives (Xc w)ᵀ(Xc w) / (n - 1), which is the sum of squared projections divided by n - 1. A sum of squares cannot be negative, which proves the positive semi-definite property.
You can check this numerically.
import numpy as np
X = np.array([[2.0, 1.0],
[4.0, 3.0],
[6.0, 5.0],
[8.0, 9.0]])
Xc = X - X.mean(axis=0)
C = np.cov(X, rowvar=False)
w = np.array([1.0, 1.0]) / np.sqrt(2.0)
projected = Xc @ w
print(w @ C @ w)
print(np.var(projected, ddof=1))
print(np.trace(C))The first two lines print the same value, 107/6 ≈ 17.83. The two features are positively correlated, so the diagonal direction captures most of the total variance of 18.33. Only about 0.5 is left for the perpendicular direction.
Reading C therefore tells you where variance sits. The diagonal gives variance along the original axes. The quadratic form wᵀ C w gives it along any other direction. PCA finds the w that makes this quantity as large as possible.
Common errors
- Forgetting to center. The formula
Xc.T @ Xc / (n - 1)is a covariance matrix only if the column means are zero. On uncentered data,X.T @ X / (n - 1)mixes the means into the entries.np.covcenters for you, but hand-written code must do it explicitly. - Wrong orientation. See the
rowvarwarning above. A transposed feature matrix is the most common source of shape errors in PCA code. - Mixing divisors.
np.vardefaults toddof=0, andnp.coveffectively usesddof=1. Comparing the two without matching them gives results that differ by a factor of (n - 1)/n. For large n the difference is small, but it breaks exactallclosechecks. - Reading covariance magnitude as strength. A covariance of 1000 between features measured in millimetres may be weaker than a covariance of 0.5 between features measured in metres. Use correlation to compare strength.
- Assuming zero covariance means independence. It means only no linear relationship.
- Too few samples. With n samples, the centered data has rank at most n - 1. If d is larger than n, C is singular, with at least d - n + 1 zero eigenvalues. This is common with genomic or image data, and later chapters return to it.
What comes next
The diagonal of C mixes features with different units and scales. A feature measured in large numbers dominates the total variance regardless of how informative it is. The next chapter covers centering and standardizing, which control this before PCA takes the eigenvectors of C.
Exercise
A data matrix has 100 samples and 5 features, stored with samples as rows. What call computes the covariance matrix, what shape does it have, and how many distinct entries does it contain?
Show answer
Use np.cov(X, rowvar=False). The result is 5 × 5. Because the matrix is symmetric, it has 5 × 6 / 2 = 15 distinct entries: 5 variances on the diagonal and 10 covariances above it. Calling np.cov(X) without rowvar=False would return a 100 × 100 matrix.
Exercise
Feature A is a length measured in metres and has variance 4. You re-express it in centimetres and compute its variance again. What is the new variance, and what happens to its covariance with another feature B that you leave unchanged?
Show answer
Multiplying a feature by 100 multiplies its variance by 100², so the new variance is 40,000. The covariance with B is multiplied by 100. The correlation with B does not change, because the factor cancels when you divide by the standard deviations.