Module contents
Lesson 15 of 25Core 110 min

The singular value decomposition

Any matrix, of any shape, is a rotation, an axiswise scaling and another rotation. Construct the SVD from the spectral theorem, interpret it geometrically, obtain paired orthonormal bases for the four fundamental subspaces, and derive the polar decomposition used to align point clouds. This is the central lesson of the module.

After this lesson you can

  • Prove the existence of the SVD of any real matrix using the spectral decomposition of AᵀA.
  • Interpret U, Σ and V geometrically as rotation, axiswise scaling and rotation.
  • Obtain orthonormal bases for the four fundamental subspaces from the SVD.
  • Distinguish full, reduced and truncated SVDs and relate singular values to eigenvalues.
  • Compute the polar decomposition and solve the orthogonal Procrustes problem (Kabsch).

Before you start

Motivation: one factorization for every matrix

The factorizations you have seen so far come with conditions. Diagonalization A=PΛP−1\mat{A} = \mat{P}\mat{\Lambda}\mat{P}\inv requires a square matrix with an eigenvector basis, and that basis is almost never orthogonal. The spectral theorem does give an orthonormal basis, but only for symmetric matrices. Matrices you actually work with need not satisfy either condition: a data matrix X∈Rn×d\mat{X} \in \R^{n\times d} is rectangular, as is a layer W∈Rdout×din\mat{W} \in \R^{d_{\text{out}}\times d_{\text{in}}}, and a matrix of user ratings by product need be neither square nor symmetric.

Singular value decomposition (SVD) has no such conditions. Every real matrix A∈Rm×n\mat{A} \in \R^{m\times n} can be written as

A=UΣV⊤,\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T,

with U\mat{U} and V\mat{V} orthogonal and Σ\mat{\Sigma} diagonal with nonnegative entries. As a transformation: rotate (or reflect), stretch each axis separately, and rotate again. In suitable bases, one for input and another for output, any linear map is diagonal.

This is why it appears throughout your map:

  • Data. Principal component analysis is the SVD of the centered data matrix; latent semantic analysis is the SVD of a term-by-document matrix.
  • Low rank. Truncating the SVD gives the best rank-kk approximation (Eckart–Young, in lesson 17). This is the idea LoRA exploits to adapt a language model with low-rank updates BA\mat{B}\mat{A}.
  • Numerics. The pseudoinverse, condition number, and spectral norm can be read directly from Σ\mat{\Sigma}.
  • Geometry and robotics. Kabsch alignment, which estimates rotation between two 3D point clouds (scan registration, object pose, SLAM), is an SVD of 3×33\times 3.
  • Optimization. The Muon optimizer replaces each matrix update by an approximation of its polar factor UV⊤\mat{U}\mat{V}\T, which you will construct in this lesson, computed with Newton–Schulz iteration.
  • Interpretability. In an attention head, product WOWV\mat{W}_O\mat{W}_V (its OV circuit) is a matrix of dmodel×dmodeld_{\text{model}}\times d_{\text{model}} with rank at most dkd_k. Its SVD says which residual-stream directions the head reads (vi\vb{v}_i), which it writes (ui\vb{u}_i), and with what gain (σi\sigma_i).

In this lesson you will construct the SVD from the spectral theorem, view its geometry, read the four fundamental subspaces from it, compare it with eigenvalues, and derive the polar decomposition, which solves the problem of aligning two point clouds.

Intuition: a circle maps to an ellipse

Start with the simplest nonsymmetric matrix, a shear

A=[1101].\mat{A} = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}.

Both eigenvalues equal 11 and it has only one invariant line (the xx axis): diagonalization is a lost cause. Instead, look at what it does to the unit circle. Each point (cos⁡α,sin⁡α)(\cos\alpha, \sin\alpha) maps to (cos⁡α+sin⁡α,sin⁡α)(\cos\alpha + \sin\alpha, \sin\alpha), and the set of images is a tilted ellipse. Its semiaxes measure φ=(1+5)/2≈1.618\varphi = (1 + \sqrt{5})/2 \approx 1.618 and 1/φ≈0.6181/\varphi \approx 0.618: the golden ratio appears in a shear.

Two facts in that figure are the heart of the lesson:

  1. The major semiaxis is the point of the ellipse farthest from the origin, so its length is the maximum stretch max⁡∥x∥=1∥Ax∥\max_{\norm{\vb{x}} = 1}\norm{\mat{A}\vb{x}}. The minor semiaxis is the minimum.
  2. The two points on the circle that map to the semiaxes, call them v1\vb{v}_1 and v2\vb{v}_2, are perpendicular. The shear distorts almost every right angle in the plane, but preserves this one: Av1⊥Av2\mat{A}\vb{v}_1 \perp \mat{A}\vb{v}_2.
InteractiveSVD as rotation, stretch, and rotation
Drag the columns of A\mat{A} (orange and aquamarine) and observe the image ellipse: vectors v1,v2\vb{v}_1, \vb{v}_2 (dashed, on the circle) are perpendicular and map to semiaxes σ1u1,σ2u2\sigma_1\vb{u}_1, \sigma_2\vb{u}_2, also perpendicular. Press play: V⊤\mat{V}\T rotates v1,v2\vb{v}_1, \vb{v}_2 onto the axes, Σ\mat{\Sigma} stretches each axis, and U\mat{U} rotates the ellipse into place. Move point x\vb{x}: the curve below shows ∥Ax∥\norm{\mat{A}\vb{x}} oscillating between σ2\sigma_2 and σ1\sigma_1 and reaching those values exactly at ±v2\pm\vb{v}_2 and ±v1\pm\vb{v}_1. Also try negative determinant and rank 1.

If you know v1,v2\vb{v}_1, \vb{v}_2 and the lengths σ1,σ2\sigma_1, \sigma_2 of their images, the entire matrix is described in three steps:

  • V⊤x\mat{V}\T\vb{x} computes the coordinates of x\vb{x} in orthonormal basis v1,v2\vb{v}_1, \vb{v}_2: a rotation (or reflection) taking vi\vb{v}_i to ei\vb{e}_i.
  • Σ\mat{\Sigma} multiplies coordinate ii by σi\sigma_i: an axiswise stretch, with no mixing.
  • U\mat{U} builds the result in orthonormal basis u1,u2\vb{u}_1, \vb{u}_2 of semiaxis directions.

Notice the ∥Ax∥\norm{\mat{A}\vb{x}} curve in the interactive: it has exactly two maxima and two minima per turn, separated by a quarter turn. This is not a coincidence specific to the shear. Squared stretch, ∥Ax∥2=x⊤A⊤Ax\norm{\mat{A}\vb{x}}^2 = \vb{x}\T\mat{A}\T\mat{A}\vb{x}, is a quadratic form, and its extrema on the unit sphere are at the eigenvectors of its matrix, which is symmetric and thus has orthogonal eigenvectors. That is the whole proof.

Construction: SVD follows from the spectral theorem

The matrix controlling stretches is A⊤A∈Rn×n\mat{A}\T\mat{A} \in \R^{n\times n}, the Gram matrix of the columns of A\mat{A}. It has two familiar properties:

  • It is symmetric: (A⊤A)⊤=A⊤A(\mat{A}\T\mat{A})\T = \mat{A}\T\mat{A}. By the spectral theorem, it has an orthonormal eigenvector basis v1,…,vn\vb{v}_1, \dots, \vb{v}_n with real eigenvalues λ1≥⋯≥λn\lambda_1 \ge \dots \ge \lambda_n.
  • It is positive semidefinite: x⊤A⊤Ax=∥Ax∥2≥0\vb{x}\T\mat{A}\T\mat{A}\vb{x} = \norm{\mat{A}\vb{x}}^2 \ge 0, so all λi≥0\lambda_i \ge 0 (positive definite matrices).

