21.3 Eigendecompositions
In Section 21.2 we asked what a matrix does to space when it is applied once. Many computations in machine learning, however, apply the same matrix over and over. A deep linear network with identical layers computes after 50 layers, and gradient descent on a quadratic objective multiplies its error by the same fixed matrix at every step. In each case we want to know whether the signal grows, dies out, or settles down, and how quickly that happens. Multiplying out the matrix powers gives us the numbers, but it does not explain them.
A random walk between two web pages is the smallest version of this question. Suppose a surfer on page 1 stays on page 1 or clicks to page 2 with probability each; from page 2 she stays with probability and returns to page 1 with probability . Let hold the probabilities of being on each page after clicks. Each click multiplies this vector by a fixed matrix,
whose columns record the click probabilities from each page and therefore sum to one. Starting on page 1 with , the first few distributions are , , , and . The changes shrink with every click, as if the walk were settling onto a fixed distribution. Where is the surfer after 50 clicks, and how fast does the distribution converge? PageRank asks the very same question of the entire web.
The key is to rewrite the starting vector in the coordinates of a few special directions, the eigenvectors, along which the matrix acts simply as multiplication by a number. In those coordinates, each component evolves on its own as a scalar power .
In Section 1.3 we already met eigenvectors as the directions that a matrix only stretches: the symmetric matrix stretches by 3 and by 1, and for any symmetric matrix we had . Here we drop the symmetry requirement. We learn how to find the eigenvalues of an arbitrary square matrix, see when a full set of eigenvectors exists and what replaces it when one does not, and then prove why symmetry guarantees so much more.
Three results carry the most weight: the eigenvector expansion
(21.3.4) of , the spectral
theorem, and the quadratic form written as a weighted sum of squares,
(21.3.12). A reader in a hurry can jump from
Section 21.3.1.3 straight to
Section 21.3.2.1. We leave two practical questions to
Section 21.4: how to locate and compute eigenvalues
when a matrix is large, and the situations in which eigenvalues can mislead us.
Throughout this section we compute with NumPy, whose eig function returns
complex eigenvalues whenever a real matrix has them.
import numpy as np21.3.1 Eigenvalues and Diagonalization#
21.3.1.1 Eigenvectors and Eigenvalues#
Certain input vectors are only rescaled by , as though the matrix were a single number. Applying to gives , leaving it completely unchanged, while applying to gives . Along the first direction multiplies by ; along the second it multiplies by .
In general, a nonzero vector is called an eigenvector of a square matrix , with corresponding eigenvalue , if
In geometric terms, only stretches an eigenvector by the factor , reversing its direction when . For the surfer's matrix , the eigenpairs are and . We exclude the zero vector from being an eigenvector because it trivially satisfies (21.3.1) for every . However, all solutions of for a fixed , together with , form a linear subspace called the eigenspace of .
The eigenvalue , on the other hand, is perfectly valid. It means that for some nonzero , so a square matrix is singular if and only if is one of its eigenvalues. Notice also that a real matrix need not have any real eigenvectors: a rotation by turns every nonzero direction in the plane. Its eigenvalues turn out to be complex, a case we take up in Section 21.3.1.6.
It is tempting to confuse eigenvectors with the axes of the ellipse produced when an invertible matrix acts on the unit circle. Figure 21.3.1 shows why the two concepts are distinct. For the symmetric matrix , the eigenvectors do lie along the ellipse axes. For the upper-triangular matrix , however, they do not: its eigenvectors are with and with , whereas the ellipse axes point at and (Section 21.5 shows how to compute them). The ellipse axes mark the directions of largest and smallest stretch, while the eigenvectors mark the directions that are not rotated at all. For symmetric matrices these two sets of directions always coincide, as the spectral theorem of Section 21.3.2.1 proves; for general matrices they need not.
The unit circle (dashed) and its image (blue). Left: for the symmetric matrix , the unit eigenvectors (green) lie along the ellipse axes, and their images (red) are scaled by 3 and 1 (for the two arrows coincide). Right: for the upper-triangular matrix , the eigenvectors and do not align with the ellipse axes (grey).
21.3.1.2 The Characteristic Polynomial#
We spotted the eigenvectors of by inspection, which does not take us far on larger matrices. To find the eigenvalues of any square matrix systematically, move to the left-hand side of (21.3.1) and factor out :
A nonzero solution exists if and only if has a nontrivial null space—that is, if and only if it is singular, so that . Expanding this determinant yields a polynomial of degree in , called the characteristic polynomial . Its roots are precisely the eigenvalues of . Once a root is known, solving the homogeneous linear system (21.3.2) gives its eigenspace.
Let us run this recipe on the surfer's matrix:
The roots are and , matching the two scaling factors we noticed earlier. Because is singular at each root, a single row suffices to find the eigenvector. For , the first row of gives , so and we may choose . For , the first row of gives , yielding . Keep in mind that every eigenvector is determined only up to a nonzero scalar factor: if is an eigenvector, then so is for any , since both sides of (21.3.1) scale by .
In practice we leave this algebra to a numerical library. NumPy's eig
returns the eigenvalues together with a matrix whose columns are the
corresponding eigenvectors; the last line below checks
(21.3.1) for all pairs at once.
P = np.array([[0.5, 0.25], [0.5, 0.75]])
lam, V = np.linalg.eig(P)
print('eigenvalues:', lam)
print('eigenvectors (columns):\n', V)
print('max |P V - V diag(lam)|:', np.abs(P @ V - V * lam).max())
eigenvalues: [0.25 1. ]
eigenvectors (columns):
[[-0.70710678 -0.4472136 ]
[ 0.70710678 -0.89442719]]
max |P V - V diag(lam)|: 0.0
Order, scale, and sign are all at the library's discretion: here eig returns
the eigenvalues as and , and the columns are unit-length vectors
parallel to and .
Numerical libraries do not actually form and solve the characteristic
polynomial. For there is no general closed-form formula for polynomial
roots in radicals, and even for moderate the roots are notoriously
sensitive to tiny rounding errors in the polynomial coefficients. Instead,
eig applies a sequence of orthogonal changes of basis that gradually drive
the matrix into triangular form without altering its eigenvalues. A triangular
matrix displays its eigenvalues right on its diagonal: subtracting
keeps it triangular, and the determinant of a triangular
matrix is simply the product of its diagonal entries
(Section 21.2.3.2). For matrices far too large to
factor at all, power iteration (Section 21.4.1.2) extracts
dominant eigenvalues using only matrix--vector products.
21.3.1.3 Diagonalization#
We can now answer our opening question about . Collect the two eigenvectors of as the columns of a matrix , and place their eigenvalues on the diagonal of :
Written side by side as columns, the two eigenvector equations compactly read . Because , the matrix is invertible, with . Multiplying on the right by yields
Read this factorization from right to left as three steps: change to eigenvector coordinates (), scale each coordinate independently by its eigenvalue (), and change back to the original coordinates (). A square matrix that can be written as , with invertible and diagonal, is called diagonalizable, and the factorization itself is its eigendecomposition. Such a factorization exists if and only if has linearly independent eigenvectors to fill the columns of .
Taking powers of a diagonalizable matrix now becomes effortless. In a product of copies of , every adjacent pair cancels out:
Powers of a diagonalizable matrix thus reduce to powers of scalars. Applying to a vector , and writing for the coordinates of in the eigenbasis (so that ), we obtain
Each eigen-coordinate evolves independently as the geometric sequence . For the surfer starting on page 1, , which gives the closed-form distribution after any number of clicks :
This completely settles the opening question. As grows, the second term vanishes and the distribution approaches : in the long run, the surfer spends twice as much time on page 2 as on page 1. The remaining error is in each entry and always points along the eigenvector . Every click divides that error by , so after 10 clicks it has dropped to , and after 50 clicks it is below . As a sanity check, setting gives , matching the third iterate we computed at the start. Figure 21.3.2 illustrates the geometry: because the entries of every sum to one, the iterates slide along the line toward the point where the eigenvector of intersects it.
The surfer's distributions slide along toward , where the eigenvector of meets the line. The error points along the eigenvector of and shrinks by a factor of 4 per click.
Let us verify that fifty matrix multiplications and the two-term eigen-expansion produce the same , and check the ratio of consecutive errors.
p0 = np.array([1.0, 0.0])
c = np.linalg.solve(V, p0) # coordinates of p0 in the eigenbasis
print('P^50 p0 :', np.linalg.matrix_power(P, 50) @ p0)
print('sum c_i lam_i^50 v_i:', V @ (c * lam ** 50))
pi = np.array([1 / 3, 2 / 3])
errs = np.array([np.abs(np.linalg.matrix_power(P, k) @ p0 - pi).max()
for k in range(8)])
print('error ratios:', np.round(errs[1:] / errs[:-1], 4))
P^50 p0 : [0.33333333 0.66666667]
sum c_i lam_i^50 v_i: [0.33333333 0.66666667]
error ratios: [0.25 0.25 0.25 0.25 0.25 0.25 0.25]
The two computations agree, and every consecutive error ratio is . The eigenvalue governs the part of that survives, while the eigenvalue governs the part that dies out.
The same recipe applies to other functions of a diagonalizable matrix. When no eigenvalue is zero, : simply invert each eigenvalue on the diagonal. Similarly, the matrix exponential , which solves the linear differential equation , is built by exponentiating each eigenvalue; Section 26.1 develops it in detail.
Similarity. The eigendecomposition tells us that and represent the very same linear map written in two different bases. In general, two matrices related by for some invertible are called similar. The next proposition confirms that changing basis cannot alter a matrix's eigenvalues. It relies on the multiplicativity of the determinant from Section 21.2,
which in particular gives from .
Proposition (similar matrices share the characteristic polynomial). For every square and every invertible ,
Proof. Rewrite and factor out and : .
Similar matrices therefore have the same eigenvalues with the same multiplicities as roots, and any quantity determined by the characteristic polynomial is a similarity invariant. The two most useful invariants are the determinant and the trace. For any diagonalizable matrix,
Thus the determinant is the product of the eigenvalues: whatever volume distortion introduces, undoes, leaving only the axis scaling of . For the trace, we use its cyclic property (Section 21.2.1.4),
which holds for any and whose products are square. Setting and gives
Thus the trace is the sum of the eigenvalues. On the surfer's matrix we can check both identities at a glance: and . For any matrix, these two numbers fix both eigenvalues directly as the roots of .
In fact, both identities hold for every square matrix, diagonalizable or not, provided we count the eigenvalues over with their multiplicities as roots. By the fundamental theorem of algebra (which we take as given), every degree- polynomial factors completely over :
Setting immediately yields . For the trace, compare the coefficients of on both sides. On the right-hand side the coefficient is . On the left-hand side, only the product of the diagonal entries of reaches degree , giving . Hence . Because any non-real eigenvalues of a real matrix come in complex conjugate pairs, both the sum and the product remain real.
Finally, the rank of a diagonalizable matrix equals its number of nonzero eigenvalues, counted with multiplicity: multiplying by the invertible matrices and preserves dimensions, so . Exercise 2 examines what happens when a matrix is not diagonalizable.
21.3.1.4 Algebraic and Geometric Multiplicity#
The surfer's matrix had two distinct eigenvalues and yielded two linearly independent eigenvectors. That was no coincidence: distinct eigenvalues always produce independent eigenvectors.
Proposition (distinct eigenvalues give independent eigenvectors). Eigenvectors belonging to distinct eigenvalues are linearly independent. In particular, any matrix with distinct eigenvalues is diagonalizable.
Proof. Suppose, for the sake of contradiction, that some eigenvectors with distinct eigenvalues are linearly dependent. Among all nontrivial dependence relations, choose one with the fewest nonzero coefficients, , and relabel if needed so that . Such a relation must have at least two nonzero coefficients, since alone would force . Now apply to the relation and subtract times the original relation:
The term drops out, leaving a shorter relation. Yet it is still nontrivial: any other nonzero coefficient () survives as because the eigenvalues are distinct. This contradicts the minimality of our chosen relation. When has distinct eigenvalues, its independent eigenvectors form a basis of (or of when all eigenvalues are real), so is invertible.
When eigenvalues repeat, we have to keep track of two different counts. The number of times appears as a root of the characteristic polynomial is its algebraic multiplicity . The dimension of its eigenspace—the number of linearly independent eigenvectors it contributes—is its geometric multiplicity .
Proposition. For every eigenvalue of a square matrix, .
Proof. Because is singular, its null space is nontrivial, which gives . For the upper bound, pick a basis of the eigenspace, extend it to a basis of , and place these basis vectors as the columns of . The first columns of are simply , so in this new basis the matrix takes a block upper-triangular form:
By (21.3.6), this matrix has the same characteristic polynomial as . Let us write the polynomial variable as , since now stands for our fixed eigenvalue. Subtracting preserves the block upper-triangular structure, with diagonal blocks and . Because the determinant of a block upper-triangular matrix is the product of the determinants of its diagonal blocks (Section 21.2.3.2), we get . Thus divides the characteristic polynomial, which means .
An eigenvalue can never supply more independent eigenvectors than its multiplicity as a root, though it can supply fewer. Now pick a basis for each eigenspace and pool all the chosen vectors together. They are jointly independent: if a linear combination of them equals zero, group the terms by eigenvalue; each group is either zero or an eigenvector, and the proposition on distinct eigenvalues forces every group to vanish. A matrix therefore possesses at most linearly independent eigenvectors. Over , the algebraic multiplicities sum to and for every , which gives a crisp criterion: the eigenvectors of span if and only if for every complex eigenvalue .
For a real matrix to have a basis of real eigenvectors, all of its eigenvalues must also be real. The rotation shows why that extra requirement is essential: its eigenvalues each satisfy , so it has a full complex eigenbasis, yet no real eigenvector at all.
When eigenvalues repeat, diagonalizability can fail altogether. The simplest counterexample is the shear from Section 21.2.1.2:
Its characteristic polynomial is , so has algebraic multiplicity . Yet becomes , which forces . The eigenspace is only the line spanned by , so the geometric multiplicity is . There is no eigenbasis, and the shear is not diagonalizable. Any matrix with for some eigenvalue is called defective. Figure 21.3.3 makes the shortage visible: the shear slides every horizontal line sideways in proportion to its height, leaving the horizontal axis as the sole line through the origin that keeps its direction. (By contrast, a diagonalizable matrix with a repeated eigenvalue would have to be , which preserves every direction.)
The defective shear acting on the plane. Every horizontal line slides to the right by an amount proportional to its height, tilting the grid, while the -axis (green) maps to itself: is the only eigendirection, with . The other basis vector picks up a horizontal component, , so no second direction is preserved: geometric multiplicity 1 against algebraic multiplicity 2.
Iterating the shear shows how defectiveness changes the behavior of matrix powers: , so grows without bound even though the only eigenvalue is . No pure eigen-expansion can produce that linear factor . The next subsection explains where it comes from.
21.3.1.5 The Jordan Normal Form#
When geometric multiplicity falls short, no eigenbasis exists. What structure takes its place? For what follows in this book, one consequence matters most: a defective eigenvalue multiplies by a polynomial in . Over the complex numbers, every square matrix is similar to a block-diagonal matrix built from Jordan blocks
which are blocks carrying a single eigenvalue down the diagonal and s on the superdiagonal immediately above it. This factorization is the Jordan normal form (Horn and Johnson, 2012), which we use without proof. By (21.3.6), it has the same eigenvalues as the original matrix.
Each Jordan block supplies exactly one eigenvector, namely its first basis vector. The geometric multiplicity of is therefore the number of blocks carrying , while its algebraic multiplicity is the sum of their sizes. In particular, a matrix is diagonalizable if and only if every Jordan block has size . The shear of (21.3.9) is the single block .
Under repeated application, a Jordan block does more than simply scale. Write , where has s just above the diagonal and zeros everywhere else. Geometrically, acts as a shift, sending each basis vector to the previous one, so (any matrix with a vanishing power is called nilpotent). Because and commute, we can expand powers with the binomial theorem. For , every term beyond the first two contains , leaving
In the long run, the eigenvalue still decides between growth and decay, but it is now multiplied by a polynomial in (of degree for an block). When , as in the shear, the iterates drift linearly. When is slightly below , something more surprising happens: the upper-right entry initially grows, peaks near , and only then decays toward zero. For this puts the peak near , where the entry reaches . Let us check this prediction numerically.
J = np.array([[0.99, 1.], [0., 0.99]]) # the Jordan block J_2(0.99)
for k in [1, 50, 100, 200, 800]:
Jk = np.linalg.matrix_power(J, k)
pred = k * 0.99 ** (k - 1) # predicted corner entry, k * lambda^(k-1)
print(f'k = {k:3d} ||J^k|| = {np.linalg.norm(Jk, 2):8.3f} '
f'k * 0.99^(k-1) = {pred:8.3f}')
k = 1 ||J^k|| = 1.609 k * 0.99^(k-1) = 1.000
k = 50 ||J^k|| = 30.568 k * 0.99^(k-1) = 30.556
k = 100 ||J^k|| = 36.977 k * 0.99^(k-1) = 36.973
k = 200 ||J^k|| = 27.067 k * 0.99^(k-1) = 27.067
k = 800 ||J^k|| = 0.260 k * 0.99^(k-1) = 0.260
Every eigenvalue of is , yet the norm of its powers climbs to about at and is still at before the exponential factor finally takes over. Eigenvalues alone do not warn us about this transient growth, a phenomenon we revisit in Section 21.4.2.3.
Jordan blocks represent one way a real matrix can lack a real eigenbasis: it simply has too few eigenvectors. The second way is quite different in nature. A real matrix can lack any real eigenvector in a plane because it rotates that plane.
21.3.1.6 Complex Eigenvalues#
Consider the planar rotation by an angle (Section 21.2.1.3),
Whenever is not a multiple of , turns every nonzero real vector, leaving no real eigenvector. Its characteristic polynomial has the complex conjugate roots . Here the modulus reflects that preserves lengths, while the argument records the rotation angle.
Now look at the chapter's running matrix, which shows no obvious rotation in its entries:
Its characteristic polynomial is , whose roots are with . To find an eigenvector for , read off the second row of , which gives . Setting yields
Where is the rotation hiding? Take any real matrix with a complex eigenpair , where and , and separate the eigenvector into its real and imaginary parts, . Expanding and equating real and imaginary parts gives
Both images stay inside , so this subspace is invariant under . Moreover, it is a genuine two-dimensional plane. If and were linearly dependent, their span would be a single line (not zero, because ) mapped into itself, on which would act by multiplying by some real scalar . That would force , making real and contradicting . Placing and as the columns of turns the two identities into , or equivalently,
In the basis of its invariant plane, acts as a rotation--scaling block : it scales by the modulus and rotates by the argument . Because the derivation used only , this block is independent of how is scaled or rotated in phase. The connection also works in reverse: if we identify with the complex number , then the block maps to , which is simply complex multiplication by .
For our running matrix , we have
and
,
which scales by and rotates by . One might expect every
step to lengthen a vector by the factor . Let us compute
the block from the eigenvector returned by eig and track the actual lengths
of the iterates .
A = np.array([[1., 2.], [-1., 3.]])
lam, V = np.linalg.eig(A)
j = np.argmax(lam.imag) # the eigenvalue a + ib with b > 0
r, theta = np.abs(lam[j]), np.angle(lam[j])
u, v = V[:, j].real, V[:, j].imag
B = np.column_stack([v, u]) # basis (v, u) of the invariant plane
print(f'lambda = {lam[j]:.4f} r = {r:.4f} theta = {theta:.4f}')
print('B^-1 A B =\n', np.round(np.linalg.inv(B) @ A @ B, 4))
xs = [np.array([1., 0.])]
for _ in range(8):
xs.append(A @ xs[-1])
norms = np.linalg.norm(xs, axis=1)
print('norm ratios:', np.round(norms[1:] / norms[:-1], 2))
x20 = np.linalg.matrix_power(A, 20) @ np.array([1., 0.])
print(f'average rate ||A^20 x||^(1/20) = {np.linalg.norm(x20) ** (1 / 20):.3f}')
lambda = 2.0000+1.0000j r = 2.2361 theta = 0.4636
B^-1 A B =
[[ 2. -1.]
[ 1. 2.]]
norm ratios: [1.41 2.92 3.45 2.76 2.27 1.88 1.5 1.54]
average rate ||A^20 x||^(1/20) = 2.252
Regardless of which eigenvector eig chooses, the resulting block is
. Yet the vector
lengths do not grow by a steady factor of at each step. Along the
trajectory , the per-step
norm ratios swing between roughly and . The reason is that the
scaling is uniform only in the coordinates , which are
not orthonormal. Back in standard coordinates, the iterates spiral outward
along stretched ellipses, completing a full turn roughly every
steps. Only the long-run geometric average
settles at (reaching by
). The motion is a rigid rotation and uniform scaling in standard
coordinates only when the matrix is normal, a property we define in
Section 21.4.2.2.
Up to a real change of basis, every real square matrix is built from the three elementary behaviors we have now uncovered, alone or in combination: stretching along a line, shearing within a Jordan block, and rotating with scaling in a plane. This decomposition is known as the real Jordan form (Horn and Johnson, 2012).
21.3.2 Symmetric Matrices and Quadratic Forms#
21.3.2.1 The Spectral Theorem#
Which matrices guarantee a real, orthonormal eigenbasis? Symmetry eliminates both obstacles we just encountered: it rules out complex eigenvalues as well as shortages of eigenvectors. The symmetric matrix from Section 1.3 shows what happens. Its unit eigenvectors and are perpendicular, giving
Because the eigenvector matrix is orthogonal (), its inverse is simply its transpose. The spectral theorem guarantees that this holds for every real symmetric matrix. It is the central theorem of this chapter: positive definiteness, the Rayleigh quotient, and all of Section 21.5 rest on it.
Theorem (spectral theorem). Every real symmetric matrix has real eigenvalues and an orthonormal basis of real eigenvectors. Equivalently,
where is real and is orthogonal.
We prove this in three steps: first, every eigenvalue is real; second, eigenvectors for distinct eigenvalues are orthogonal; third, a full orthonormal eigenbasis always exists. For complex vectors we use the Hermitian inner product , where is the conjugate transpose (which reduces to the ordinary dot product on real vectors). The only external fact we borrow is that the characteristic polynomial has at least one complex root (the fundamental theorem of algebra), ensuring that at least one eigenpair exists over . Parts (i) and (ii) take only two lines each; the real work is in part (iii).
Proof, part (i): the eigenvalues are real. Suppose with , allowing complex entries for the moment. Because is real and symmetric, , and therefore
Since , we can divide both sides by it to obtain : the eigenvalue must be real. Its eigenvector can then be chosen real as well, because it solves the real homogeneous system .
Proof, part (ii): eigenvectors of distinct eigenvalues are orthogonal. Let and with , where both eigenvalues and both eigenvectors are real by part (i). Using to move across the inner product,
Thus . Because , we must have .
Proof, part (iii): an orthonormal eigenbasis. We argue by induction on ; for the claim is immediate. For , part (i) supplies a real eigenpair with . Consider the -dimensional orthogonal complement . Symmetry ensures that maps back into itself: for any ,
Choose an orthonormal basis of and assemble its vectors as the columns of . Because every column of lies in , we can write where represents restricted to . Notice that is symmetric, , and has size . By the inductive hypothesis, for an orthogonal matrix . Now look at the columns of : they are orthonormal because ; they lie in , so they are orthogonal to ; and they are eigenvectors of , because . Appending them to gives the orthogonal matrix satisfying .
Geometrically, (21.3.11) breaks any symmetric linear map into three clean actions. First, aligns the orthonormal eigenvectors with the coordinate axes—a pure rotation, possibly combined with a reflection (for above, ). Next, stretches each coordinate axis by its eigenvalue. Finally, turns the axes back. This proves what the left panel of Figure 21.3.1 illustrated for , now for every symmetric matrix.
Every matrix , rectangular or square, produces a symmetric matrix . Its quadratic form can never be negative—a property that we name, test, and exploit next.
21.3.2.2 Positive Definiteness#
Can the quadratic form ever turn negative? This single question decides whether a critical point of a loss surface is a minimum, whether a matrix is a valid covariance, and whether a least-squares problem has a unique solution. A symmetric matrix is positive semidefinite (PSD), written , if
and positive definite (PD), written , if the inequality is strict for every nonzero . For instance, is strictly positive whenever , so , whereas is neither PD nor PSD because gives . Completing the square by hand quickly becomes impractical in higher dimensions, but the eigenvalues settle the question cleanly for any symmetric matrix.
Proposition (definiteness from eigenvalues). For symmetric ,
Proof. Apply the spectral theorem to write , and switch to eigenvector coordinates —an orthogonal change of basis that preserves lengths. Then
In eigenvector coordinates, the quadratic form is simply a weighted sum of squares whose weights are the eigenvalues. If every , this sum is clearly non-negative. Conversely, plugging in gives and , forcing . The positive definite case follows by the same argument with strict inequalities, since whenever .
Let us check (21.3.12) on with : the eigen-coordinates are , and the weighted sum gives , matching . Three consequences account for most appearances of positive definiteness in deep learning:
- PD implies invertible. If and , then , which forces .
- Gram and covariance matrices are PSD. For any matrix , , so . It is strictly PD if and only if has full column rank (so that implies ). Because the sample covariance of centered data is a Gram matrix divided by the number of samples, it is always PSD.
- A PD Hessian guarantees a strict local minimum. Suppose is twice continuously differentiable with , and its Hessian (the symmetric matrix of second partial derivatives) is PD. For any small step , the second-order Taylor expansion (Section 22.2.3.2) reads . By (21.3.12), the quadratic term is at least , so is a strict local minimum. Note that this condition is sufficient rather than necessary: has a strict minimum at even though its second derivative there is .
Positive definiteness also admits a fast algorithmic test, the Cholesky factorization: if and only if for a lower-triangular matrix with positive diagonal entries. One direction is immediate: such an is invertible, so for every nonzero . Attempting a Cholesky factorization is the standard numerical way to test positive definiteness, and it is considerably cheaper than computing all eigenvalues. As a bonus, the same factor transforms independent standard Gaussian samples into samples with covariance .
Geometrically, the signs of the eigenvalues govern the shape of the surface (Figure 21.3.4): a bowl when all eigenvalues are positive, a trough that is flat along any zero-eigenvalue direction, and a saddle when signs are mixed.
The quadratic-form surface for three diagonal matrices takes its shape from the eigenvalue signs: a bowl when all (positive definite), a trough when one (positive semidefinite), and a saddle for mixed signs (indefinite).
We can see the rank condition for Gram matrices directly in their eigenvalues. Below we compare a tall matrix with independent columns, whose should be PD, against one whose second column is twice the first, which should yield a PSD matrix with a zero eigenvalue.
X_full = np.array([[1., 0.], [1., 1.], [0., 1.], [2., 1.]]) # rank 2
X_dep = np.array([[1., 2.], [1., 2.], [0., 0.], [2., 4.]]) # col 2 = 2*col 1
for X, name in [(X_full, 'full column rank'), (X_dep, 'dependent columns')]:
eigvals = np.linalg.eigvalsh(X.T @ X).round(4)
eigvals[np.abs(eigvals) < 1e-9] = 0.0 # clean up tiny round-off / -0.0
print(f'{name}: eigenvalues of X^T X = {eigvals}')
full column rank: eigenvalues of X^T X = [1.1459 7.8541]
dependent columns: eigenvalues of X^T X = [ 0. 30.]
Both eigenvalues are strictly positive in the full-rank case. In the dependent case, one drops to zero: the quadratic form vanishes along , the very direction that maps to zero.
21.3.2.3 The Rayleigh Quotient#
Identity (21.3.12) does more than test signs: it turns the largest and smallest eigenvalues into the solutions of optimization problems. For a symmetric matrix , define the Rayleigh quotient
This measures the quadratic form per unit squared length, and whenever is an eigenvector, equals its eigenvalue. Throughout this subsection we order the eigenvalues by their signed values, , rather than by magnitude.
Proposition (Rayleigh). For symmetric with eigenvalues ,
with the maximum and minimum attained at the corresponding eigenvectors.
Proof. Rescaling leaves unchanged, so we may restrict attention to unit vectors. Setting preserves the norm () and turns (21.3.12) into . This is a weighted average of the eigenvalues with non-negative weights summing to . Every average lies between its smallest and largest values, so . Putting all the weight onto a single coordinate, at or , attains the two bounds.
For our running symmetric matrix , this tells us that ranges over , peaking along the eigenvector at and reaching its minimum along the eigenvector at . Every intermediate direction blends the eigenvalues and in proportion to its squared eigen-coordinates.
Maximizing over subspaces recovers all intermediate eigenvalues as well: the Courant--Fischer theorem states that , the highest guaranteed Rayleigh quotient across all -dimensional subspaces (Exercise 4d guides you through the proof).
Two applications of the extreme eigenvalues recur throughout this book. First, for any matrix , the largest Rayleigh quotient of is , the square of the largest factor by which can stretch a vector. Second, consider gradient descent on a convex quadratic with , whose update is . By (21.3.4), each eigen-coordinate is multiplied by at every step, so the iteration converges from every starting point if and only if for all —that is, . The largest eigenvalue thus caps the step size (it is the smoothness constant of Section 23.1), and for step sizes the smallest eigenvalue dictates the slowest contraction rate, . Their ratio is the condition number of , which Section 21.5.3.2 generalizes to arbitrary matrices.
21.3.2.4 Sample Covariance and the Marchenko--Pastur Law#
When we look for structure in high-dimensional data, we inspect the largest eigenvalues of the sample covariance matrix. To judge which eigenvalues are truly large, however, we first need a baseline: what do the eigenvalues look like when the data contain no structure at all? Suppose we draw samples of pure noise in dimensions, with independent coordinates of mean and variance (so the true covariance is ), and stack them as the rows of . Do the eigenvalues of the sample covariance cluster near ? For any unit vector , the Rayleigh quotient is the sample variance of the data projected onto . The extreme eigenvalues of are therefore the sample variances along the most and least variable directions—the very quantities that principal component analysis interprets as structure (Section 21.5.2.2).
Surprisingly, they do not cluster near . Let while holding the aspect ratio fixed. Then the histogram of eigenvalues of converges to a deterministic density supported on the interval
known as the Marchenko--Pastur bulk (Marchenko and Pastur, 1967), and provided the noise has a finite fourth moment, the extreme eigenvalues converge right to its edges. When , the matrix has rank at most , so at least eigenvalues are identically zero in addition to the bulk. Even with four samples per dimension (), pure-noise eigenvalues spread all the way across : the sample variance along the loudest random direction is more than double the true variance, while along the quietest it is only a quarter. At and , this asymptotic limit is already strikingly accurate. Let us test it.
n, d = 4000, 1000 # aspect ratio c = d / n = 1/4
X = np.random.randn(n, d) # pure noise: true covariance I
ev = np.linalg.eigvalsh(X.T @ X / n)
c = d / n
print(f'eigenvalues of C: min {ev.min():.3f}, max {ev.max():.3f}')
print(f'Marchenko-Pastur edges: {(1 - c ** 0.5) ** 2:.3f}, '
f'{(1 + c ** 0.5) ** 2:.3f}')eigenvalues of C: min 0.247, max 2.238
Marchenko-Pastur edges: 0.250, 2.250
On every run, the smallest and largest eigenvalues land within a few hundredths of the predicted edges and . Any eigenvalue falling inside this bulk is indistinguishable from pure noise; only an eigenvalue clearly above the upper edge provides evidence of genuine structure. Exercise 5 explores how strong a signal must be before its eigenvalue escapes the bulk.
Throughout this section we took two things for granted: that we can actually compute the eigenvalues of a matrix, and that those eigenvalues tell us what its powers do after a handful of steps just as well as after many. For large matrices and for matrices far from symmetric, neither assumption is safe. Section 21.4 takes up both.
21.3.3 Summary#
In eigenvector coordinates, a diagonalizable matrix acts as a list of scalars, , explaining repeated application in Markov chains, deep linear networks, and gradient descent on quadratics. A full eigenbasis exists over if and only if every eigenvalue's geometric multiplicity matches its algebraic multiplicity; otherwise Jordan blocks introduce polynomial factors in that can cause transient growth, while complex conjugate pairs correspond to rotation and scaling in an invariant plane. Real symmetric matrices avoid both pitfalls: they always have real eigenvalues and an orthonormal eigenbasis. Their quadratic forms become weighted sums of squares, so eigenvalue signs determine positive definiteness and the extreme eigenvalues are the extremes of the Rayleigh quotient. Finally, the eigenvalues of a pure-noise sample covariance spread across the Marchenko--Pastur interval, meaning that only eigenvalues above the upper bulk edge signal real structure.
21.3.4 Exercises#
-
Trace, determinant, and definiteness. The identities (21.3.7) and (21.3.8) fix both eigenvalues of a matrix through their sum and product.
- Find the eigenvalues of from its trace and determinant alone, without forming the characteristic polynomial. Then find its eigenvectors. Do the same for the surfer's matrix , whose trace is and determinant .
- Show that a symmetric matrix is positive definite if and only if its trace and its determinant are both positive. Which sign conditions on trace and determinant characterize positive semidefiniteness?
- Each of the matrices , , and is the Hessian of the quadratic at its critical point . Use (b) to decide for each whether the origin is a strict minimum, a minimum that is not strict, or a saddle point. For the saddle point, give a direction along which decreases.
- Show that the Cholesky factor of has the diagonal entries and . Why do the conditions under which a factor with positive diagonal exists coincide with the test of (b)?
-
Rank and zero eigenvalues. The section shows that the rank of a diagonalizable matrix equals the number of its nonzero eigenvalues, counted with multiplicity.
- Find the rank and the eigenvalues of . Which step of the argument for diagonalizable matrices fails for ?
- Let be the geometric multiplicity of the eigenvalue of an matrix , with when is not an eigenvalue. Show that for every square matrix. Conclude that the rank is at least the number of nonzero eigenvalues counted with algebraic multiplicity, with equality if and only if the eigenvalue is not defective.
- The singular values of a matrix are , the square roots of the eigenvalues of the PSD matrix . Find the singular values of and of the Jordan block of Section 21.3.1.5. Compare the number of nonzero singular values with the rank and with the number of nonzero eigenvalues.
-
The centering matrix. Let be the all-ones vector and .
- Show that is positive semidefinite by writing as a sum of squares of the differences . Then find all eigenvalues of and their eigenvectors.
- Show that is symmetric with , and deduce its eigenvalues and its rank from (a).
- Let the rows of be samples. Subtracting the sample mean from every row gives , so that the sample covariance is . Show that and . How many zero eigenvalues does the sample covariance of -dimensional embeddings computed from a minibatch of examples have at least? This is the case of Section 21.3.2.4. Which operations on does it rule out?
Adapted from Gilbert Strang, MIT 18.065 Problem Sets, Problems for Lecture 13, Problem 4.
-
[code] Accuracy of computed eigenvalues. ● The algorithm behind
np.linalg.eigvalsis backward stable: it returns the exact eigenvalues of a matrix with of the order of , where in double precision (Golub and Van Loan, 1996). A small perturbation can move a defective eigenvalue by a fractional power of .- Let be the standard basis vectors. Show that , which places in the lower-left corner of the Jordan block, has the eigenvalues , where ranges over the -th roots of unity.
- For , form with an orthogonal taken from the QR factorization of a Gaussian matrix, and record the median over draws of for the computed eigenvalues . Compare with . Repeat with the symmetric matrix .
- Let and be symmetric. Use the Rayleigh proposition of Section 21.3.2.3 to show that and . How does this explain the symmetric result of (b)?
- Prove the Courant--Fischer theorem for symmetric with . For the upper bound, intersect with , which has dimension , so the intersection is at least a line; for the lower bound take . Deduce Weyl's inequality for every , which extends (c) to all eigenvalues.
-
[code] Spikes above the bulk. ● Section 21.3.2.4 treats the Marchenko--Pastur bulk as the range of pure-noise eigenvalues. Suppose that the data contain one real direction: the samples have independent Gaussian coordinates of variance , except the first coordinate, whose variance is . For with fixed, Baik and Silverstein (2006) show that the largest eigenvalue of converges to
- For and , compute the largest eigenvalue of for , averaged over five draws, and compare with the prediction.
- Fix and . Use the formula to find the sample size above which the largest eigenvalue leaves the bulk. Then increase the number of samples through , and compare the largest eigenvalue with the bulk edge, with the prediction, and with the largest eigenvalue for at the same . Why is the separation hard to see at ?
- A practitioner keeps the principal components whose eigenvalues exceed the bulk edge. How large must the variance of a direction be at for it to be kept? How many samples per dimension are needed to detect a direction whose variance exceeds the others by ?