In P1.B12 you looked for directions that a matrix only stretches. That works well for symmetric matrices, but a general matrix can turn every direction, and its eigenvalues can even be complex. This lesson gives the answer that works for every real matrix, of any shape: there is always a pair of perpendicular input directions that the matrix sends to a pair of perpendicular output directions, stretching each by some amount. That is the singular value decomposition, or SVD.
It is one of the most useful facts in applied linear algebra. It shows what a matrix does, it measures how many directions really matter, and it hands you the best simple approximation of a matrix, the pseudo-inverse, the condition number and PCA, all from one factorisation.
The picture: a circle becomes an ellipse
Start with the shear of P1.B12:
Take all vectors of length : they form the unit circle. Send each one through . The circle comes out as an ellipse (a stretched circle). This is true for every matrix that is not squashed flat: a linear map turns a circle into an ellipse.
An ellipse has a longest axis and a shortest axis, and they are perpendicular. Call the half-lengths (sigma) and the unit directions of the axes and . So the axes are the arrows and . Now ask which inputs land on the ends of these axes. Those inputs are two perpendicular unit vectors, and :
The numbers are the singular values of . For the shear they are and , the numbers promised in P1.B12. The widget shows all of this and lets you apply the three steps one at a time.
Things to try:
- At the start (the shear, stage 3): the ellipse is long and thin, tilted up to the right. The pink arrow is the short axis and the blue the long one. On the dashed circle, the thin arrows and are perpendicular. The check lines show and .
- Press Start, then 1: Vᵀ, 2: Σ, 3: U. Step 1 turns the plane (the circle looks the same, but now lie on the axes). Step 2 stretches the horizontal axis by and the vertical one by . Step 3 turns the ellipse into its final place. Or drag the Stage slider, or press Play all.
- Press Diagonal: the matrix already stretches along the axes, so the turns are (or a flip of an axis). Press Symmetric ( and , the eigenvalues of P1.B12): the ellipse axes lie along and .
- Press Rotate 30°: and the ellipse is a circle. A circle has no longest direction, so the status says that any perpendicular pair would work for .
- Press Rank 1: the ellipse collapses to a line segment, , and the status says that is the direction that is squashed to the origin. Press Zero: everything collapses to a point.
- Press Reflect: , and the status mentions a reflection (). Use the sliders to make negative in other ways, and watch the Stage-3 step flip the plane over.
Intuition
Every matrix, however messy, does three simple things in a row: it turns the plane (or flips it), it stretches along the two axes by different amounts, and it turns again. The first turn lines up the two special input directions with the axes. The stretch is the only part that changes lengths. The last turn puts the result where it belongs. The singular values are the stretch factors, so they are the “size” of each of the two directions.
The picture of a rubber sheet from P1.B12 breaks in two places. A flip is not something a sheet can do by pulling (it is a reflection, when ). And for a matrix that is not square, the “plane” you start in and the space you end in have different numbers of dimensions, so the turns happen in different spaces.
Math
Every real matrix can be written
with an orthogonal matrix, an orthogonal matrix (P1.B10), and an matrix that is zero except for the numbers on its main diagonal. The proof that this always exists is not needed here. The columns of are the right singular vectors, the columns of the left singular vectors, and .
Code
import numpy as np
A = np.array([[1.0, 1.0], [0.0, 1.0]])
U, S, Vh = np.linalg.svd(A) # S: the singular values (a 1-D array); Vh: V transposed
print(S) # about [1.618 0.618]
print(U @ np.diag(S) @ Vh) # gives A backThe NumPy section below runs this with all the checks.
Rotate, stretch, rotate
Read from right to left, because applies first (P1.B6):
- rotates or reflects. It is orthogonal, so it keeps lengths and angles (P1.B10). The dot products are the coordinates of along the new axes , and is the -th axis arrow .
- stretches along the axes: coordinate is multiplied by . This is the only step that changes lengths.
- rotates or reflects again, so the -th axis ends up along .
Putting the middle step into words for the unit circle: step 1 maps it to itself, step 2 makes an axis-aligned ellipse with semi-axes , step 3 moves that ellipse. That is exactly what the widget stages show.
For the shear, with numbers rounded to three decimals:
is a rotation by clockwise and is a rotation by counterclockwise. Check: .
The properties to remember
- Singular values are non-negative and sorted: . A negative sign, if there is one, is moved into or . That is why a reflection shows up as an orthogonal matrix with : when , one of the two turns is really a flip. For a square matrix, , since turns and flips do not change areas or volumes (P1.B8); the shear has .
- Rank = number of non-zero singular values (P1.B7). A zero means the direction is squashed to : the vectors with (together with any extra when ) span the null space, and the vectors with span the column space.
- The factorisation exists for every real matrix. Not only square, not only symmetric, not only invertible.
- Not unique in the details. The singular values are unique. If you flip the signs of and together, you get another valid SVD, and software may return either. If two singular values are equal (a rotation has ), then any perpendicular pair in that plane works: the circle stays a circle.
- Norms. The largest stretch over all is , the 2-norm (it is the longest semi-axis of the ellipse). The Frobenius norm , the square root of the sum of the squares of all entries, equals . For the shear, and .
Full and thin SVD
If is then the full SVD has of shape , of shape and of shape . There are only singular values, so for a tall matrix () the extra columns of multiply rows of zeros in and do nothing. The thin (or economy) SVD drops them: is , is and is , where . It rebuilds the same , and it is what you want for tall data matrices. For the matrix of P1.B9 the full is and the thin one .
Finding an SVD by hand
The singular values and vectors hide in a matrix you already know how to handle. Multiply out using and :
This is an eigen-decomposition of the symmetric matrix (P1.B12 spectral theorem). So the columns of are eigenvectors of and the eigenvalues are . In the same way, : the columns of are eigenvectors of with the same non-zero eigenvalues. A one-line reason that the are never negative: (P1.B12: is positive semi-definite).
The recipe, for the shear:
- , with trace and determinant . The characteristic equation gives and .
- : and . (Indeed .)
- is a unit eigenvector. For : gives , so , which as a unit vector is .
- (when ). For the full SVD, complete the ‘s (and ‘s) with any extra perpendicular unit vectors. For the shear, .
This is the method for hand work. Software does not form for real problems, because it squares the condition number (P1.B11), and it uses other algorithms that work on directly.
Eigenvalues are not singular values
P1.B12 promised this comparison. The eigenvalues of a matrix are about directions that stay on their own line; the singular values are about the largest and smallest stretch over all directions.
- Shear : eigenvalues , singular values and . It stretches (length ) to (length ), which no eigenvalue of could explain.
- Rotation: complex eigenvalues (P1.B12), singular values and . A rotation does not stretch anything.
- Symmetric matrix : eigenvalues and , singular values and . For a symmetric matrix the singular values are the absolute values of the eigenvalues; the minus sign becomes a flip. And for a symmetric positive semi-definite matrix, such as (eigenvalues ), the SVD is the eigen-decomposition: and (P1.B12 spectral theorem).
- A non-square matrix has no eigenvalues at all, but it always has singular values.
Both and appear in the SVD, and they are different matrices in general: the eigen-decomposition uses one basis for input and output, while the SVD lets the input and output axes differ and keeps both perpendicular.
A matrix as a sum of layers
Write column by column, using the outer-product view of P1.B6 (a product is a sum of columns times rows):
with the rank. Each term is a rank-1 layer (every row is a multiple of one row, P1.B6). The layers come in decreasing order of importance: the first has the largest . A low-rank approximation keeps only the first :
It has rank at most . A first example uses the matrix of P1.B7. Its singular values are about , and (almost exactly) , so its rank is , and the first layer already gets close:
Every entry is within of the entry of , and the error (in the 2-norm) is exactly .
How good is the truncation? Eckart–Young
The Eckart–Young theorem (Eckart and Young proved it for the Frobenius norm; the 2-norm version is usually credited to Mirsky) says that is the best rank- approximation there is, in two senses. Among all matrices of rank at most :
and reaches both values:
(Both statements are given without a full proof; the 2-norm one is proved in the box below, for .) For and both errors are , because . A good rule: the error is made of the singular values you throw away. A relative error is , and it is small exactly when the discarded ‘s are small next to the kept ones. For , the first layer holds of the total in the sum of squares, about .
Go deeper Why no rank-k matrix beats the cut-off, in the 2-norm
Let have rank at most . Its null space has dimension at least (P1.B7, rank plus nullity). The span of has dimension . In dimensions, a space of dimension and one of dimension must share a non-zero vector (their dimensions add up to ), so take it with length . Then , so . Write with . Then and , because each of is at least . So .
Storage: when does it really compress?
Keeping means keeping the first columns of (each has numbers), the first columns of (each has numbers) and the singular values. That is
numbers, against for the original. This is smaller only when . For a picture, and , so saves space () and does not (). The larger the matrix, the more it saves: for a matrix, rank needs numbers instead of .
Image compression
A grey picture is a matrix of brightness numbers (P1.B1 treated a picture as a list of numbers). The widget below makes a picture in code (a house, a sun and a tree; no image file is loaded), computes its SVD in your browser, and rebuilds it from the first layers.
Things to try:
- At the picture is a pattern of horizontal and vertical bands: one layer is one column pattern times one row pattern. The relative error is about . At the house and the sun are clear, and at the picture is a good copy (about error) with numbers instead of , about .
- Look at the bar chart. The first singular value is about , the second about , and by the tenth they are near . A few big values and many small ones is why compression works: the small layers add little detail. Tick Log scale to see them.
- The two error lines agree to the digits shown at every : one is computed from the singular values with the formula, the other by subtracting the pictures. At each the next singular value is the 2-norm error.
- Slide to : the picture is almost exactly the original, but the storage line shows numbers against : no saving, and the status says so. At the picture is rebuilt exactly (up to rounding). At the picture is black and the error is .
- This particular picture has about non-zero singular values; the last or so are zero up to rounding errors, because the picture is made of a few flat shapes. A photograph usually has many more non-zero values, with a slower fall.
A preview of LoRA
P1.B6 and P1.B7 met LoRA, the method behind P10.E3. The weight matrix is frozen, and the update is learned as a product of a and an matrix (the paper’s letters: these and are new matrices, not the ones of this lesson), so the update has rank at most and only numbers to learn. For and that is numbers instead of . (The SVD form above stores : the extra are the singular values. A product has no separate ‘s.)
The SVD says what this restriction means: a rank- matrix is a sum of layers, and by Eckart–Young the best rank- stand-in for any matrix is its top layers. LoRA’s authors hypothesised that the change in weights during adaptation has a low “intrinsic rank”, so a small can be enough. That is an empirical bet that worked well in their experiments, not a theorem. Also note that LoRA does not compute an SVD. It learns and by gradient descent, starting from a random and so that the update starts at zero. P10.E3 covers the method.
The pseudo-inverse
A non-square or singular matrix has no inverse (P1.B9). But its SVD still shows what to do. A matrix does three things: turns, stretches, turns. To undo it, undo each step in reverse order: undoes , then divide by each , then undoes . The only problem is a zero , which cannot be divided by. The fix is to leave those directions at zero. The result is the pseudo-inverse:
where is made from by inverting every non-zero singular value and transposing the shape (an matrix becomes ). It exists for every matrix and is unique.
What it is for. is the minimum-length least-squares solution of : among all that make smallest (P1.B11), it is the shortest one. When is square and invertible, .
Example 1: independent columns. The tall matrix of P1.B9 has , with eigenvalues and (the matrix of P1.B12). So and . Inverting these and rebuilding gives
which is the left inverse that P1.B9 wrote down and promised to explain. It equals , the least-squares formula of P1.B11. This is the general fact: if the columns of are independent, then , because then is invertible and its inverse times gives (the shape version of ). Then .
Example 2: dependent columns. The “same ” matrix of P1.B11 has two columns that are multiples of one another:
It has rank with and . Only one layer exists, , so , and
This is the answer np.linalg.lstsq gave in P1.B11. Many weights fit equally well (any ): has length , has length , and has length , the shortest. The pseudo-inverse picks it because it leaves the direction (the null space) at zero: it never adds a null-space part, which could only make longer.
Warnings. is the identity only when the columns are independent (otherwise it is the projection onto the row space), and is the identity only when the rows are independent. In floating point, “zero” means “below a cutoff”: np.linalg.pinv treats singular values that are tiny compared with as zero, much as matrix_rank does, though the default cutoff differs (pinv drops singular values up to times ).
Conditioning and numerical rank
The condition number from P1.B8 and P1.B9 can now be written down. It is the ratio of the largest to the smallest stretch, for a square matrix (for any shape, the largest singular value over the smallest of the of them; if the smallest is , is infinite). The shear has , a rotation .
Why do small singular values matter? Inverting divides by each : . Any noise in along is multiplied by , and if is tiny that is a huge number. The nearly parallel basis of P1.B9, , has and , so . With the solution is ; changing by moves the answer to , a change of in each weight from a change of in the data.
Numerical rank is the count of singular values above a tolerance: np.linalg.matrix_rank uses (by default) , with (P1.B7). For that is about , and the third singular value of is far below it, so the rank is . In real data the question is rarely “is this exactly zero” but “where do the singular values fall off”, and a good cutoff is a modelling choice.
Notice the contrast: to approximate the small singular values are the ones to drop, but to invert they are the dangerous ones, because their inverses are the largest. Ridge regression (P3.A6) is a gentler way to handle them than cutting them off.
PCA via the SVD
Let be an data matrix whose columns have been centred (each column has mean , P1.D7), with one row per example. Its sample covariance matrix is (some books divide by instead; then the numbers below change by that factor). If , then
So the right singular vectors are the principal directions (the eigenvectors of the covariance matrix of P1.B12), and the variance along is . The coordinates of the data along them are the columns of . Keeping only the first is the best rank- approximation of the data (Eckart–Young), the idea of P3.C3.
Example: four points , , , have mean and sample covariance , the matrix of P1.B12. The SVD of the matrix has and , so the variances are and : the eigenvalues and of P1.B12, along and (up to sign). Why use the SVD rather than form and take its eigenvectors? It works on itself and so avoids squaring the condition number (P1.B11).
Try it in NumPy
np.linalg.svd(A) returns three things: U, a 1-D array S of singular values (largest first, not a matrix: use np.diag(S) to make ), and Vh, which is (so the right singular vector is row Vh[i], not a column). By default it returns the full SVD; pass full_matrices=False for the thin one. The signs of the singular vectors are arbitrary: your U and Vh may differ in sign from the numbers below (a column of U and the matching row of Vh flip together). np.linalg.pinv(A) is the pseudo-inverse, np.linalg.norm(A, 2) is , and np.linalg.cond(A) is .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect:
- The singular values are and . The rebuilt equals (
True), and both linesA v_iandsigma_i u_iagree. - The values and are the eigenvalues of . The product of the ‘s is ,
norm(A, 2)is andcondis . UandVhon your machine may differ from the numbers in this lesson by signs (for example a column ofUand the matching row ofVhboth negated).- The shapes: full
(3, 3) (2,) (2, 2)and thin(3, 2) (2,) (2, 2). The singular values of are and .
The second cell does the low-rank approximation, the pseudo-inverse and conditioning.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
- The singular values of are about , and a number that prints as
0.(really about ). The rank-1 approximation matches the matrix shown earlier, has rank , and both error lines equal .matrix_rank(M)is and the tolerance is about (the exact digits can differ between machines). pinv(B)has rows with entries and ( and ),pinv(B) @ yandlstsqboth give .3 * pinv(A3)shows the left inverse of P1.B9 (a zero entry may print as-0.), andallcloseprintsTrue.Chas singular values and about and condition number about . The two solves return and , up to rounding in the last printed digits.
Where you will meet it next
- PCA (P3.C3). The SVD of the centred data matrix, above.
- LoRA and low-rank fine-tuning (P10.E3). A weight update restricted to rank .
- Recommender systems (P11.3). A table of user ratings is approximated by a product of two thin matrices (user features times item features). Real systems have missing ratings, so they fit the factors to the known entries instead of computing a plain SVD of the table, but the low-rank idea is the same.
- Model compression (P11.8). A big weight matrix can be replaced by two thin factors, one of several compression ideas.
- Linear regression and least squares (P3.A2). NumPy’s
lstsqis computed from the SVD, and that is how it copes with dependent features (P1.B11). - Exploding gradients (P4.16). for every , so (the 2-norm, or spectral norm) is the most a layer can stretch a vector. Keeping it near is one way to keep signals and gradients stable.
- Tensors and shapes (P1.B14) and the map of linear algebra in a neural network (P1.B15) come next.
Go deeper The four subspaces and the SVD
The SVD gives orthonormal bases for all four fundamental subspaces of an matrix of rank . span the row space, span the null space (), span the column space, and span the null space of . The matrix is an invertible map from the row space to the column space (stretching to ) and sends the null space to zero. The pseudo-inverse runs the invertible part backwards and sends the null space of to zero.
Go deeper Ridge regression as a soft cut-off of small singular values
For , ridge regression with penalty (P3.A6) has the solution . Compare with the pseudo-inverse, which uses : for a large the two factors are almost equal, but for a tiny the ridge factor is near (small) instead of the huge . So ridge turns the sharp “keep or drop” of the pseudo-inverse into a smooth shrinking of the directions with small singular values.
Common mistakes
Check your understanding
The shear has eigenvalues and . What is the largest factor by which it can stretch a vector?
The largest stretch of a matrix over all directions is its largest singular value, . The eigenvalues only describe the one direction that stays on its own line. For example has length and goes to , of length about , so the largest stretch is more than . The length of a row is not a stretch factor, and is the smallest stretch, not the largest.
A real matrix has rank . What are the shapes of , and in its thin (economy) SVD?
The thin SVD keeps singular values: is , is and is with . The option with a and a describes the full SVD. The option with a and a swaps the roles of and (the left vectors live in the output space of dimension ). The option with a keeps one singular value, which is the shape of a rank-1 approximation.
A matrix has singular values , and . The best rank-1 approximation of it (the top layer) has what error in the Frobenius norm?
By Eckart–Young the Frobenius error is the square root of the sum of the squares of the singular values that are dropped: . The value is the error in the 2-norm, , not the Frobenius norm. The value is only , and is the size of the whole matrix, not the error.
The equation has many solutions for the least-squares problem with the matrix of this lesson. Which one does the pseudo-inverse pick?
All four options satisfy (for : ), so all fit equally well. The pseudo-inverse chooses the one of smallest length. The lengths are for , for , for and for .
A square matrix has singular values and . What is its condition number, and what does it mean?
The condition number is the largest singular value over the smallest, . A value this large means the matrix is badly conditioned: a small relative error in the data can become a relative error up to about times larger in the solution (P1.B9). The value is just the largest singular value, not a ratio. is the inverse ratio and would be below , which the condition number never is. The sum is not a measure of conditioning.
A real matrix has singular values and . What is it?
Equal singular values mean the unit circle goes to a circle of radius , so every vector is stretched by the same factor and angles are kept: the matrix is times an orthogonal matrix. A shear has two different singular values, a projection has a zero one, and the zero matrix has both equal to .
A data matrix with rows has centred columns, and its first singular value is . Using the sample covariance with in the denominator, what is the variance of the data along the first principal direction?
With , the variance along is . The singular value itself is not a variance, dividing it without squaring is wrong, and multiplying by goes the wrong way.
Exercises
- Find the singular values of and say what the minus sign becomes.
Show answer
The matrix stretches the axes by and and flips the second one. , so and (sorted). The minus sign is moved into (or ) as a reflection, so and . The eigenvalues are and and the singular values are their absolute values. - Find the singular values of and its rank, and say where points.
Show answer
has trace and determinant , so eigenvalues and and and . The rank is . is the direction squashed to the origin: , so up to sign. - A matrix has singular values and . Give , , and the singular values of .
Show answer
, , . has singular values and , so its largest is . - Find an SVD of by the recipe.
Show answer
, so the eigenvalues are (eigenvector ) and (eigenvector ): , and , . Then and . It swaps the axes while stretching one by . (The eigenvalues of itself are , not the singular values.) - A matrix is approximated with rank . How many numbers are stored, against the original, and up to which does the approximation save space?
Show answer
against (about ). It saves space while , so for . - Find the pseudo-inverse of the column vector (a matrix) and use it to solve for in the least-squares sense.
Show answer
The only singular value is , with and . So , a matrix. Then . This is also , since the one column is independent. - Show that for any real matrix and unit vector , , and use it to say why is the largest eigenvalue of .
Show answer
. For a symmetric matrix such as this is largest, over unit , along the eigenvector of its largest eigenvalue, where it equals that eigenvalue (P1.B12, covariance and PCA). So the largest stretch squared, , is the largest eigenvalue of . - Give the eigenvalues and the singular values of .
Show answer
It is triangular, so the eigenvalues are the diagonal entries, and . But , so the singular values are and : the matrix sends to , a stretch of . The eigenvalues say nothing about this stretch. - Predict the shapes
np.linalg.svd(np.ones((5, 3)), full_matrices=False)returns, then check with code.Show answer
Uis(5, 3),Sis(3,)andVhis(3, 3). The matrix has rank , so only the first value ofSis clearly non-zero (it is ) and the other two are zero up to rounding (around , or exactly ). - For the four-point data of the PCA section, what are the principal directions and the variances, from the singular values and ?
Show answer
The variances are with : along and along (signs are arbitrary). Their sum is the trace of the covariance matrix, the total variance.