Matrix factorisation and low-rank approximation
Be able to explain rank, the SVD and why a large matrix can often be approximated as the product of two small ones.
Prerequisites
Intuition
Rank = the number of independent directions a matrix «really» contains. A 1000 × 1000 matrix of rank 5 is only five patterns in different mixtures — it can be written as the product of a 1000 × 5 and a 5 × 1000 matrix: 10 000 numbers instead of a million.
The SVD (singular value decomposition) finds those patterns, sorted by importance: . Keep the k largest singular values → the best rank-k approximation (Eckart–Young).
Why care? Rating matrices (users × films), word co-occurrences and weight updates during fine-tuning are often nearly low-rank. LoRA exploits exactly that: ΔW ≈ BA with a small k.
Code
import numpy as np
rng = np.random.default_rng(0)
# a «secretly» low-rank matrix plus noise
B, A = rng.normal(size=(200, 4)), rng.normal(size=(4, 300))
M = B @ A + rng.normal(0, 0.5, (200, 300))
U, s, Vt = np.linalg.svd(M, full_matrices=False)
print(np.round(s[:8], 1)) # four large ones, then small: [.. .. .. .. ~10 ~10 ...]
def approx(k):
return (U[:, :k] * s[:k]) @ Vt[:k]
for k in (1, 2, 4, 8, 50):
err = np.linalg.norm(M - approx(k)) / np.linalg.norm(M)
print(k, round(err, 3)) # falls steeply up to k=4, after which only noise is left
print(200 * 300, 200 * 4 + 4 * 300) # 60000 vs 2000 numbers
Formal
For : with orthogonal and . The rank = the number of . Eckart–Young–Mirsky: minimises over all of rank , with error . Parameters: against . The share of the «energy» gives you a choice of . A randomised SVD gives in .
Mastery means
- Explains rank and the SVD
- Approximates a matrix with a low rank and measures the error
- Connects low rank to LoRA and to recommender systems
Sign in to do the exercises and build your mastery up.
Sources
- Wikipedia — Singular value decomposition (CC BY-SA 4.0) — CC BY-SA 4.0
- arXiv — LoRA: Low-Rank Adaptation of Large Language Models — arXiv (open access; licence per article)