Sub topic 4
Eigenvectors and Eigenvalues in Brief
This chapter assumes you can multiply a matrix by a vector, know what the covariance matrix of a dataset is, and can read basic NumPy. You don't need to know how to compute eigenvalues by hand. PCA needs only the meaning of eigenvectors and eigenvalues and a reliable way to get them from NumPy.
What an eigenvector is
A matrix A acts on a vector v by moving it: it can rotate it, stretch it, or both. An eigenvector of A is a nonzero vector that the matrix only stretches or flips, without changing its line. The stretch factor is the eigenvalue:
A v = λ vHere v is the eigenvector and λ (lambda) is a number. If λ = 3, the matrix triples v. If λ = -1, it flips v to the opposite direction. If λ = 0, it collapses v to zero.
Any multiple of an eigenvector is also an eigenvector with the same eigenvalue. So v and -v describe the same direction. By convention, libraries return eigenvectors with length 1.
Why covariance matrices are well behaved
Eigenvectors of a general matrix can be awkward. They can be complex numbers, and they need not be perpendicular. A covariance matrix Σ avoids these problems because it has two properties:
- It is symmetric:
Σ[i, j] = Σ[j, i], since the covariance of featureiwith featurejequals the covariance ofjwithi. - It is positive semi-definite: the variance of any weighted sum of the features is never negative.
For such matrices, the spectral theorem guarantees the following:
- All eigenvalues are real and are greater than or equal to zero.
- Eigenvectors that belong to different eigenvalues are perpendicular.
- You can pick a full set of
dperpendicular unit eigenvectors for ad × dmatrix.
Stacking those eigenvectors as the columns of V and the eigenvalues on the diagonal of Λ gives the decomposition:
Σ = V Λ VᵀBecause V has perpendicular unit columns, VᵀV = I. In other words, V is a rotation, possibly with a reflection. The decomposition says that Σ rotates into a new coordinate system, stretches each axis independently by its eigenvalue, and rotates back. In that new coordinate system the features are uncorrelated. This is what PCA uses.
A worked 2×2 example
Take the covariance matrix:
Σ = [[2, 1],
[1, 2]]Try v = (1, 1). Then Σv = (2+1, 1+2) = (3, 3) = 3·v, so (1, 1) is an eigenvector with eigenvalue 3. Try w = (1, -1). Then Σw = (2-1, 1-2) = (1, -1) = 1·w, so (1, -1) is an eigenvector with eigenvalue 1. The two directions are perpendicular, as the theorem promised.
Now check it in NumPy:
import numpy as np
S = np.array([[2.0, 1.0],
[1.0, 2.0]])
eigvals, eigvecs = np.linalg.eigh(S)
print(eigvals) # approximately [1. 3.]
for lam, v in zip(eigvals, eigvecs.T):
print(lam, np.allclose(S @ v, lam * v))
print(np.allclose(eigvecs.T @ eigvecs, np.eye(2)))
print(np.allclose(eigvecs @ np.diag(eigvals) @ eigvecs.T, S))The loop iterates over eigvecs.T because the eigenvectors are the columns of eigvecs, not its rows. The last two lines confirm that V has perpendicular unit columns and that V Λ Vᵀ rebuilds Σ.
Why eigenvalues are variances
Pick any unit vector u and project centered data onto it. The variance of the projected values is:
Var(Xc u) = uᵀ Σ uNow suppose u is an eigenvector of Σ with eigenvalue λ. Then uᵀΣu = uᵀ(λu) = λ(uᵀu) = λ. So the variance of the data along an eigenvector equals its eigenvalue.
This also explains why the top eigenvector is the direction of maximum variance. Write any unit vector in the eigenbasis as u = c₁v₁ + c₂v₂ + ... + c_d v_d, where c₁² + ... + c_d² = 1. Because the eigenvectors are perpendicular, uᵀΣu = λ₁c₁² + ... + λ_d c_d². This is a weighted average of the eigenvalues, with weights that sum to 1. A weighted average can't exceed the largest value, and it reaches it only when all the weight sits on the largest eigenvalue. The best direction is therefore the eigenvector with the largest eigenvalue. The next chapter builds the principal components on this fact.
The following code checks it on random data:
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 2)) @ np.array([[2.0, 1.0],
[0.0, 1.0]])
Xc = X - X.mean(axis=0)
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
for lam, v in zip(eigvals, eigvecs.T):
projected = Xc @ v
print(lam, projected.var(ddof=1))
print(np.trace(cov), eigvals.sum())Each pair of printed numbers matches. The last line shows a second useful fact: the eigenvalues sum to the trace of the covariance matrix, which is the total variance of all features. PCA splits that total among the new axes, and later chapters use this split to define explained variance.
The pipeline from data to eigenpairs
Choosing the right NumPy function
NumPy has two common eigensolvers, and for covariance matrices you should use eigh.
| Function | Assumes | Returns | Order of eigenvalues |
|---|---|---|---|
| `np.linalg.eigh` | Symmetric (or Hermitian) matrix | Real eigenvalues, perpendicular eigenvectors | Ascending |
| `np.linalg.eig` | Any square matrix | Possibly complex eigenvalues, not necessarily perpendicular eigenvectors | No guaranteed order |
eigh reads only one triangle of the matrix, runs a faster algorithm, and guarantees real output. eig would also work on a covariance matrix, but it can return tiny imaginary parts from rounding and gives no ordering guarantee.
Gotchas
Ascending order
eigh returns eigenvalues from smallest to largest. PCA wants the largest first, so sort in descending order and reorder the eigenvector columns with the same index:
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]Sorting only the eigenvalues, and not the columns, silently pairs values with the wrong directions.
Sign ambiguity
Both v and -v are valid unit eigenvectors, and the solver picks one arbitrarily. Two runs on different machines, or two library versions, may return flipped signs. Never write code or tests that depend on the sign of a component. Compare results up to sign, for example by comparing the absolute values of the entries.
Repeated eigenvalues
If two eigenvalues are equal, any perpendicular pair of directions in their shared plane is a valid set of eigenvectors. The identity matrix is the extreme case: every vector is an eigenvector with eigenvalue 1. In PCA this means the data has the same spread in several directions. Those directions are not uniquely defined, so don't interpret them individually.
Tiny negative eigenvalues
In exact arithmetic a covariance matrix has no negative eigenvalues. In floating-point arithmetic, a rank-deficient matrix can produce values such as -3e-17. This happens when one feature is an exact combination of others:
import numpy as np
rng = np.random.default_rng(1)
a = rng.normal(size=(100, 2))
X = np.column_stack([a[:, 0], a[:, 1], a[:, 0] + a[:, 1]])
cov = np.cov(X, rowvar=False)
print(np.linalg.eigvalsh(cov))The smallest value printed is zero up to rounding, and it may be slightly negative. The data has three columns but only two independent directions, so the third eigenvalue is zero. If you take a square root of the eigenvalues, for instance to compute standard deviations, first clip them with np.clip(eigvals, 0, None).
What carries forward
- An eigenvector keeps its direction under the matrix, and its eigenvalue is the stretch factor.
- A covariance matrix is symmetric and positive semi-definite, so its eigenvalues are real and nonnegative, and its eigenvectors are perpendicular.
- The variance of the data along a unit eigenvector equals the eigenvalue, and the eigenvalues sum to the total variance.
- Use
eigh, sort in descending order with the columns reordered to match, and treat signs and tiny negative values as noise.
Exercise
The covariance matrix of two features is [[4, 0], [0, 1]]. Without running code, give its eigenvalues and eigenvectors, and say what fraction of the total variance lies along the first eigenvector.
Show answer
The matrix is diagonal, so the coordinate axes are already its eigenvectors. The eigenvector (1, 0) has eigenvalue 4, and (0, 1) has eigenvalue 1. The total variance is the trace, 4 + 1 = 5, so the first eigenvector carries 4/5 = 80% of the variance.
Exercise
You call np.linalg.eigh on a covariance matrix and take eigvecs[:, -1]. What does this vector represent, and why is it the last column rather than the first?
Show answer
It is the unit eigenvector with the largest eigenvalue, which is the direction of maximum variance in the data. eigh returns eigenvalues in ascending order, and the columns of eigvecs follow the same order, so the largest eigenvalue and its eigenvector come last.
Exercise
Two colleagues run PCA on the same data. Their first eigenvectors are (0.6, 0.8) and (-0.6, -0.8). Is one of them wrong?
Show answer
Neither is wrong. An eigenvector and its negative span the same direction and have the same eigenvalue, and solvers choose the sign arbitrarily. The scores from the two runs will differ only by a sign flip.