A matrix can mix features so thoroughly that none of its entries tells you what happens when you apply the transformation twice. An eigenvector exposes a direction where that question has a one-number answer. In machine learning, the same idea lets you find directions of high variance in a cloud of data and diagnose which components of an iterated linear update grow.
You will learn to read a transformation from its columns, find eigenpairs by hand, recognize when an eigenbasis exists, and verify the resulting decomposition with array operations. You will also use a covariance matrix to translate eigenvalues into projected variances.
Prerequisites are matrix multiplication, homogeneous linear systems, and the Euclidean norm from Linear Systems and Least Squares and Norms, Distances, and Similarity.
Read a linear transformation from its columns#
Write a vector as a column in the mathematics. In two dimensions, let e_1=(1,0)^T and e_2=(0,1)^T be the standard basis. If x=x_1 e_1+x_2 e_2, then
The first column of A is Ae_1 and the second is Ae_2. Each tells you where one unit step lands. For example, with A=[[3,2],[0,1]] written row by row, a horizontal unit step becomes (3,0)^T. A vertical unit step becomes (2,1)^T. Consequently, the point (1,1)^T maps to (5,1)^T, the sum of those two steps. The unit square becomes a parallelogram with vertices (0,0), (3,0), (5,1), and (2,1). You can recover the whole transformed grid from the two steps.
A linear transformation preserves sums and scalar multiples and fixes the origin. Adding a nonzero bias makes the transformation affine. To study the response of an affine layer f(x)=Ax+b to a perturbation d, subtract the original output. The difference f(x+d)-f(x)=Ad depends only on the linear part.
If a second matrix B acts after A, the result is B(Ax)=(BA)x. Order matters. Scaling the horizontal coordinate by two after a quarter turn sends (1,0)^T to (0,1)^T. Scaling first sends the same vector to (0,2)^T after the turn.
| Map in standard coordinates | Effect on a point (x,y) | What happens to lines through zero |
|---|---|---|
| Horizontal scale | (2x,y) | Both coordinate axes stay on their original lines |
| Reflection across the horizontal axis | (x,-y) | The vertical line stays on itself and its arrows reverse |
| Projection onto the horizontal axis | (x,0) | The horizontal line stays fixed and the vertical line collapses |
| Quarter turn counterclockwise | (-y,x) | Every nonzero real vector turns onto a perpendicular line |
| Horizontal shear | (x+2y,y) | The horizontal line stays fixed and other lines tilt |
Find the invariant lines by hand#
For a square matrix A, an eigenpair consists of a scalar \lambda and a nonzero column v that satisfy
The nonzero condition matters because A0=\lambda 0 holds for every \lambda. On an eigenline with real eigenvalue, a positive value preserves the arrow's orientation, a negative value reverses it, and zero sends the arrow to the origin. In all three cases the length scales by |\lambda|. Each nonzero multiple of v has the same eigenvalue.
Rearrange the equation as (A-\lambda I)v=0, where I is the identity matrix of the same size as A. A nonzero solution exists exactly when that shifted matrix is singular. This gives the characteristic equation \det(A-\lambda I)=0. Its roots are the eigenvalues. For each root, solve the corresponding homogeneous system. The solution space, including zero, is the eigenspace.
Return to A=[[3,2],[0,1]]. Subtract \lambda from both diagonal entries. For a two-by-two matrix, the determinant is the product along the main diagonal minus the product along the other diagonal, so
The roots are 3 and 1. For \lambda=3, the shifted rows give 2v_2=0 and -2v_2=0. Choose v=(1,0)^T. The multiplication gives Av=(3,0)^T=3v. For \lambda=1, the first row gives 2v_1+2v_2=0 and the second gives no additional constraint. Choose w=(-1,1)^T. Its image is (-3+2,1)^T=(-1,1)^T=1w. The visible vertical edge of the original square tilts, while the diagonal line through (-1,1) stays fixed.
A quarter turn uses R=[[0,-1],[1,0]]. Its characteristic polynomial is \lambda^2+1, with complex roots i and -i, where i^2=-1. There are no real eigenvectors. The real-plane geometry predicts this because a nonzero arrow and its quarter-turned image are perpendicular.
Change coordinates to make repeated transformations predictable#
Our vectors v and w are independent, so every input can be expressed in their basis. Form V by stacking the eigenvectors as columns. Let D be the diagonal matrix with the corresponding eigenvalues in column order. Since AV=VD, multiplying on the right by V^{-1} gives
Read the rightmost operation first. For x=(1,1)^T, write x=2v+1w. In the eigenbasis it has coordinates (2,1). One application multiplies these by 3 and 1, yielding (6,1). Returning to standard coordinates gives 6v+w=(5,1)^T. A second application gives 18v+w=(17,1)^T. After k applications, the coefficients are 2\cdot3^k and 1\cdot1^k because each multiplication uses the same basis.
Diagram key and text version
- Entry
- Process
- Outcome
- Input (1, 1) → Coefficients (2, 1)
- Coefficients (2, 1) → Coefficients (6, 1)
- Coefficients (6, 1) → Output (5, 1)
Repeated roots need extra care. The shear S=[[1,2],[0,1]] has the root 1 twice, an algebraic multiplicity of two. Solving (S-I)v=0 forces the second coordinate to be zero. The eigenspace dimension, called the geometric multiplicity, is one. The matrix is defective because it lacks a full eigenbasis. After k steps the shear sends (0,1)^T to (2k,1)^T, even though its only eigenvalue is 1. Checking eigenvalues alone can miss growth in a repeated update. Even a diagonalizable nonsymmetric matrix can exhibit transient amplification when its eigenbasis is poorly conditioned.
Real symmetric matrices have a stronger guarantee. The spectral theorem gives real eigenvalues and an orthonormal basis of eigenvectors, even for repeated eigenvalues. For the matrix Q of these unit-length, mutually perpendicular columns, Q^{-1}=Q^T. This turns reconstruction into A=QDQ^T and makes the change of coordinates length-preserving.
What changes when you choose a different basis?
A basis change describes the same geometric operation from another coordinate system. If a matrix P holds a new basis in its columns, then Pz expresses a coordinate vector z in the standard basis. Apply A there and solve for the new coordinates, giving P^{-1}APz. The matrix P^{-1}AP is called similar to A. If Av=\lambda v, the vector P^{-1}v is an eigenvector of the new matrix because applying it gives P^{-1}Av=\lambda P^{-1}v. The eigenvalue survives the change of coordinates.
The determinant and trace offer quick checks. The determinant is the product of the eigenvalues, counted with multiplicity. The trace, the sum of the diagonal entries, is their sum. In the worked example the product is 3 and the sum is 4, matching the determinant and trace of A. A zero eigenvalue means some nonzero input vanishes, so the map cannot be inverted.
Verify the mathematics with NumPy#
In NumPy a single sample can use shape [D] and a table of N samples uses [N,D]. When A maps D inputs to M outputs, its shape is [M,D]. With samples stored as rows, the batch expression is X @ A.T, yielding [N,M]. Ordinary eigenanalysis requires M=D because Av and \lambda v must inhabit the same coordinates.
import numpy as np
A = np.array([[3.0, 2.0], [0.0, 1.0]])
X = np.array([[1.0, 1.0], [-1.0, 1.0]])
assert np.allclose(X @ A.T, [[5, 1], [-1, 1]])
values, V = np.linalg.eig(A)
assert np.allclose(A @ V, V * values[None, :])
coordinates = np.linalg.solve(V, X[0])
assert np.allclose(V @ (values * coordinates), [5, 1])
The jth eigenvalue pairs with column j of V, and the broadcast multiplication scales columns. With a stack of square matrices shaped [B,D,D], the eigenvalues have shape [B,D] and the eigenvectors have shape [B,D,D]. Use values[..., None, :] to preserve the batch axes when checking the residual. Compare eigenpair equations or reconstructions with a tolerance appropriate to matrix scale and dtype. The general solver can return complex values for a real input and its order is unspecified.
Use np.linalg.eigh for symmetric real or Hermitian complex input. It returns eigenvalues in ascending order and uses the triangle selected by UPLO. Check the symmetry assumption before calling it on data assembled by code. On the tensor side, torch.linalg.eigh follows the same batch and column conventions for symmetric or Hermitian matrices. PyTorch documents numerical instability in eigenvector gradients when eigenvalues are close. If a loss only needs the spectrum, express it directly using eigenvalues instead of differentiating through an eigenvector basis.
Run the downloadable lab with python3 labs/ai/05-matrix-transformations-eigenvalues.py from the repository, or run the downloaded file with Python 3 and NumPy installed. The lab checks the hand calculations, complex rotation, shear growth, batch residuals, and covariance reconstruction.
See projected variance before you learn PCA#
Suppose your centered dataset, stored as rows, is X=[(2,1),(-2,-1),(1,2),(-1,-2)]. Its column means are both zero. With N=4 samples, the sample covariance is C=X^TX/(N-1). Here X^TX=[[10,8],[8,10]], so the diagonal variances are both 10/3 and the cross-covariance is 8/3.
Project the data onto a unit column q using Xq. These coordinates have mean zero. Their sample variance is
For an eigenvector of C with unit norm, this simplifies to q^TCq=\lambda. The direction q_+=(1,1)^T/\sqrt{2} has eigenvalue 6 and q_-=(1,-1)^T/\sqrt{2} has eigenvalue 2/3. You can check the first result directly. The projection onto q_+ has coordinates 3/\sqrt{2}, -3/\sqrt{2}, 3/\sqrt{2}, and -3/\sqrt{2}. Their squares add to 18, and dividing by 3 yields 6.
Any unit direction can be written as a q_+ + b q_- with a^2+b^2=1. Orthogonality cancels the cross-terms, so the projected variance is 6a^2+(2/3)b^2. The maximum is 6 and occurs along the line of q_+. A model that keeps only that projection retains 6/(6+2/3)=90\% of this sample's total variance. That figure describes spread. For a prediction task, check whether the discarded direction carried information about the target.
Every real sample covariance is symmetric and positive semidefinite, meaning q^TCq\ge 0 for any q. The formula expresses it as a sum of squares divided by N-1, provided N>1. Zero is a legitimate result when a direction has no observed variation. A tiny negative computed eigenvalue can come from roundoff. A substantial negative eigenvalue calls for checking the matrix construction, symmetry, and input quality.
Debug numerical and modeling failures#
- A direction changed sign after a library upgrade. Both signs describe the same real eigenline. Validate the residual, or compare the sign-invariant matrix qq^T for a unit eigenvector.
- Two directions rotate between runs. Repeated eigenvalues allow different orthonormal bases of the same eigenspace. For a separated group of nearly equal eigenvalues, compare the projector Q_kQ_k^T onto the group, where Q_k contains its k orthonormal eigenvectors. Inspect the gap between the group and the rest of the spectrum before interpreting changes.
- Training and serving give different projections. Check sample and feature axes, center using the training mean, and deploy the fitted feature order, scaling, and basis together. Covariance depends on feature units, so compare results before and after justified scaling.
- An update grows faster than expected. Measure \lVert A^k x\rVert_2 for representative initial states. Eigenvalues describe modal growth. Nonsymmetric maps can amplify vectors in one step by more than the largest eigenvalue magnitude. Check singular values when you need worst-case one-step stretch.
- An eigenbasis reconstructs poorly. Check shapes, pair ordering, finiteness, and the residual AV-VD. Inspect rank and conditioning of V before solving for eigenbasis coordinates. A small residual can coexist with a nearly singular eigenbasis.
Try it yourself
Recover the collapse direction
Let P=[[1,1],[0,0]]. Find its eigenvalues and an eigenvector for each. Predict what P^2 does.
Reveal solution
The polynomial is (1-\lambda)(-\lambda), with roots 1 and 0. For 1, choose (1,0)^T, which lies on the horizontal line that stays fixed. For 0, solve v_1+v_2=0 and choose (-1,1)^T. Any first application produces (x+y,0)^T. That output stays fixed under a second application, so P^2=P.
Try it yourself
Explain a covariance test failure
A model fit returns a unit top eigenvector q on one machine and -q on another. A test compares raw vectors and fails. Which test would check whether the two results represent the same line?
Reveal solution
Compare qq^T to (-q)(-q)^T, which are identical in exact arithmetic. Also verify the covariance eigenpair residual for each result. If two eigenvalues coincide, check the projector onto their full eigenspace because individual columns may rotate inside it.
Memory chart#
| Question | Calculation |
|---|---|
| Where does basis vector e_j go? | Read column j of A |
| Which scalars preserve an eigenline? | Solve \det(A-\lambda I)=0 |
| Which vectors belong to a root? | Solve (A-\lambda I)v=0 and exclude zero for eigenvectors |
| How does a diagonalizable map iterate? | Multiply each eigenbasis coefficient by \lambda^k |
| How much variance lies along a unit covariance eigenvector? | Read its eigenvalue |
The next lesson, SVD and Low-Rank Structure, extends these ideas to rectangular feature matrices and separates the input directions of greatest stretch from their output directions.
References#
- Mathematics for Machine Learning, Chapters 2 and 4 covers matrix representations, eigenpairs, and diagonalization.
- Deep Learning, Section 2.7 connects symmetric eigendecomposition with quadratic forms.
- NumPy eig documentation specifies the general solver's output shapes and pairing.
- NumPy eigh documentation describes the symmetric and Hermitian solver.
- PyTorch eigh documentation describes batched inputs, eigenvector ambiguity, and gradient behavior.