Skip to content
ml-recall

Topic notes

Linear Algebra

The linear algebra deep learning uses — shapes and products, norms and angles, rank and null space, determinants, eigenvalues, singular values and the cost of matrix products.

3-min read AI-checked

Practise 59 questions Take a test

Key ideas

Objects and shapes. A vector is a 1-D array (one example's features), a matrix a 2-D array (a dense layer's weights), a tensor any kk-D array. With one example per row, a mini-batch of nn examples with dd features is X∈Rn×dX\in\mathbb{R}^{n\times d}. A product ABAB needs matching inner sizes: (n×k)(k×m)→n×m(n\times k)(k\times m)\to n\times m, and entry (i,j)(i,j) is row ii of AA dotted with column jj of BB1. A batch of 32 examples with 10 features times a 10×6410\times64 weight matrix gives 32×6432\times64: one row of 64 outputs per example.

Norms1: ∥x∥1=∑∣xi∣\lVert x\rVert_1=\sum|x_i| (Manhattan, city-block distance), ∥x∥2=∑xi2\lVert x\rVert_2=\sqrt{\sum x_i^2}, ∥x∥∞=max⁡∣xi∣\lVert x\rVert_\infty=\max|x_i|. Every norm satisfies ∥αx∥=∣α∣∥x∥\lVert\alpha x\rVert=|\alpha|\lVert x\rVert and the triangle inequality ∥x+y∥≤∥x∥+∥y∥\lVert x+y\rVert\le\lVert x\rVert+\lVert y\rVert — equality is not guaranteed. Among the pp-norms only ℓ2\ell_2 comes from an inner product, since only it satisfies the parallelogram law7. ∥x∥1\lVert x\rVert_1 is the walking distance on a grid (no diagonals).

Dot products and angles2: x⊤y=∥x∥∥y∥cos⁡θx^\top y=\lVert x\rVert\lVert y\rVert\cos\theta; orthogonal means x⊤y=0x^\top y=0; cosine similarity ignores length. For unit vectors ∥u−v∥2=2−2u⊤v\lVert u-v\rVert^2=2-2u^\top v. The closest point to xx on the line through a unit vector uu is (x⊤u) u(x^\top u)\,u. Entry (i,j)(i,j) of HH⊤HH^\top is the dot product of rows ii and jj — a cosine only if the rows are normalised.

Rank, null space, invertibility. Rank = number of linearly independent columns 2; rank + nullity = number of columns4. The solutions of Ax=0Ax=0 form a subspace (the null space) of dimension n−rank⁡An-\operatorname{rank}A: sums and multiples of solutions are solutions, and a nullity of 2 or more means they are not all multiples of one vector. For a square AA these are equivalent: AA invertible, det⁡A≠0\det A\ne0, full rank, columns independent, null space {0}\{0\}, Ax=bAx=b uniquely solvable for every bb, 0 not an eigenvalue2. Pairwise independence of columns is weaker and not enough. A column times a row (cr⊤cr^\top) has rank 1, so its determinant is 0; a set of vectors containing 00 is always dependent. For 2×22\times2, [abcd]−1=1ad−bc[d−b−ca]\begin{bmatrix}a&b\\c&d\end{bmatrix}^{-1}=\frac1{ad-bc}\begin{bmatrix}d&-b\\-c&a\end{bmatrix}.

Linear maps and subspaces. A linear map is fixed by its values on a basis: write the new input as a combination of inputs you know and combine their images the same way. For a linear map T:V→WT:V\to W, dim⁡V=dim⁡ker⁡T+dim⁡im⁡T\dim V=\dim\ker T+\dim\operatorname{im}T (the rank theorem again)4. Two subspaces of a space XX satisfy dim⁡(V∩W)≥dim⁡V+dim⁡W−dim⁡X\dim(V\cap W)\ge\dim V+\dim W-\dim X, because dim⁡(V+W)≤dim⁡X\dim(V+W)\le\dim X.

Determinant = signed factor by which AA scales area/volume2; for 2×22\times2, ad−bcad-bc. det⁡(AB)=det⁡Adet⁡B\det(AB)=\det A\det B, det⁡A−1=1/det⁡A\det A^{-1}=1/\det A. If y=Axy=Ax, densities rescale: py(y)=px(x)/∣det⁡A∣p_y(y)=p_x(x)/|\det A|.

Eigenvalues. Av=λvAv=\lambda v, v≠0v\ne0; eigenvalues are roots of det⁡(A−λI)\det(A-\lambda I). Then det⁡A=∏λi\det A=\prod\lambda_i, tr⁡A=∑λi\operatorname{tr}A=\sum\lambda_i — read them off the characteristic polynomial: its constant term is det⁡A\det A and the coefficient of λn−1\lambda^{n-1} is (−1)n−1tr⁡A(-1)^{n-1}\operatorname{tr}A. AkA^k, A−1A^{-1}, cAcA keep the eigenvectors with eigenvalues λk\lambda^k, 1/λ1/\lambda, cλc\lambda3. Symmetric matrices have real eigenvalues and orthogonal eigenvectors, A=WΣW⊤A=W\Sigma W^\top3. Similar matrices (B=P−1APB=P^{-1}AP) share eigenvalues, trace and determinant. A projection (P2=PP^2=P) has eigenvalues 0 and 1 only, is diagonalizable, and its trace equals its rank. A+A⊤A+A^\top and A⊤AA^\top A are always symmetric; AA maps orthogonal e1,e2e_1, e_2 to orthogonal vectors exactly when its columns are orthogonal, i.e. A⊤AA^\top A is diagonal.

Power iteration. Repeatedly multiplying a random vector by AA (and normalising) aligns it with the eigenvector of the largest ∣λ∣|\lambda|; the other components shrink like (λi/λ1)k(\lambda_i/\lambda_1)^k3.