The key calculation is the inner product of two images:

(Avi)⊤(Avj)=vi⊤(A⊤Avj)=λj vi⊤vj={λii=j0i≠j.(\mat{A}\vb{v}_i)\T(\mat{A}\vb{v}_j) = \vb{v}_i\T(\mat{A}\T\mat{A}\vb{v}_j) = \lambda_j\,\vb{v}_i\T\vb{v}_j = \begin{cases} \lambda_i & i = j \\ 0 & i \ne j. \end{cases}

The images of the eigenvectors of A⊤A\mat{A}\T\mat{A} are mutually orthogonal, and the image of vi\vb{v}_i has length λi\sqrt{\lambda_i}. That is the perpendicularity seen in the ellipse. It remains to normalize.

Before reading the written proof, construct it yourself. Each step has a typical trap.

ProofConstructing the SVD
Prove: Every A∈Rm×n\mat{A} \in \R^{m\times n} admits a factorization A=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T with U,V\mat{U}, \mat{V} orthogonal and Σ\mat{\Sigma} diagonal and nonnegative.
0
Let A∈Rm×n\mat{A} \in \R^{m\times n} be arbitrary. Do not assume it is square or full rank.

Step 1 of 5. Which matrix do you diagonalize, and using which theorem?

Proof

By the spectral theorem, A⊤A=VΛV⊤\mat{A}\T\mat{A} = \mat{V}\mat{\Lambda}\mat{V}\T with V∈Rn×n\mat{V} \in \R^{n\times n} orthogonal and λ1≥⋯≥λn\lambda_1 \ge \dots \ge \lambda_n. Since λi=∥Avi∥2≥0\lambda_i = \norm{\mat{A}\vb{v}_i}^2 \ge 0, define σi=λi\sigma_i = \sqrt{\lambda_i}. Let rr be the number of λi>0\lambda_i > 0; for i≤ri \le r define ui=Avi/σi\vb{u}_i = \mat{A}\vb{v}_i/\sigma_i, which are orthonormal by calculation (Avi)⊤(Avj)=λjδij(\mat{A}\vb{v}_i)\T(\mat{A}\vb{v}_j) = \lambda_j\delta_{ij}. For i>ri > r, ∥Avi∥2=λi=0\norm{\mat{A}\vb{v}_i}^2 = \lambda_i = 0 and Avi=0\mat{A}\vb{v}_i = \vb{0}.

Since the u1,…,ur\vb{u}_1, \dots, \vb{u}_r are rr orthonormal vectors in Rm\R^m, r≤mr \le m; extend them to an orthonormal basis u1,…,um\vb{u}_1, \dots, \vb{u}_m and call U\mat{U} the matrix with them as columns. Let Σ∈Rm×n\mat{\Sigma} \in \R^{m\times n} with Σii=σi\Sigma_{ii} = \sigma_i for i≤ri \le r and zeros elsewhere. Then column ii of UΣ\mat{U}\mat{\Sigma} is σiui=Avi\sigma_i\vb{u}_i = \mat{A}\vb{v}_i if i≤ri \le r and 0=Avi\vb{0} = \mat{A}\vb{v}_i if i>ri > r, that is, UΣ=AV\mat{U}\mat{\Sigma} = \mat{A}\mat{V}, and multiplying on the right by V⊤\mat{V}\T gives A=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T.

Finally, rank⁡A=rank⁡(UΣV⊤)=rank⁡Σ=r\rank\mat{A} = \rank(\mat{U}\mat{\Sigma}\mat{V}\T) = \rank\mat{\Sigma} = r, because multiplication by invertible matrices does not change rank.

∎

Uniqueness. Singular values are determined by A\mat{A} (they are square roots of eigenvalues of A⊤A\mat{A}\T\mat{A}, as you will prove for any SVD in the exercises). Singular vectors are not completely determined:

  • Each pair (ui,vi)(\vb{u}_i, \vb{v}_i) can change sign together: A(−vi)=σi(−ui)\mat{A}(-\vb{v}_i) = \sigma_i(-\vb{u}_i).
  • If a singular value is repeated, any orthonormal basis of its subspace works (with the corresponding u\vb{u}). In the extreme case, orthogonal A=Q\mat{A} = \mat{Q} has σ1=⋯=σn=1\sigma_1 = \dots = \sigma_n = 1 and any orthogonal V\mat{V} works, with U=QV\mat{U} = \mat{Q}\mat{V}.
  • The ui\vb{u}_i with i>ri > r are determined only as a basis of col⁡(A)⊥\col(\mat{A})^\perp.

If the nonzero σi\sigma_i are distinct, that is all: each pair (ui,vi)(\vb{u}_i, \vb{v}_i) with σi>0\sigma_i > 0 is unique up to a common sign.

Proof

Write x=Vc\vb{x} = \mat{V}\vb{c}, with ∥c∥=∥x∥=1\norm{\vb{c}} = \norm{\vb{x}} = 1 because V\mat{V} is orthogonal. Then ∥Ax∥2=∥UΣc∥2=∥Σc∥2=∑i=1pσi2ci2\norm{\mat{A}\vb{x}}^2 = \norm{\mat{U}\mat{\Sigma}\vb{c}}^2 = \norm{\mat{\Sigma}\vb{c}}^2 = \sum_{i=1}^{p}\sigma_i^2 c_i^2, a weighted average of the σi2\sigma_i^2 (with weights ci2c_i^2 summing to at most 1, and exactly 1 if m≥nm \ge n). A weighted average lies between the smallest and largest values: maximum σ12\sigma_1^2 is attained with c=±e1\vb{c} = \pm\vb{e}_1 and, if m≥nm \ge n, minimum σn2\sigma_n^2 with c=±en\vb{c} = \pm\vb{e}_n. This is the Rayleigh quotient of A⊤A\mat{A}\T\mat{A} in another form.

∎

The maximum σ1\sigma_1 is the spectral norm ∥A∥2\norm{\mat{A}}_2, the subject of the next lesson. If m<nm < n, the minimum on the sphere is 0 because A\mat{A} has a kernel: a wide matrix always collapses some direction.

Geometry: rotate, stretch along axes, rotate

Read Ax=UΣV⊤x\mat{A}\vb{x} = \mat{U}\mat{\Sigma}\mat{V}\T\vb{x} from right to left, as in the first interactive:

  1. c=V⊤x\vb{c} = \mat{V}\T\vb{x}: coordinates of x\vb{x} in basis v1,…,vn\vb{v}_1, \dots, \vb{v}_n. It is an isometry of Rn\R^n: a rotation if det⁡V=1\det\mat{V} = 1, a rotation followed by reflection if det⁡V=−1\det\mat{V} = -1.
  2. Σc=(σ1c1,…,σpcp,0,… )\mat{\Sigma}\vb{c} = (\sigma_1 c_1, \dots, \sigma_p c_p, 0, \dots): stretches each coordinate by its factor and, if m≠nm \ne n, adds or removes coordinates (moving from Rn\R^n to Rm\R^m).
  3. U(Σc)\mat{U}(\mat{\Sigma}\vb{c}): places the result in basis u1,…,um\vb{u}_1, \dots, \vb{u}_m of Rm\R^m.

The image of the unit sphere of Rn\R^n is therefore an ellipsoid (possibly flattened) with semiaxes σiui\sigma_i\vb{u}_i. In coordinates: if y=Ax\vb{y} = \mat{A}\vb{x} with ∥x∥=1\norm{\vb{x}} = 1, then ui⊤y=σici\vb{u}_i\T\vb{y} = \sigma_i c_i and

∑i=1r(ui⊤yσi)2=∑i=1rci2≤1,ui⊤y=0 para i>r.\sum_{i=1}^{r}\left(\frac{\vb{u}_i\T\vb{y}}{\sigma_i}\right)^2 = \sum_{i=1}^{r} c_i^2 \le 1, \qquad \vb{u}_i\T\vb{y} = 0 \text{ para } i > r.

The image always lies in subspace span⁡{u1,…,ur}=col⁡(A)\spn\{\vb{u}_1, \dots, \vb{u}_r\} = \col(\mat{A}). If r=nr = n (A\mat{A} injective), the cic_i with i≤ri \le r are all the coordinates, equality is exact, and the image is the surface of an ellipsoid inside that subspace (of all Rm\R^m if also m=nm = n). If r<nr < n, coordinates cr+1,…,cnc_{r+1}, \dots, c_n are lost in the kernel, ∑i≤rci2\sum_{i \le r} c_i^2 takes all values in [0,1][0, 1], and the image is a solid ellipsoid of dimension rr: the sphere collapses onto its interior.

Two consequences for square matrices. Since ∣det⁡U∣=∣det⁡V∣=1\abs{\det\mat{U}} = \abs{\det\mat{V}} = 1,

∣det⁡A∣=σ1σ2⋯σn,\abs{\det\mat{A}} = \sigma_1\sigma_2\cdots\sigma_n ,

the volume factor is the product of the stretches. The sign of the determinant, if A\mat{A} is invertible, is det⁡U⋅det⁡V\det\mat{U}\cdot\det\mat{V}: orientation reversal comes from the orthogonal matrices, never Σ\mat{\Sigma}.

InteractiveSphere, ellipsoid, and collapse
The unit sphere (gray, with its vi\vb{v}_i) and its image under A=U diag⁡(σ1,σ2,σ3) V⊤\mat{A} = \mat{U}\,\diag(\sigma_1, \sigma_2, \sigma_3)\,\mat{V}\T, with semiaxes σiui\sigma_i\vb{u}_i. Drag to rotate the scene. Lower σ3\sigma_3 to zero: the ellipsoid flattens into an ellipse within the plane col⁡(A)\col(\mat{A}), the kernel line (that of v3\vb{v}_3) appears in red and the left-kernel line (that of u3\vb{u}_3) in gray, and volume σ1σ2σ3\sigma_1\sigma_2\sigma_3 vanishes. Lower σ2\sigma_2 too to reach rank 1. In 3×23\times 2 mode, the domain is R2\R^2 (panel inset) and the image is always flat, whatever you move.

The SVD and the four subspaces

In the rank lesson you saw the four fundamental subspaces and that Rn=row⁡(A)⊕null⁡(A)\R^n = \row(\mat{A}) \oplus \nullsp(\mat{A}) and Rm=col⁡(A)⊕null⁡(A⊤)\R^m = \col(\mat{A}) \oplus \nullsp(\mat{A}\T), with orthogonal sums. The SVD gives orthonormal bases for all four at once, and paired.

Proof

For i>ri > r, Avi=0\mat{A}\vb{v}_i = \vb{0}, so vr+1,…,vn∈null⁡(A)\vb{v}_{r+1}, \dots, \vb{v}_n \in \nullsp(\mat{A}). There are n−rn - r orthonormal vectors and dim⁡null⁡(A)=n−r\dim\nullsp(\mat{A}) = n - r by the rank–nullity theorem: they form a basis. Their orthogonal complement in Rn\R^n is span⁡{v1,…,vr}\spn\{\vb{v}_1, \dots, \vb{v}_r\} and also null⁡(A)⊥=row⁡(A)\nullsp(\mat{A})^\perp = \row(\mat{A}).

For i≤ri \le r, ui=A(vi/σi)∈col⁡(A)\vb{u}_i = \mat{A}(\vb{v}_i/\sigma_i) \in \col(\mat{A}); these are rr orthonormal vectors in a space of dimension rr: a basis. Their orthogonal complement in Rm\R^m is span⁡{ur+1,…,um}=col⁡(A)⊥=null⁡(A⊤)\spn\{\vb{u}_{r+1}, \dots, \vb{u}_m\} = \col(\mat{A})^\perp = \nullsp(\mat{A}\T). Relation A⊤ui=σivi\mat{A}\T\vb{u}_i = \sigma_i\vb{v}_i follows by transposing: A⊤=VΣ⊤U⊤\mat{A}\T = \mat{V}\mat{\Sigma}\T\mat{U}\T.

∎

The example illustrates a practical trick: if m<nm < n, diagonalize AA⊤\mat{A}\mat{A}\T (of m×mm\times m) and obtain the vi\vb{v}_i as A⊤ui/σi\mat{A}\T\vb{u}_i/\sigma_i; if m>nm > n, reverse the procedure.

This view of A\mat{A} (diagonal between row⁡(A)\row(\mat{A}) and col⁡(A)\col(\mat{A}), zero on null⁡(A)\nullsp(\mat{A})) leads directly to the pseudoinverse, A+=VΣ+U⊤\mat{A}\pinv = \mat{V}\mat{\Sigma}\pinv\mat{U}\T, which inverts what is invertible (σi↦1/σi\sigma_i \mapsto 1/\sigma_i) and zeros the rest; you will study it in lesson 18. It also explains rank in practice: in floating point no σi\sigma_i is exactly zero, and deciding how many are “really zero” is the problem of numerical rank (lesson 17).

Full, reduced, and truncated

The full SVD carries columns that do nothing. If m>nm > n, rows n+1,…,mn + 1, \dots, m of Σ\mat{\Sigma} are zero and columns un+1,…,um\vb{u}_{n+1}, \dots, \vb{u}_m of U\mat{U} are multiplied by zero. Removing them loses nothing.

Each term σiuivi⊤\sigma_i\vb{u}_i\vb{v}_i\T is rank one: all its columns are multiples of ui\vb{u}_i and all its rows multiples of vi⊤\vb{v}_i\T. The terms are mutually orthogonal under the Frobenius inner product, ⟨X,Y⟩F=tr⁡(X⊤Y)\inner{\mat{X}}{\mat{Y}}_F = \tr(\mat{X}\T\mat{Y}):

⟨uivi⊤,ujvj⊤⟩F=tr⁡(viui⊤ujvj⊤)=(ui⊤uj)(vj⊤vi)=δij.\inner{\vb{u}_i\vb{v}_i\T}{\vb{u}_j\vb{v}_j\T}_F = \tr(\vb{v}_i\vb{u}_i\T\vb{u}_j\vb{v}_j\T) = (\vb{u}_i\T\vb{u}_j)(\vb{v}_j\T\vb{v}_i) = \delta_{ij}.

By Pythagoras, the Frobenius norm is distributed among the layers:

∥A∥F2=∑i=1rσi2,∥A−∑i∈Sσiuivi⊤∥F2=∑i∉Sσi2.\norm{\mat{A}}_F^2 = \sum_{i=1}^{r}\sigma_i^2, \qquad \norm{\mat{A} - \textstyle\sum_{i \in S}\sigma_i\vb{u}_i\vb{v}_i\T}_F^2 = \sum_{i \notin S}\sigma_i^2 .

Keeping the first kk terms gives the truncated SVD Ak=∑i≤kσiuivi⊤\mat{A}_k = \sum_{i \le k}\sigma_i\vb{u}_i\vb{v}_i\T, with Frobenius error σk+12+⋯+σr2\sqrt{\sigma_{k+1}^2 + \dots + \sigma_r^2}. That no rank-kk matrix lies closer to A\mat{A} is the Eckart–Young theorem, the subject of lesson 17 (low-rank approximation). Storing Ak\mat{A}_k costs k(m+n+1)k(m + n + 1) numbers rather than mnmn.

InteractiveThe matrix as a sum of rank-one layers
A ratings matrix (8 users by 6 films, three action A and three drama D, minus 3 for centering) and its six layers σiuivi⊤\sigma_i\vb{u}_i\vb{v}_i\T. Each layer is bar ui\vb{u}_i (how much the factor weighs for each user) times bar vi⊤\vb{v}_i\T (how much each film has of that factor). Turn layers on and off: measured error ∥A−A^∥F\norm{\mat{A} - \hat{\mat{A}}}_F always matches the square root of the disabled σi2\sigma_i^2 terms, whatever the combination. The first layer separates action from drama; the first two already capture 92% of the energy.

The first layer illustrates factorization-based recommendation: v1\vb{v}_1 has opposite signs for action films and dramas, and u1\vb{u}_1 indicates which users prefer each type. The second layer has v2\vb{v}_2 with all entries of the same sign: a factor common to all films, more like user “generosity” or film quality. Nobody told the SVD there were genres: it found them because they explain most of ∥A∥F2\norm{\mat{A}}_F^2. At the end of the lesson you will do the same with a matrix of 300×36300\times 36.

Singular values versus eigenvalues

For a square matrix you now have two decompositions, and they are easy to confuse. They solve different problems:

Eigenvalues: Ax=λx\mat{A}\vb{x} = \lambda\vb{x}Singular values: Av=σu\mat{A}\vb{v} = \sigma\vb{u}
Existenceonly if A\mat{A} is square; may be complex or fail to give a basisalways, for any shape
Vectorsinvariant: Ax\mat{A}\vb{x} lies on the same lineorthogonal at input and output, but Avi\mat{A}\vb{v}_i changes direction
Basisgenerally nonorthogonalorthonormal, two distinct bases
Usepowers At\mat{A}^t, dynamics xt+1=Axt\vb{x}_{t+1} = \mat{A}\vb{x}_tsizes: norms, rank, conditioning, approximation

The shear is an extreme example: λ1=λ2=1\lambda_1 = \lambda_2 = 1 but σ=φ,1/φ\sigma = \varphi, 1/\varphi. A rotation through angle θ\theta has λ=e±iθ\lambda = e^{\pm i\theta} (complex) and σ1=σ2=1\sigma_1 = \sigma_2 = 1. What is related in general:

Proof

The first equality is det⁡A=∏λi\det\mat{A} = \prod\lambda_i; the second is ∣det⁡A∣=∣det⁡U∣det⁡Σ∣det⁡V∣\abs{\det\mat{A}} = \abs{\det\mat{U}}\det\mat{\Sigma}\abs{\det\mat{V}}. For the bound, take a unit eigenvector x∈Cn\vb{x} \in \C^n of λi\lambda_i: ∣λi∣=∥Ax∥\abs{\lambda_i} = \norm{\mat{A}\vb{x}}. The stretch proposition’s argument works identically in Cn\C^n (with complex c=V⊤x\vb{c} = \mat{V}\T\vb{x}, ∥Ax∥2=∑σi2∣ci∣2\norm{\mat{A}\vb{x}}^2 = \sum\sigma_i^2\abs{c_i}^2), so σn≤∥Ax∥≤σ1\sigma_n \le \norm{\mat{A}\vb{x}} \le \sigma_1.

∎

In particular the spectral radius never exceeds σ1\sigma_1: ρ(A)≤∥A∥2\rho(\mat{A}) \le \norm{\mat{A}}_2. The inequality can be very loose, with consequences. With

A=[0.51000.5],ρ(A)=0.5,σ1≈10.02,\mat{A} = \begin{bmatrix} 0.5 & 10 \\ 0 & 0.5 \end{bmatrix}, \qquad \rho(\mat{A}) = 0.5, \qquad \sigma_1 \approx 10.02,

the dynamical system xt+1=Axt\vb{x}_{t+1} = \mat{A}\vb{x}_t eventually reaches zero because ρ<1\rho < 1, but grows first: ∥At∥2\norm{\mat{A}^t}_2 is about 10 at t=1t = 1 and t=2t = 2 and does not drop below 1 until t=8t = 8. Eigenvalues describe long-term behavior; singular values describe what happens at each step. This distinction matters when studying exploding gradients in recurrent networks (spectral conditions in RNNs).

When they agree. If A\mat{A} is symmetric, A=QΛQ⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T and it suffices to move the signs:

A=∑iλiqiqi⊤=∑i∣λi∣ (sgn⁡(λi)qi)qi⊤,\mat{A} = \sum_i\lambda_i\vb{q}_i\vb{q}_i\T = \sum_i\abs{\lambda_i}\,\big(\operatorname{sgn}(\lambda_i)\vb{q}_i\big)\vb{q}_i\T ,

which is an SVD with σi=∣λi∣\sigma_i = \abs{\lambda_i} (reordered), vi=qi\vb{v}_i = \vb{q}_i and ui=±qi\vb{u}_i = \pm\vb{q}_i (if λi=0\lambda_i = 0, the sign is free: take ui=qi\vb{u}_i = \vb{q}_i). If it is also positive semidefinite, ui=vi\vb{u}_i = \vb{v}_i and the two decompositions coincide. More generally, σi=∣λi∣\sigma_i = \abs{\lambda_i} for every normal matrix (A⊤A=AA⊤\mat{A}\T\mat{A} = \mat{A}\mat{A}\T), such as rotations, because they admit an orthonormal basis of complex eigenvectors (a unitary matrix diagonalizes them). Nonnormality is exactly what separates the two sets of numbers.

InteractiveSingular vectors versus eigenvectors
In orange, eigenvectors xi\vb{x}_i (dashed) and their images λixi\lambda_i\vb{x}_i, on the same line; in blue, vi\vb{v}_i (dashed) and their images σiui\sigma_i\vb{u}_i. For the starting matrix, eigenvectors form about 56°56° and the vi\vb{v}_i are perpendicular, but Av1\mat{A}\vb{v}_1 departs from the line of v1\vb{v}_1. Increase symmetrization ss: at s=1s = 1 the sets agree up to sign and σi=∣λi∣\sigma_i = \abs{\lambda_i}. Try the shear (one invariant line), complex eigenvalues (none), and very nonnormal (∣λ∣=0.5\abs{\lambda} = 0.5 with σ1≈1.93\sigma_1 \approx 1.93). The SVD always exists.

Polar decomposition: rotate and stretch

A nonzero complex number is z=eiθrz = e^{i\theta}r: a rotation times a positive stretch. The SVD gives the matrix analogue by regrouping factors:

A=UΣV⊤=(UV⊤)(VΣV⊤).\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T = (\mat{U}\mat{V}\T)(\mat{V}\mat{\Sigma}\mat{V}\T).

The factor S\mat{S} is always unique: A⊤A=SQ⊤QS=S2\mat{A}\T\mat{A} = \mat{S}\mat{Q}\T\mat{Q}\mat{S} = \mat{S}^2, and a positive semidefinite matrix has a unique positive semidefinite square root. If A\mat{A} is invertible, S\mat{S} is too and Q=AS−1\mat{Q} = \mat{A}\mat{S}\inv is determined. Geometrically: first a pure stretch along axes vi\vb{v}_i (no net rotation), then a rigid movement. For the shear,

[1101]=15[21−12]⏟Q: giro de −26.57° 15[2113]⏟S.\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix} = \underbrace{\frac{1}{\sqrt{5}}\begin{bmatrix} 2 & 1 \\ -1 & 2 \end{bmatrix}}_{\mat{Q}:\ \text{giro de } -26.57°}\ \underbrace{\frac{1}{\sqrt{5}}\begin{bmatrix} 2 & 1 \\ 1 & 3 \end{bmatrix}}_{\mat{S}} .

