The eigendecomposition works on a square covariance. The singular value decomposition (SVD) works directly on a rectangular data matrix. It separates a matrix operation into input directions, nonnegative scale factors, and output directions. The input and output can have different dimensions, so the directions on the two sides need not live in the same space.
For this chapter let be any matrix. A column input has entries and the output has entries. In the small example
the input maps to , which is three times the unit output direction . The input maps to , which is twice . These perpendicular input directions map to perpendicular output directions, with scale factors 3 and 2. The output has three entries even though the input has two.
For a general matrix, SVD finds suitable directions even when the input table is not already diagonal. Let be a unit right singular direction in the input space, let be its unit left singular direction in the output space, and let be their nonnegative scale. The key relation is . “Right” and “left” describe where the directions appear in the factorization; neither means an orientation on a page. A zero scale contributes no output in that direction.
Let be an orthogonal matrix of left directions, and a orthogonal matrix of right directions. Let be an rectangular diagonal matrix: its only potentially nonzero entries lie where row and column indices agree. Those entries are the singular values in decreasing order. Then
Figure 6 labels this singular-value matrix with the traditional bare ; it is a different object from the covariance in §4. The columns of are directions indexed by features, and those of are directions indexed by observations. Actual coordinate scores are , not alone: each left direction must receive its singular-value scale.
Read the product from right to left, as with eigendecomposition. resolves an input into right-direction coordinates; scales those coordinates and accounts for the change in dimension; writes the result in the original output coordinates. For the example, full factors can use a identity for , a identity for , and the displayed rectangular table for . Nothing needs turning because the table already uses suitable directions.
Let , where selects the smaller number. The thin SVD removes the unused full-matrix directions: it has of shape , of shape , and of shape , with the same product . Keeping only directions is the further operation of truncation.
In the example, . The thin keeps the first two columns of the three-dimensional identity, the scale matrix becomes , and remains the two-dimensional identity. Multiplying these factors still reconstructs every entry. Thin factorization changes storage without losing any information; truncation will deliberately lose contributions.
Transposing a product reverses its order: . Apply that rule to the SVD, multiply, and use . For the full rectangular decomposition the steps are
Each diagonal entry in the middle is a singular value multiplied by itself. For the thin decomposition the middle product is the square diagonal matrix . Thus the right singular directions are also eigenvectors of the Gram matrix, with squared singular values as eigenvalues. In the exact example, the Gram matrix is .
If is centered and equally weighted, covariance is that Gram matrix divided by . Its right directions therefore stay the same, and its eigenvalues are . The diagonal example above is not centered, so its Gram matrix should not silently be called an empirical centered covariance. The notebook also applies the identity to the centered six-document table.
For the weighted covariance of §4, instead decompose . Here is diagonal with entries , so it scales each centered row by the square root of its weight. When we form a Gram product, one square-root weight comes from each factor; their product is the full weight . Divide the resulting squared singular values by total weight . Scores for the original, unweighted observations are still , not the weighted rows’ scores. A direction’s canon is its representative collection of high-scoring stories; a left singular vector alone is not generally the original article-score column in a weighted fit.
Let and contain the first columns of the thin factors, and let contain their singular values on its diagonal. Their shapes are , , and , respectively. The approximation has rank at most . It keeps only independent contributions with which to rebuild the table.
The residual table is original minus reconstructed, . A positive residual entry says that the reconstruction was smaller than the original there; a negative entry says it was larger. Adding those signed errors would allow overestimates and underestimates to cancel. Instead square every entry and add. This is the sum of squared errors. Least squares means choosing a reconstruction that makes such a sum as small as the allowed family permits.
The Frobenius norm, written for a matrix , is the square root of the sum of all its squared entries. It extends vector length to a whole table by treating every cell as a coordinate. Minimizing this norm or its square gives the same minimizing table, because the square-root function preserves order among nonnegative numbers.
In the rectangular diagonal example, keeping the scale 3 and dropping the scale 2 reconstructs only the entry 3. The residual has a single nonzero entry, 2. Its squared Frobenius norm is therefore 4, and its norm is 2. The original table’s squared norm is . Define relative error as residual norm divided by the positive original norm; here it is . An error ratio is not a proportion of articles reconstructed correctly; it compares geometric lengths in this representation.
Before asking a matrix theorem to minimize anything, solve a scalar fitting problem. Suppose we must replace the observations 1, 2, and 3 by one common fitted value, called (Greek theta). Their residuals are , , and . Let name their sum of squared residuals; is a function, a rule returning a number for each proposed input . Expanding the three squares gives
The last form makes the minimum visible. A square cannot be negative, and is zero exactly when . Thus the smallest squared error is 2. Trying or gives squared error 5. At the best fit the signed residuals are −1, 0, and 1; their sum is zero, while their sum of squares is two. These are different quantities.
Differentiation provides another way to inspect how changing the fit changes the error. Let be a small nonzero change in . The difference is the change in error. Divide by to obtain change in error per unit change in the fitted value, an average slope over that step. Expanding the quadratic and canceling equal terms gives
As the step becomes arbitrarily small, the last term approaches zero. The resulting local slope is the derivative, written or ; the prime here means derivative, not the rotated coordinate notation used later:
We differentiated to learn which way the error changes. Below 2 the slope is negative, so increasing the fit locally lowers error; above 2 the slope is positive, so increasing it locally raises error. At 2 the slope is zero. A zero derivative is a stationary point, not automatically a minimum for every function. Here the completed-square formula proves it is the global minimum. This example supplies the meaning of derivative, the calculation from a small change, and the reason for setting it to zero. No matrix differentiation is required to use the SVD that follows.
The Eckart–Young theorem says that the truncated SVD minimizes among all matrices of rank at most . This comparison matters: we are not saying that an arbitrary reconstruction is best, or that the reconstruction is a true explanation of the subjects. We are choosing the best approximation under this particular squared-error measure and rank constraint.
The squared error equals the sum of squared discarded singular values. To see the accounting, each singular component has a unit left direction, a unit right direction, and a scale . Its contribution to squared table length is . Distinct components are perpendicular when their tables are compared entry by entry, so their squared lengths add without cross terms. Keeping the largest scales retains the most of this length budget. The theorem adds the stronger claim that no different rank- table does better.
Figure 7 applies this to the six-document matrix of Figure 1. Its singular values are 1.64, 1.51, 0.82, 0.55, and then almost nothing. Relative error means for nonzero . Compute it by squaring and adding the discarded singular values, dividing by the sum of all squared singular values, and taking a square root. Rank 1 rebuilds only the war documents (relative error 0.74); rank 2 rebuilds both blocks, war and banking, and the error drops to 0.42; rank 3 reaches 0.24. Two components already separate the two kinds of document in this small example. The notebook uses unrounded singular values, so its checks do not accumulate rounding error from the printed labels.
Latent semantic analysis (LSA) uses a truncated SVD of a document–term matrix such as TF‑IDF; Eigen Times additionally centres and, in the archive edition, weights that matrix. Each retained column of is a direction over terms. Its entries are loadings: coefficients telling how strongly each input feature contributes to the direction. Its largest term loadings provide a word list (Figure 8). In the toy corpus the first component loads on troops, border, ceasefire, the second on bank, rate, mortgage, rise. In the real Eigen Times v0 basis the axes read bank · financial · credit · rate · loan, Russian · Russia · Ukraine · Putin · Moscow, flight · airline · passenger · airport · crash, and so on—sixty word lists that a reader recognises at once.
There are two distinct roles for a loading. When measuring an article’s coordinate, multiply each term entry by the direction’s loading for that term, then add the products. When reconstructing an article, multiply that whole direction by the article’s coordinate on it. A loading’s sign determines which pole of the direction it supports; its magnitude measures strength within this numerical representation. Neither alone is a probability that a document concerns a subject. A word list is a reading aid extracted from the direction, not a replacement for its full vector.
The small factorization can be computed directly. The real document–term table needs two additional ideas: applying a centered table without storing it, and finding its leading directions through a much smaller working space. We develop them separately.
For this calculation, has document rows and term columns, is its reference mean, and has entries. Forming would turn many absent-term zeros into negative mean values and destroy sparsity. We can still calculate a product involving without storing those changed cells.
Let count a small number of working columns, let (capital omega) be any matrix, and let be . Each column of is an input direction. Expand the centered product using the rule that multiplication distributes over subtraction:
Associativity lets us change the grouping in the last product without changing its order. Compute the small row first, then repeat that row times using . For the transposed operation, apply the same reasoning. The resulting identities are
The results have shapes and . In the second correction, adds each column of over observations; multiplying those column totals by constructs the needed adjustment. Each correction is an outer product, of rank at most one, because all its columns are scalar multiples of the same column. The sparse is used as is; the centered dense matrix need never be stored. The notebook verifies both identities against a directly centered small table before using them in the larger algorithm.
A matrix is far too large for a full classical SVD here, but only the top 60 directions are wanted. The method of Halko, Martinsson and Tropp approximates them with repeated matrix products. Draw a random matrix : working columns provide desired directions plus 20 extra directions for approximation. Each random column mixes many input features; applying gives one corresponding mixture of output directions. The resulting table is called a sketch: a smaller collection of vectors with which to explore the large matrix’s output space. The extra columns are oversampling, a margin for approximation rather than extra final news axes.
The range of a matrix is the set of outputs it can produce. The goal is for the sketch’s span to cover the most important part of that range. Random combinations can capture the leading directions well when the singular values decay sufficiently; the method offers an approximation whose quality must still be assessed.
To orthonormalise is to replace spanning vectors by perpendicular unit vectors spanning the same space. Here is one step of the Gram–Schmidt idea used to explain that operation. Take columns and . First normalize to the unit column . The scalar measures how much of already lies along . The corresponding vector contribution is .
Subtract that contribution from . The residual is and has dot product zero with . Normalize it to get . The columns now have unit lengths and zero mutual dot product, while their combinations still reach the same plane as . If the residual were zero, the new input would add no independent direction and should be skipped. Practical routines also address floating-point accuracy, often with repeated orthogonalization or other stable factorizations. The notebook checks the small construction directly.
Two rounds of power iteration amplify stronger singular directions relative to weaker ones. The update means replace by that product. The left arrow denotes assignment: calculate the right side using the current , then store the result as the next .
Why does this help? A left singular direction with scale receives a factor when mapped back by and another factor when mapped forward by . Its coefficient is multiplied by . In the rectangular diagonal example the two factors are 9 and 4, so the stronger contribution gains relative to the weaker. Orthonormalising between rounds prevents all the stored columns from merely growing huge and becoming numerically indistinguishable. The calculation applies two products in sequence; it does not form a huge matrix.
Call the final orthonormal working matrix . Its columns describe a smaller output space in which to seek the answer. The product expresses every original feature column in those working coordinates and has shape . Compute an SVD of that smaller table. Its left directions have entries; multiplying them by returns them to the original -entry output space. Retain the desired directions. If a sketch has fewer than independent columns, the working dimension is reduced accordingly.
This gives an approximate truncated SVD of . Weighted fitting applies the same method to . Each sparse product touches the nonzero entries once. On the reported laptop the first LSA fit, including tokenising 1.6 GB of text twice, takes about five minutes. A fixed random seed, input order, and numerical procedure make the computation reproducible. For teaching, the notebooks use the same explicitly specified four-column sketch in both languages, so differences in random-number generators cannot hide disagreements in the algebra.