Singular values. A=UΣV⊤A=U\Sigma V^\top; the singular values are the square roots of the eigenvalues of A⊤AA^\top A, and the spectral norm ∥A∥2\lVert A\rVert_2 is the largest one6. Power iteration on AA⊤AA^\top therefore estimates σmax⁡2\sigma_{\max}^2 from below: a ratio ∥AA⊤u∥/∥u∥\lVert AA^\top u\rVert/\lVert u\rVert can never exceed ∥AA⊤∥2=σmax⁡2\lVert AA^\top\rVert_2=\sigma_{\max}^2.

Random matrices. Take a d×dd\times d matrix with independent entries of mean 0 and variance 1 (e.g. standard normal). Its largest ∣eigenvalue∣|\text{eigenvalue}| is about d\sqrt d (circular law)3, but its spectral norm is 2d (1+o(1))2\sqrt d\,(1+o(1)) as d→∞d\to\infty (Bai–Yin law, needs a finite fourth moment); for Gaussian entries E∥G∥2≤2d\mathbb{E}\lVert G\rVert_2\le2\sqrt d for every dd8. So a matrix of size-1 entries stretches some vector by about 2d2\sqrt d — why initial weights are scaled by 1/d1/\sqrt d.

Cost of products. (p×q)(q×r)(p\times q)(q\times r) costs pqrpqr multiplications. Matrix multiplication is associative, so choose the parenthesisation that keeps intermediate results small5. For a tall A∈Rn×dA\in\mathbb{R}^{n\times d} (n≫dn\gg d), A(A⊤A)A(A^\top A) costs 2nd22nd^2 but (AA⊤)A(AA^\top)A costs 2n2d2n^2d, because it builds an n×nn\times n intermediate.

Einsum. Repeated indices are summed: tr⁡(A)=aii\operatorname{tr}(A)=a_{ii}, (AB)ik=aijbjk(AB)_{ik}=a_{ij}b_{jk}; in code torch.einsum('ij,jk->ik', A, B)2.

Formulas

cos⁡θ=x⊤y∥x∥2∥y∥2,rank⁡A+dim⁡Nul⁡A=n,σi(A)=λi(A⊤A)\cos\theta=\frac{x^\top y}{\lVert x\rVert_2\lVert y\rVert_2},\qquad \operatorname{rank}A+\dim\operatorname{Nul}A=n,\qquad \sigma_i(A)=\sqrt{\lambda_i(A^\top A)}

Worked example

A=[2112]A=\begin{bmatrix}2&1\\1&2\end{bmatrix}: det⁡(A−λI)=(2−λ)2−1=0\det(A-\lambda I)=(2-\lambda)^2-1=0 gives λ=3,1\lambda=3,1 with eigenvectors (1,1)(1,1) and (1,−1)(1,-1). Check: trace 4=3+14=3+1, determinant 3=3⋅13=3\cdot1, so AA triples areas. A−1A^{-1} has eigenvalues 1/31/3 and 11; power iteration on AA approaches (1,1)/2(1,1)/\sqrt2, with the error shrinking by λ2/λ1=1/3\lambda_2/\lambda_1=1/3 per step.

Chain cost with A10×100A_{10\times100}, B100×5B_{100\times5}, C5×50C_{5\times50}: (AB)C(AB)C costs 10⋅100⋅5+10⋅5⋅50=7,50010\cdot100\cdot5+10\cdot5\cdot50=7{,}500; A(BC)A(BC) costs 100⋅5⋅50+10⋅100⋅50=75,000100\cdot5\cdot50+10\cdot100\cdot50=75{,}000.

In code

import numpy as np

A = np.array([[2.0, 1.0], [1.0, 2.0]])
print(np.linalg.eigvalsh(A))                    # [1. 3.]
print(np.trace(A), round(np.linalg.det(A), 6))  # 4.0 3.0
B = np.array([[1.0, 2.0], [0.0, 2.0]])
print(np.linalg.svd(B, compute_uv=False))       # [2.92080963 0.68474165]
rng = np.random.default_rng(0)
d = 1000
G = rng.standard_normal((d, d))
print(round(np.linalg.norm(G, 2) / np.sqrt(d), 3))                # 1.998
print(round(np.abs(np.linalg.eigvals(G)).max() / np.sqrt(d), 3))  # 1.014

Common pitfalls

References

  1. Dive into Deep Learning — Sec. 2.3.10 Matrix–Matrix Multiplication; Sec. 2.3.11 Norms
  2. Dive into Deep Learning — Sec. 22.1.2 Dot Products and Angles; 22.1.6 Rank; 22.1.7 Invertibility; 22.1.8 Determinant; 22.1.9 Tensors and Common Linear Algebra Operations
  3. Dive into Deep Learning — Sec. 22.2.3 Operations on Eigendecompositions; 22.2.4 Eigendecompositions of Symmetric Matrices; 22.2.6 A Useful Application — The Growth of Iterated Maps; 22.2.7 Discussion
  4. Margalit & Rabinoff, Interactive Linear Algebra — Sec. 2.9 The Rank Theorem
  5. Wikipedia: Matrix chain multiplication — Introduction
  6. Wikipedia: Singular value decomposition — SVD and spectral decomposition (Relation to eigenvalue decomposition); Norms (Ky Fan norms)
  7. Vershynin, Introduction to the non-asymptotic analysis of random matrices (2010), arXiv:1011.3027 — Sec. 5.3.1 Limit laws and Gaussian matrices (Theorem 5.31 Bai–Yin's law; Theorem 5.32 Gordon's theorem)
  8. Wikipedia: Parallelogram law — Normed vector spaces satisfying the parallelogram law