Factor Q\mat{Q} has a characterization making it useful in its own right.

Proof

For orthogonal Q′\mat{Q}', ∥A−Q′∥F2=∥A∥F2+∥Q′∥F2−2tr⁡(Q′TA)=∥A∥F2+n−2tr⁡(Q′TA)\norm{\mat{A} - \mat{Q}'}_F^2 = \norm{\mat{A}}_F^2 + \norm{\mat{Q}'}_F^2 - 2\tr(\mat{Q}'^{\mathsf T}\mat{A}) = \norm{\mat{A}}_F^2 + n - 2\tr(\mat{Q}'^{\mathsf T}\mat{A}). We must maximize

tr⁡(Q′TUΣV⊤)=tr⁡(V⊤Q′TU Σ)=∑i=1nσizii,Z=V⊤Q′TU,\tr(\mat{Q}'^{\mathsf T}\mat{U}\mat{\Sigma}\mat{V}\T) = \tr(\mat{V}\T\mat{Q}'^{\mathsf T}\mat{U}\,\mat{\Sigma}) = \sum_{i=1}^{n}\sigma_i z_{ii}, \qquad \mat{Z} = \mat{V}\T\mat{Q}'^{\mathsf T}\mat{U},

using trace invariance under cyclic permutations. Z\mat{Z} is orthogonal, so its columns are unit vectors and zii≤1z_{ii} \le 1. Since σi≥0\sigma_i \ge 0, the sum is at most ∑σi\sum\sigma_i, with equality if Z=I\mat{Z} = \mat{I}, that is, Q′=UV⊤\mat{Q}' = \mat{U}\mat{V}\T.

∎

This is the operation Muon performs on each weight update: it replaces it with (an approximation of) the nearest orthogonal matrix, or a matrix with orthonormal columns if the layer is rectangular, with the same “direction” (U\mat{U} and V\mat{V}) but all singular values equal to 1.

Orthogonal Procrustes and the Kabsch algorithm

You have nn points x1,…,xn∈Rd\vb{x}_1, \dots, \vb{x}_n \in \R^d (for example, atoms of a molecule or corners of a part in a CAD model) and corresponding y1,…,yn\vb{y}_1, \dots, \vb{y}_n measured in another pose, with noise. You want the rigid motion that best aligns them:

min⁡R∈SO(d), t∈Rd ∑i=1n∥Rxi+t−yi∥2.\min_{\mat{R} \in SO(d),\ \vb{t} \in \R^d}\ \sum_{i=1}^{n}\norm{\mat{R}\vb{x}_i + \vb{t} - \vb{y}_i}^2 .

Translation. For fixed R\mat{R}, the problem in t\vb{t} is least squares with gradient 2∑i(Rxi+t−yi)2\sum_i(\mat{R}\vb{x}_i + \vb{t} - \vb{y}_i), which vanishes at t=yˉ−Rxˉ\vb{t} = \bar{\vb{y}} - \mat{R}\bar{\vb{x}} (the means). Substitution reduces the problem to rotation with centered data, xi−xˉ\vb{x}_i - \bar{\vb{x}} and yi−yˉ\vb{y}_i - \bar{\vb{y}}. From here assume the data are centered.

Rotation. Expand the square as in the previous proof. Since ∥Rxi∥=∥xi∥\norm{\mat{R}\vb{x}_i} = \norm{\vb{x}_i},

∑i∥Rxi−yi∥2=∑i∥xi∥2+∑i∥yi∥2−2tr⁡(R⊤M),M=∑i=1nyixi⊤=Y⊤X,\sum_i\norm{\mat{R}\vb{x}_i - \vb{y}_i}^2 = \sum_i\norm{\vb{x}_i}^2 + \sum_i\norm{\vb{y}_i}^2 - 2\tr(\mat{R}\T\mat{M}), \qquad \mat{M} = \sum_{i=1}^{n}\vb{y}_i\vb{x}_i\T = \mat{Y}\T\mat{X},

where X,Y∈Rn×d\mat{X}, \mat{Y} \in \R^{n\times d} have one point per row. Minimizing error means maximizing tr⁡(R⊤M)\tr(\mat{R}\T\mat{M}), the same problem as finding the nearest orthogonal matrix, now with M\mat{M} in the role of A\mat{A}. If only orthogonal R\mat{R} were required (the orthogonal Procrustes problem, solved generally by Schönemann, 1966), the answer would be the polar factor of M\mat{M}: with M=UΣV⊤\mat{M} = \mat{U}\mat{\Sigma}\mat{V}\T, R=UV⊤\mat{R} = \mat{U}\mat{V}\T.

The determinant trap. UV⊤\mat{U}\mat{V}\T is orthogonal, but may have determinant −1-1: a reflection. This happens when data are reflected (a molecule and its enantiomer, a point cloud with an axis reversed by a convention error) and also, with much noise or nearly coplanar points, when nothing is reflected. A reflection is not a proper rigid motion. The Kabsch algorithm (1976), with the improper case discussed in Kabsch (1978), resolves this by changing the sign of the last pair:

Proof

As before, tr⁡(R⊤M)=∑iσizii\tr(\mat{R}\T\mat{M}) = \sum_i\sigma_i z_{ii} with Z=V⊤R⊤U\mat{Z} = \mat{V}\T\mat{R}\T\mat{U} orthogonal and det⁡Z=det⁡R⋅det⁡(UV⊤)=s\det\mat{Z} = \det\mat{R}\cdot\det(\mat{U}\mat{V}\T) = s. If s=1s = 1, Z=I\mat{Z} = \mat{I} is admissible and gives the absolute maximum. If s=−1s = -1, maximize ∑iσizii\sum_i\sigma_i z_{ii} over orthogonal Z\mat{Z} with det⁡Z=−1\det\mat{Z} = -1. Write

∑i=1dσizii=∑i<d(σi−σd) zii+σd tr⁡Z.\sum_{i=1}^{d}\sigma_i z_{ii} = \sum_{i<d}(\sigma_i - \sigma_d)\,z_{ii} + \sigma_d\,\tr\mat{Z}.

The first term is at most ∑i<d(σi−σd)\sum_{i<d}(\sigma_i - \sigma_d), because zii≤1z_{ii} \le 1 and σi−σd≥0\sigma_i - \sigma_d \ge 0. For the second: eigenvalues of an orthogonal matrix have magnitude 1, nonreal ones come in conjugate pairs (with product 1), and real ones are ±1\pm 1; since their product is det⁡Z=−1\det\mat{Z} = -1, one equals −1-1. The trace is the sum of real parts, so tr⁡Z≤−1+(d−1)=d−2\tr\mat{Z} \le -1 + (d - 1) = d - 2. Adding gives ∑iσizii≤∑i<dσi−(d−1)σd+(d−2)σd=∑i<dσi−σd\sum_i\sigma_i z_{ii} \le \sum_{i<d}\sigma_i - (d-1)\sigma_d + (d-2)\sigma_d = \sum_{i<d}\sigma_i - \sigma_d, attained with Z=diag⁡(1,…,1,−1)\mat{Z} = \diag(1, \dots, 1, -1). Undoing the change gives R⋆=UZV⊤\mat{R}^\star = \mat{U}\mat{Z}\mat{V}\T.

∎

Notice what is sacrificed: pair (ud,vd)(\vb{u}_d, \vb{v}_d) for the smallest singular value, the direction in which the data provide the least information about rotation.

In the plane everything is visible. With Rθ\mat{R}_\theta the rotation through angle θ\theta, tr⁡(Rθ⊤M)=(M11+M22)cos⁡θ+(M21−M12)sin⁡θ\tr(\mat{R}_\theta\T\mat{M}) = (M_{11} + M_{22})\cos\theta + (M_{21} - M_{12})\sin\theta: error is a sinusoid in θ\theta, with a unique minimum at θ⋆=atan2⁡(M21−M12, M11+M22)\theta^\star = \operatorname{atan2}(M_{21} - M_{12},\ M_{11} + M_{22}). Reflections RθF\mat{R}_\theta\mat{F}, with F=diag⁡(1,−1)\mat{F} = \diag(1, -1), form another family with their own sinusoid; uncorrected SVD chooses the minimum of the two curves, Kabsch stays on the first.

InteractiveAligning two point clouds
The blue cloud is a rotated, noisy letter F; orange is the model, rotated by θ\theta. Gray segments are residuals and the curve below is total error at each angle: a sinusoid. Press Kabsch to jump to the optimal rotation, computed with the SVD of M=∑iyixi⊤\mat{M} = \sum_i\vb{y}_i\vb{x}_i\T. Then choose rotated and reflected: the dashed reflection curve now goes lower than the rotation curve, det⁡(UV⊤)=−1\det(\mat{U}\mat{V}\T) = -1 and the polar factor fits better, but produces a mirror-image F that no rotation yields. Kabsch keeps the best rotation.

If a scale is also allowed, yi≈cRxi+t\vb{y}_i \approx c\mat{R}\vb{x}_i + \vb{t}, the same SVD gives the solution with c=tr⁡(ΣD)/∑i∥xi∥2c = \tr(\mat{\Sigma}\mat{D})/\sum_i\norm{\vb{x}_i}^2, where D=diag⁡(1,…,1,s)\mat{D} = \diag(1, \dots, 1, s) (Umeyama, 1991). In robotics and vision, Kabsch is the inner step of ICP, which alternates matching each point to its nearest neighbor and solving this problem.

Implementation from scratch

First, the SVD as constructed above: diagonalize A⊤A\mat{A}\T\mat{A}, take square roots, construct ui=Avi/σi\vb{u}_i = \mat{A}\vb{v}_i/\sigma_i, and complete U\mat{U}. This is the teaching version: you will soon see why no library uses it.

[ ]SVD from the spectral theoremBrowser
import numpy as np
np.set_printoptions(precision=4, suppress=True)

def svd_eigh(A):
    """SVD completa A = U S Vᵀ a partir de eigh(AᵀA). Didáctica: pierde precisión en los σ pequeños."""
    A = np.asarray(A, dtype=float)
    m, n = A.shape
    lam, V = np.linalg.eigh(A.T @ A)          # autovalores en orden creciente
    orden = np.argsort(lam)[::-1]
    lam, V = lam[orden], V[:, orden]
    s = np.sqrt(np.clip(lam, 0.0, None))       # σᵢ = √λᵢ (los λ negativos son redondeo)
    # Por debajo de √(n·u)·σ₁ los σ que salen de AᵀA son ruido: los tratamos como ceros.
    tol = np.sqrt(max(m, n) * np.finfo(float).eps) * s[0]
    r = int(np.sum(s > tol))
    s[r:] = 0.0
    U = np.zeros((m, m))
    U[:, :r] = A @ V[:, :r] / s[:r]            # uᵢ = A vᵢ / σᵢ
    if r < m:                                  # completar con una base de col(A)^⊥ = N(Aᵀ)
        G = np.random.default_rng(0).normal(size=(m, m - r))
        Q, _ = np.linalg.qr(np.hstack([U[:, :r], G]))
        U[:, r:] = Q[:, r:]
    S = np.zeros((m, n))
    p = min(m, n)
    S[:p, :p] = np.diag(s[:p])
    return U, S, V

A = np.array([[1.0, 1.0], [0.0, 1.0]])                     # la cizalla
U, S, V = svd_eigh(A)
print("σ de la cizalla:", np.diag(S), " φ =", (1 + 5 ** 0.5) / 2)

B = np.array([[1.0, 2, 3], [2, 4, 6], [1, 0, 1], [0, 1, 1]])  # 4×3, rango 2
U, S, V = svd_eigh(B)
print("σ de B:", np.diag(S))
print("‖U S Vᵀ − B‖ =", np.abs(U @ S @ V.T - B).max())
print("‖UᵀU − I‖ =", np.abs(U.T @ U - np.eye(4)).max(), " ‖VᵀV − I‖ =", np.abs(V.T @ V - np.eye(3)).max())
print("np.linalg.svd:", np.linalg.svd(B, compute_uv=False))

The rank tolerance already reveals the problem: with A⊤A\mat{A}\T\mat{A} only singular values above u σ1≈10−8σ1\sqrt{u}\,\sigma_1 \approx 10^{-8}\sigma_1 can be distinguished, not u σ1≈10−16σ1u\,\sigma_1 \approx 10^{-16}\sigma_1 (uu is unit roundoff). The reason is that the eigenvalues of A⊤A\mat{A}\T\mat{A} are σi2\sigma_i^2: a stable algorithm computes λi\lambda_i with absolute error of order u λ1=u σ12u\,\lambda_1 = u\,\sigma_1^2, and on taking the square root the relative error of σi\sigma_i can reach order u (σ1/σi)2u\,(\sigma_1/\sigma_i)^2: squared conditioning, as in the normal equations of the QR lesson. A real SVD works on A\mat{A} and its bound is u σ1/σiu\,\sigma_1/\sigma_i:

[ ]Why SVD is not computed using AᵀABrowser
rng = np.random.default_rng(1)
Uq, _ = np.linalg.qr(rng.normal(size=(6, 4)))
Vq, _ = np.linalg.qr(rng.normal(size=(4, 4)))
s_true = np.array([1.0, 1e-3, 1e-6, 1e-9])
A = Uq @ np.diag(s_true) @ Vq.T                   # valores singulares conocidos

s_gram = np.sqrt(np.clip(np.sort(np.linalg.eigvalsh(A.T @ A))[::-1], 0, None))
s_svd = np.linalg.svd(A, compute_uv=False)
print("   σ real |   vía AᵀA   err. rel. |   np.svd    err. rel.")
for st, sg, sv in zip(s_true, s_gram, s_svd):
    print(f"{st:9.0e} | {sg:10.3e}  {abs(sg - st) / st:8.1e} | {sv:10.3e}  {abs(sv - st) / st:8.1e}")

With σ=10−6\sigma = 10^{-6}, the A⊤A\mat{A}\T\mat{A} route has already lost about ten of its sixteen digits, and σ=10−9\sigma = 10^{-9} (whose square, 10−1810^{-18}, is below the noise in u σ12≈10−16u\,\sigma_1^2 \approx 10^{-16}) is completely wrong. NumPy’s SVD recovers it with relative error of order 10−810^{-8} or less, as permitted by its absolute error of about 10−1610^{-16}.

Now Kabsch in 3D, including reflection. The function returns rotation R\mat{R} and translation t\vb{t} with yi≈Rxi+t\vb{y}_i \approx \mat{R}\vb{x}_i + \vb{t}. Watch the order: the code, like almost all implementations, decomposes H=X⊤Y=M⊤\mat{H} = \mat{X}\T\mat{Y} = \mat{M}\T, so its U\mat{U} and V\mat{V} are the text’s V\mat{V} and U\mat{U}, and the rotation is VDU⊤\mat{V}\mat{D}\mat{U}\T.

[ ]Kabsch algorithm with reflection correctionBrowser
def kabsch(X, Y):
    """Rotación R y traslación t que minimizan Σ‖R xᵢ + t − yᵢ‖² (un punto por fila)."""
    mx, my = X.mean(axis=0), Y.mean(axis=0)
    H = (X - mx).T @ (Y - my)                  # H = Xᵀ Y = Mᵀ  (d×d)
    U, s, Vt = np.linalg.svd(H)                # H = U Σ Vᵀ  ⇒  M = V Σ Uᵀ
    d = np.sign(np.linalg.det(Vt.T @ U.T))     # ±1: ¿el factor polar es una reflexión?
    D = np.diag([1.0] * (X.shape[1] - 1) + [d])
    R = Vt.T @ D @ U.T
    return R, my - R @ mx

def rotacion_aleatoria(rng):
    Q, R = np.linalg.qr(rng.normal(size=(3, 3)))
    Q = Q * np.sign(np.diag(R))
    if np.linalg.det(Q) < 0:
        Q[:, 0] *= -1
    return Q

rng = np.random.default_rng(2)
X = rng.normal(size=(50, 3)) * [3, 2, 1]
R_true, t_true = rotacion_aleatoria(rng), np.array([1.0, -2.0, 0.5])
Y = X @ R_true.T + t_true + 0.05 * rng.normal(size=X.shape)

R, t = kabsch(X, Y)
angulo = np.degrees(np.arccos(np.clip((np.trace(R.T @ R_true) - 1) / 2, -1, 1)))
print(f"error de rotación: {angulo:.3f}°   det R = {np.linalg.det(R):.6f}   error de t: {np.abs(t - t_true).max():.4f}")

# datos reflejados: Y es la imagen especular de X, girada
F = np.diag([1.0, 1.0, -1.0])
Ym = X @ (R_true @ F).T + 0.05 * rng.normal(size=X.shape)
H = (X - X.mean(0)).T @ (Ym - Ym.mean(0))
U, s, Vt = np.linalg.svd(H)
print("det del factor polar sin corregir:", round(np.linalg.det(Vt.T @ U.T), 6))
R, t = kabsch(X, Ym)
print("det de la solución de Kabsch:", round(np.linalg.det(R), 6))

The professional version: NumPy, SciPy, and PyTorch

np.linalg.svd calls LAPACK (the divide-and-conquer routine gesdd) and has three details worth knowing by heart:

  • It returns V⊤\mat{V}\T, not V\mat{V}. U, S, Vh = np.linalg.svd(A): right singular vectors are the rows of Vh. S is a 1D vector with σi\sigma_i in decreasing order, not a matrix.
  • By default, full SVD (full_matrices=True): for A\mat{A} of m×nm\times n, U is m×mm\times m and Vh is n×nn\times n. With a tall data matrix (nn examples by dd features, n≫dn \gg d), that U\mat{U} of n×nn\times n costs O(n2)\bigO(n^2) memory and is useless: use full_matrices=False (reduced). If you only need σi\sigma_i, compute_uv=False is much cheaper.
  • Reconstruction is (U[:, :p] * S) @ Vh[:p] or, for the reduced form, U @ np.diag(S) @ Vh. Multiplying U * S scales columns by broadcasting without forming the diagonal.

The cost for m≥nm \ge n is O(mn2)\bigO(mn^2): according to Trefethen and Bau (lecture 31), the dominant step, Golub–Kahan bidiagonalization, costs about 4mn2−43n34mn^2 - \tfrac{4}{3}n^3 flops, essentially the cost of obtaining only σi\sigma_i. Requesting singular vectors also keeps order O(mn2)\bigO(mn^2) but multiplies the constant (accumulating reflections and rotations costs several times more). You will see the algorithms in the numerical computation module, and the randomized version for enormous matrices in lesson 25.

In SciPy, scipy.linalg.svd supports lapack_driver="gesvd" (slower than gesdd when vectors are requested, but more robust; Octave’s default and the usual alternative when gesdd does not converge); scipy.linalg.polar(A) gives polar decomposition; scipy.linalg.orthogonal_procrustes(A, B) solves Procrustes without Kabsch correction; and scipy.spatial.transform.Rotation.align_vectors(a, b) is Kabsch with proper rotations, but aligns b onto a (argument order is opposite to the usual convention).

[ ]Library versions and their correspondenceBrowser
from scipy.linalg import polar, orthogonal_procrustes
from scipy.spatial.transform import Rotation

A = np.array([[1.0, 1.0], [0.0, 1.0]])
Q, S = polar(A)                                   # A = Q S
U, s, Vh = np.linalg.svd(A)
print("Q =\n", Q, "\n¿Q = U Vᵀ?", np.allclose(Q, U @ Vh), "  ¿S = V Σ Vᵀ?", np.allclose(S, Vh.T @ np.diag(s) @ Vh))
print("giro de Q:", np.degrees(np.arctan2(Q[1, 0], Q[0, 0])).round(2), "grados")

Xc, Ymc = X - X.mean(0), Ym - Ym.mean(0)
Ro, _ = orthogonal_procrustes(Xc, Ymc)            # minimiza ‖Xc Ro − Ymc‖: Ro = Rᵀ, sin corregir el signo
print("orthogonal_procrustes con datos reflejados: det =", round(np.linalg.det(Ro), 6))
rot, rssd = Rotation.align_vectors(Ymc, Xc)       # alinea el SEGUNDO argumento sobre el primero
print("align_vectors = Kabsch:", np.allclose(rot.as_matrix(), kabsch(X, Ym)[0]))

In PyTorch, torch.linalg.svd(A, full_matrices=False) follows NumPy’s convention and returns U, S, Vh; beware the older function torch.svd, which returns V (not transposed). Gradients through SVD exist, but contain factors 1/(σi2−σj2)1/(\sigma_i^2 - \sigma_j^2) and explode when two singular values approach each other: ambiguity of subspaces with repeated σ\sigma appears in backpropagation. If you need only σi\sigma_i, torch.linalg.svdvals is cheaper and has stable gradients.

Reading the SVD of a ratings matrix

A synthetic matrix of 300 users by 36 products (12 action, 12 comedies, 12 dramas). Each rating is the inner product of a user preference vector and a three-factor product vector (quality, action versus comedy, drama versus the rest), plus noise. The SVD does not know the factors or genres.

[ ]Latent factors in a ratings matrixBrowser
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
genero = np.repeat([0, 1, 2], 12)                  # 36 productos
nombres = ["acción", "comedia", "drama"]
calidad = rng.uniform(0.5, 1.5, genero.size)
eje_a = np.array([1.0, -1.0, 0.0])[genero]         # acción frente a comedia
eje_b = np.array([-0.5, -0.5, 1.0])[genero]        # drama frente al resto
P = np.column_stack([calidad, eje_a, eje_b])       # productos × factores (36 × 3)
G = rng.normal(size=(300, 3)) * [0.6, 1.0, 1.0] + [1.0, 0.0, 0.0]   # usuarios × factores
limpia = G @ P.T                                   # rango 3
R = limpia + 0.5 * rng.normal(size=limpia.shape)   # lo que se observa

U, s, Vt = np.linalg.svd(R, full_matrices=False)
print("primeros valores singulares:", np.round(s[:6], 1))
for k in [1, 2, 3, 4, 8]:
    Rk = (U[:, :k] * s[:k]) @ Vt[:k]
    e_obs = np.linalg.norm(R - Rk) / np.linalg.norm(R)
    e_limpia = np.linalg.norm(limpia - Rk) / np.linalg.norm(limpia)
    print(f"k = {k}: error relativo frente a R = {e_obs:.3f}   frente a la matriz limpia = {e_limpia:.3f}")
print(f"distancia relativa de R (con ruido) a la matriz limpia: {np.linalg.norm(R - limpia) / np.linalg.norm(limpia):.3f}")

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
ax[0].semilogy(np.arange(1, 21), s[:20], "o-")
ax[0].set_xlabel("$i$")
ax[0].set_title(r"valores singulares $\sigma_i$")
for g in range(3):
    ax[1].scatter(Vt[1, genero == g], Vt[2, genero == g], label=nombres[g])
ax[1].axhline(0, lw=0.8, color="0.6")
ax[1].axvline(0, lw=0.8, color="0.6")
ax[1].set_xlabel(r"$\mathbf{v}_2$")
ax[1].set_ylabel(r"$\mathbf{v}_3$")
ax[1].set_title("productos según los factores 2 y 3")
ax[1].legend()
plt.tight_layout()
plt.show()

Three singular values stand out and the rest form a flat floor: the signature of a rank-3 matrix plus noise (you will study the floor with the Marchenko–Pastur law). In the plane of v2\vb{v}_2 and v3\vb{v}_3, products group by genre without being told to, and v1\vb{v}_1 tracks quality. Notice also that the rank-3 reconstruction is closer to the clean matrix than the data themselves: truncating the SVD removed noise. Do not overinterpret: here v2\vb{v}_2 and v3\vb{v}_3 closely resemble the two genre axes used, but need not. Within the three-factor subspace, SVD chooses the orthogonal basis ordering energy, and it matches “meaningful” factors only when they are mutually orthogonal and have well-separated energies. The subspace is well determined; the basis inside it much less so.

Common mistakes

Exercises

NumericThe largest singular value
Compute the largest singular value of A=[3045]\mat{A} = \begin{bmatrix} 3 & 0 \\ 4 & 5 \end{bmatrix}.
QuizSVD shapes
A∈R5×3\mat{A} \in \R^{5\times 3} has rank 2. How many nonzero singular values does it have, and what are the factor shapes in the full and reduced SVD with p=min⁡(m,n)p = \min(m, n) (using full_matrices=False)?
ProofThe σ² are eigenvalues of AᵀA
Prove: If A=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T is any SVD of A∈Rm×n\mat{A} \in \R^{m\times n}, the σi2\sigma_i^2 are eigenvalues of A⊤A\mat{A}\T\mat{A} (padded with zeros). Therefore singular values do not depend on the SVD chosen, and AA⊤\mat{A}\mat{A}\T has the same nonzero eigenvalues.
0
Start only from the factorization: U,V\mat{U}, \mat{V} orthogonal and Σ∈Rm×n\mat{\Sigma} \in \R^{m\times n} diagonal with σ1≥⋯≥σp≥0\sigma_1 \ge \dots \ge \sigma_p \ge 0.

Step 1 of 4. Compute A⊤A\mat{A}\T\mat{A}.

QuizEigenvalues or singular values?
Let A\mat{A} be a real square matrix. Which statements are always true?

More than one answer may be correct.

QuizReconstructing with NumPy
You run U, S, Vh = np.linalg.svd(A) with A of shape (5, 3). Which expressions reconstruct A?

More than one answer may be correct.

NumericThe ellipsoid's volume
A∈R3×3\mat{A} \in \R^{3\times 3} has singular values 33, 22 and 0.50.5. What is the volume of the image of the unit ball?
NumericThe polar factor's rotation
For A=[3045]\mat{A} = \begin{bmatrix} 3 & 0 \\ 4 & 5 \end{bmatrix}, polar factor Q=UV⊤\mat{Q} = \mat{U}\mat{V}\T is a rotation. How many degrees does it rotate (positive counterclockwise)?
NumericKabsch in the plane
Centered points xi\vb{x}_i: (2,0)(2, 0), (0,1)(0, 1), (−2,0)(-2, 0), (0,−1)(0, -1). Their measured correspondences, also centered, are yi\vb{y}_i: (1.7,1.0)(1.7, 1.0), (−0.5,0.9)(-0.5, 0.9), (−1.6,−1.3)(-1.6, -1.3), (0.4,−0.6)(0.4, -0.6). What is the angle in degrees of the rotation minimizing ∑i∥Rθxi−yi∥2\sum_i\norm{\mat{R}_\theta\vb{x}_i - \vb{y}_i}^2?
CodeKabsch with reflection correction
Implement kabsch_rotation(X, Y) which, given X and Y of shape (n, 3) (one corresponding point per row), returns rotation R (3×33\times 3, with det⁡R=1\det\mat{R} = 1) minimizing ∑i∥R(xi−xˉ)−(yi−yˉ)∥2\sum_i\norm{\mat{R}(\vb{x}_i - \bar{\vb{x}}) - (\vb{y}_i - \bar{\vb{y}})}^2. The data are not centered. Tests include a case where the uncorrected polar factor would be a reflection.
import numpy as np

def kabsch_rotation(X, Y):
  X = np.asarray(X, dtype=float)
  Y = np.asarray(Y, dtype=float)
  # 1. centra las dos nubes
  # 2. forma H = Xcᵀ Yc y calcula su SVD
  # 3. corrige el signo si el factor polar es una reflexión
  return np.eye(3)
Shift+Enter to run
CodePolar decomposition with SVD
Implement polar_decomposition(A) for A of shape (m, n) with m≥nm \ge n. Return (Q, S) with A=QS\mat{A} = \mat{Q}\mat{S}, Q of shape (m, n) with orthonormal columns, and S of shape (n, n) symmetric positive semidefinite. Do not use scipy.linalg.polar or sqrtm. Do not correct signs: if det⁡A<0\det\mat{A} < 0, Q\mat{Q} must be a reflection.
import numpy as np

def polar_decomposition(A):
  A = np.asarray(A, dtype=float)
  # tu código: usa la SVD reducida
  Q = None
  S = None
  return Q, S
Shift+Enter to run

Summary

  • Every matrix A∈Rm×n\mat{A} \in \R^{m\times n} factors as A=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T: rotate (or reflect) with V⊤\mat{V}\T, stretch each axis by σi≥0\sigma_i \ge 0, and position with U\mat{U}. The unit sphere maps to an ellipsoid with semiaxes σiui\sigma_i\vb{u}_i, and Avi=σiui\mat{A}\vb{v}_i = \sigma_i\vb{u}_i.
  • SVD follows from the spectral theorem applied to A⊤A\mat{A}\T\mat{A}: vi\vb{v}_i are its eigenvectors, σi2\sigma_i^2 its eigenvalues, and ui=Avi/σi\vb{u}_i = \mat{A}\vb{v}_i/\sigma_i. The σi\sigma_i are unique; vectors are unique up to signs and rotations within repeated values. For computation, never use A⊤A\mat{A}\T\mat{A}.
  • Columns of U\mat{U} and V\mat{V} give paired orthonormal bases of the four subspaces, and rank is the number of σi>0\sigma_i > 0. Expansion A=∑iσiuivi⊤\mat{A} = \sum_i\sigma_i\vb{u}_i\vb{v}_i\T distributes ∥A∥F2=∑σi2\norm{\mat{A}}_F^2 = \sum\sigma_i^2 into orthogonal rank-one layers.
  • Singular values and eigenvalues coincide in magnitude only for normal matrices; in general they share ∣det⁡A∣\abs{\det\mat{A}} and satisfy σn≤∣λi∣≤σ1\sigma_n \le \abs{\lambda_i} \le \sigma_1.
  • Polar decomposition A=(UV⊤)(VΣV⊤)\mat{A} = (\mat{U}\mat{V}\T)(\mat{V}\mat{\Sigma}\mat{V}\T) separates rotation and stretch; UV⊤\mat{U}\mat{V}\T is the nearest orthogonal matrix to A\mat{A} and solves Procrustes. For a proper rotation, Kabsch corrects the last pair’s sign.
Key idea
The SVD says there are no complicated matrices, only poorly chosen bases: with basis vi\vb{v}_i at input and basis ui\vb{u}_i at output, any linear map is an independent stretch of each axis, and almost everything you want to measure about a matrix (size, rank, conditioning, best approximation, nearest rotation) can be read from those stretches.