Skip to content

46. Linear algebra in depth

In module 32 you learned to treat rows as vectors, compute dot products, and call np.linalg.lstsq as a reliable solver. This module opens the hood on the geometry and numerical machinery underneath almost every data science and ML algorithm: why least squares is a perpendicular drop onto a subspace, why forming X⊤XX^\top X fails when features are collinear, how eigenvalues describe the shape of a covariance ellipse, and why Singular Value Decomposition (SVD) powers PCA, low-rank compression, pseudoinverses, and latent topic discovery.

  • Read matrices as linear transformations (scaling, rotation, shear, projection) and diagnose column dependence via rank and null space.
  • Project vectors onto subspaces and derive ordinary least squares geometrically using orthogonality and QR factorization.
  • Compute and interpret determinants, eigenvalues, eigenvectors, positive definite matrices, and the spectral theorem.
  • Use Singular Value Decomposition (SVD) for PCA, pseudoinverses, low-rank compression, and latent topics on real course datasets.
  • NumPy arrays, broadcasting, @, solve, and lstsq: 23. NumPy.
  • Feature vectors, norms, dot products, and closed-form linear regression: 32. Math for ML.
  • Loading and pivoting tables with pandas: 24. pandas fundamentals.
  • The course datasets data/houses.csv, data/customers.csv, data/sales.csv, and data/reviews.csv, documented in the data dictionary.

Start with one setup block for the lesson page. It sets compact NumPy printing and loads the four course tables used across the concepts and worked examples.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.sparse.linalg import svds
from sklearn.decomposition import PCA, TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
np.set_printoptions(precision=4, suppress=True)
houses = pd.read_csv("data/houses.csv")
customers = pd.read_csv("data/customers.csv")
sales = pd.read_csv("data/sales.csv")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)

Matrices as transformations: stretching, rotating and projecting space

Section titled “Matrices as transformations: stretching, rotating and projecting space”

A matrix is not only a table of numbers; it is a linear transformation—a function T(x)=AxT(\mathbf{x}) = A\mathbf{x} that maps every vector x\mathbf{x} to a new vector while preserving vector addition and scalar multiplication:

A(u+v)=Au+AvA(c u)=c AuA(\mathbf{u} + \mathbf{v}) = A\mathbf{u} + A\mathbf{v} \qquad A(c\,\mathbf{u}) = c\,A\mathbf{u}

Geometrically, every linear transformation keeps the origin fixed and keeps straight parallel grid lines straight and evenly spaced. The columns of AA tell you everything: column 1 is where the horizontal unit vector e1=(1,0)\mathbf{e}_1 = (1, 0) lands, and column 2 is where e2=(0,1)\mathbf{e}_2 = (0, 1) lands.

Four 2-D matrices illustrate the building blocks of all matrix transformations:

Transformation Matrix AA What it does to the unit circle
Scaling [1.8000.7]\begin{bmatrix} 1.8 & 0 \\ 0 & 0.7 \end{bmatrix} Stretches xx by 1.8 and shrinks yy by 0.7
Rotation by θ\theta [cos⁡θ−sin⁡θsin⁡θcos⁡θ]\begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix} Turns every point counterclockwise without changing lengths
Shear [10.801]\begin{bmatrix} 1 & 0.8 \\ 0 & 1 \end{bmatrix} Slants horizontal layers proportionally to yy
Projection onto xx-axis [1000]\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix} Flattens 2-D space onto a 1-D line
angles = np.linspace(0, 2 * np.pi, 200)
circle = np.vstack([np.cos(angles), np.sin(angles)])
basis = np.eye(2)
theta = np.deg2rad(35)
transforms = [
("Scaling", np.array([[1.8, 0.0], [0.0, 0.7]])),
(
"Rotation (35 deg)",
np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]),
),
("Shear", np.array([[1.0, 0.8], [0.0, 1.0]])),
("Projection onto x-axis", np.array([[1.0, 0.0], [0.0, 0.0]])),
]
fig, axes = plt.subplots(1, 4, figsize=(11, 2.8))
for ax, (name, mat) in zip(axes, transforms, strict=True):
img = mat @ circle
e_img = mat @ basis
ax.plot(circle[0], circle[1], "--", color="gray", lw=1)
ax.plot(img[0], img[1], color="tab:blue", lw=2)
for idx, color in [(0, "tab:red"), (1, "tab:green")]:
ax.annotate(
"",
xy=e_img[:, idx],
xytext=(0, 0),
arrowprops={"arrowstyle": "->", "color": color, "lw": 2},
)
ax.set_xlim(-2.1, 2.1)
ax.set_ylim(-2.1, 2.1)
ax.set_aspect("equal")
ax.axhline(0, color="lightgray", lw=0.6)
ax.axvline(0, color="lightgray", lw=0.6)
ax.set_title(name, fontsize=9)
fig.tight_layout()
plt.show()
Four side-by-side plots showing the dashed unit circle transformed into a blue ellipse by scaling, a rotated circle by a 35-degree rotation, a tilted ellipse by shear, and a flat horizontal line segment by projection onto the x-axis, with red and green arrows showing where the two basis vectors land.
Four fundamental 2-D linear transformations applied to the unit circle and standard basis vectors.

When a model applies a linear layer Z=XWZ = XW or rotates standardized features into principal components, it is chaining linear transformations. Notice the last panel: projection collapses 2-D area into a 1-D line, so information is lost and the transformation cannot be inverted.

Linear independence, span, basis and matrix rank

Section titled “Linear independence, span, basis and matrix rank”

Suppose a feature matrix X∈Rn×pX \in \mathbb{R}^{n \times p} has pp columns c1,…,cp\mathbf{c}_1, \dots, \mathbf{c}_p. Four closely linked definitions describe what those columns can express:

  • The span of c1,…,cp\mathbf{c}_1, \dots, \mathbf{c}_p is the set of all linear combinations w1c1+⋯+wpcpw_1\mathbf{c}_1 + \dots + w_p\mathbf{c}_p.
  • A subspace is any flat slice through the origin (a line, plane, or higher-dimensional flat) closed under addition and scaling. The span of a matrix’s columns is its column space col⁡(X)\operatorname{col}(X)—every prediction vector y^=Xw\hat{\mathbf{y}} = X\mathbf{w} a linear model can possibly produce.
  • Vectors have linear independence when no column can be written as a linear combination of the others: Xw=0X\mathbf{w} = \mathbf{0} only when w=0\mathbf{w} = \mathbf{0}.
  • A basis of a subspace is a linearly independent set that spans it. Every point in the subspace has unique coordinates in that basis.

The rank of XX is the dimension of its column space—the number of linearly independent columns. The null space (or kernel) of XX is the set of all nonzero (plus zero) vectors v\mathbf{v} satisfying Xv=0X\mathbf{v} = \mathbf{0}. By the rank–nullity theorem:

rank⁡(X)+dim⁡(null⁡(X))=p\operatorname{rank}(X) + \dim(\operatorname{null}(X)) = p

Whenever a feature is an exact linear combination of others (such as including sqft and sqm = 0.0929 * sqft in the same regression), rank⁡(X)<p\operatorname{rank}(X) < p and the null space contains nonzero directions along which weights can slide infinitely without changing XwX\mathbf{w}.

sqft = houses["sqft"].to_numpy(dtype=float)[:200]
beds = houses["bedrooms"].to_numpy(dtype=float)[:200]
sqm = sqft * 0.092903 # exact scalar multiple of sqft
X_indep = np.column_stack([sqft, beds])
X_dep = np.column_stack([sqft, beds, sqm])
print("independent shape and rank:", X_indep.shape, np.linalg.matrix_rank(X_indep))
print("dependent shape and rank: ", X_dep.shape, np.linalg.matrix_rank(X_dep))
null_vec = np.array([-0.092903, 0.0, 1.0])
print("max |X_dep @ null_vec|: ", np.max(np.abs(X_dep @ null_vec)))
Output
independent shape and rank: (200, 2) 2
dependent shape and rank: (200, 3) 2
max |X_dep @ null_vec|: 0.0

X_dep has 3 columns but rank 2, because null_vec lies in its null space: adding any multiple of null_vec to a weight vector w\mathbf{w} leaves every prediction XwX\mathbf{w} unchanged.

Orthogonality, orthonormal bases and Gram–Schmidt

Section titled “Orthogonality, orthonormal bases and Gram–Schmidt”

Two vectors u\mathbf{u} and v\mathbf{v} are orthogonal vectors when their dot product is zero (u⊤v=0\mathbf{u}^\top \mathbf{v} = 0): geometrically, they meet at a 90∘90^\circ angle. An orthonormal basis is a basis of mutually orthogonal unit vectors (qi⊤qj=1\mathbf{q}_i^\top \mathbf{q}_j = 1 if i=ji = j else 00). Stacking them as columns of QQ gives Q⊤Q=IQ^\top Q = I. When QQ is square (p×pp \times p), it is an orthogonal matrix, meaning Q⊤=Q−1Q^\top = Q^{-1} and multiplying by QQ preserves every vector length and angle (∥Qx∥2=∥x∥2\lVert Q\mathbf{x} \rVert_2 = \lVert \mathbf{x} \rVert_2).

Why do numerical algorithms love orthonormal columns? Computing coordinates in an orthonormal basis needs no matrix inversion—just a dot product: c=Q⊤v\mathbf{c} = Q^\top \mathbf{v}.

The Gram–Schmidt process turns any linearly independent columns a1,…,ap\mathbf{a}_1, \dots, \mathbf{a}_p into an orthonormal basis q1,…,qp\mathbf{q}_1, \dots, \mathbf{q}_p by subtracting each new column’s projection onto the already-orthonormalized directions and normalizing what remains. In floating-point arithmetic, modified Gram–Schmidt subtracts each component one by one from the updated residual vector, which prevents rounding errors from accumulating.

def modified_gram_schmidt(A: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Orthonormalize columns of A (m x p) into Q (m x p) and upper-triangular R."""
m, p = A.shape
Q = np.zeros((m, p), dtype=float)
R = np.zeros((p, p), dtype=float)
for j in range(p):
v = A[:, j].astype(float).copy()
for i in range(j):
R[i, j] = Q[:, i] @ v
v = v - R[i, j] * Q[:, i]
R[j, j] = np.linalg.norm(v)
Q[:, j] = v / R[j, j]
return Q, R
A_small = np.array([[1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
Q_mgs, R_mgs = modified_gram_schmidt(A_small)
print("max |Q.T @ Q - I|:", f"{np.max(np.abs(Q_mgs.T @ Q_mgs - np.eye(3))):.2e}")
print("max |Q @ R - A|: ", f"{np.max(np.abs(Q_mgs @ R_mgs - A_small)):.2e}")
print("R:\n", R_mgs)
Output
max |Q.T @ Q - I|: 2.60e-16
max |Q @ R - A|: 3.32e-17
R:
[[1.7321 1.1547 1.1547]
[0. 1.291 0.5164]
[0. 0. 1.1832]]

Notice that Q_mgs @ R_mgs reproduces A_small to machine precision (10−1610^{-16}) and R_mgs is upper triangular. You just built QR factorization from scratch.

Orthogonal projection: least squares as dropping a perpendicular

Section titled “Orthogonal projection: least squares as dropping a perpendicular”

Given a vector y∈Rn\mathbf{y} \in \mathbb{R}^n and a subspace S=col⁡(X)S = \operatorname{col}(X), what point y^∈S\hat{\mathbf{y}} \in S is closest to y\mathbf{y} in Euclidean distance? The orthogonal projection of y\mathbf{y} onto SS: the unique point y^=Xw\hat{\mathbf{y}} = X\mathbf{w} such that the residual vector r=y−y^\mathbf{r} = \mathbf{y} - \hat{\mathbf{y}} is perpendicular to every column of XX.

  • Onto a single nonzero vector a\mathbf{a}: proj⁡a(y)=a⊤ya⊤aa\operatorname{proj}_{\mathbf{a}}(\mathbf{y}) = \frac{\mathbf{a}^\top \mathbf{y}}{\mathbf{a}^\top \mathbf{a}} \mathbf{a}.
  • Onto a subspace with orthonormal basis QQ: y^=Q(Q⊤y)=(QQ⊤)y\hat{\mathbf{y}} = Q(Q^\top \mathbf{y}) = (QQ^\top)\mathbf{y}.
  • Onto col⁡(X)\operatorname{col}(X) directly: requiring X⊤(y−Xw)=0X^\top(\mathbf{y} - X\mathbf{w}) = \mathbf{0} yields the normal equations X⊤Xw=X⊤yX^\top X \mathbf{w} = X^\top \mathbf{y} and the projection matrix P=X(X⊤X)−1X⊤P = X(X^\top X)^{-1} X^\top.

Every orthogonal projection matrix P=QQ⊤P = QQ^\top satisfies two algebraic signatures: it is symmetric (P⊤=PP^\top = P) and idempotent (P2=PP^2 = P, because projecting a point that is already in the subspace does not move it). And because y^⊥r\hat{\mathbf{y}} \perp \mathbf{r}, the Pythagorean theorem holds in nn-dimensional space:

∥y∥22=∥y^∥22+∥r∥22\lVert \mathbf{y} \rVert_2^2 = \lVert \hat{\mathbf{y}} \rVert_2^2 + \lVert \mathbf{r} \rVert_2^2
y_vec = np.array([2.0, 3.0, 1.0, 4.0])
P = Q_mgs @ Q_mgs.T
y_hat = P @ y_vec
resid = y_vec - y_hat
print("max |P @ P - P|:", f"{np.max(np.abs(P @ P - P)):.2e}")
print("max |A.T @ r|: ", f"{np.max(np.abs(A_small.T @ resid)):.2e}")
lhs = np.linalg.norm(y_vec) ** 2
rhs = np.linalg.norm(y_hat) ** 2 + np.linalg.norm(resid) ** 2
print("Pythagoras ||y||^2 vs ||y_hat||^2 + ||r||^2:", round(lhs, 4), round(rhs, 4))
Output
max |P @ P - P|: 2.22e-16
max |A.T @ r|: 1.55e-15
Pythagoras ||y||^2 vs ||y_hat||^2 + ||r||^2: 30.0 30.0

Ordinary least squares is not a trick from calculus alone—it is geometry. Minimizing ∥y−Xw∥22\lVert \mathbf{y} - X\mathbf{w} \rVert_2^2 simply drops a perpendicular from y\mathbf{y} onto the flat subspace spanned by the feature columns.

QR factorization and why lstsq stays stable when X⊤XX^\top X fails

Section titled “QR factorization and why lstsq stays stable when X⊤XX^\top XX⊤X fails”

Writing X=QRX = QR (called QR factorization, where Q∈Rn×pQ \in \mathbb{R}^{n \times p} has orthonormal columns and R∈Rp×pR \in \mathbb{R}^{p \times p} is upper triangular) simplifies the normal equations dramatically:

X⊤Xw=X⊤y  ⟹  R⊤Q⊤QRw=R⊤Q⊤y  ⟹  Rw=Q⊤yX^\top X \mathbf{w} = X^\top \mathbf{y} \implies R^\top Q^\top Q R \mathbf{w} = R^\top Q^\top \mathbf{y} \implies R\mathbf{w} = Q^\top \mathbf{y}

Because RR is upper triangular, solving Rw=Q⊤yR\mathbf{w} = Q^\top \mathbf{y} takes fast back-substitution, and you never form X⊤XX^\top X. Why does avoiding X⊤XX^\top X matter so much?

The condition number κ(X)=σmax⁡/σmin⁡\kappa(X) = \sigma_{\max} / \sigma_{\min} measures how much tiny input perturbations or floating-point rounding errors get amplified when solving a linear system. Forming X⊤XX^\top X squares the condition number: κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2. In 64-bit floats (about 16 digits of precision), if κ(X)≈108\kappa(X) \approx 10^8, then κ(X⊤X)≈1016\kappa(X^\top X) \approx 10^{16} and normal equations lose every single digit of accuracy, while QR and SVD (np.linalg.lstsq) still retain roughly 8 accurate digits.

eps = 1e-8
X_ill = np.array([[1.0, 1.0], [eps, 0.0], [0.0, eps]])
y_ill = np.array([2.0, eps, eps]) # true w = [1, 1]
print("cond(X): ", f"{np.linalg.cond(X_ill):.2e}")
print("cond(X.T @ X):", f"{np.linalg.cond(X_ill.T @ X_ill):.2e}")
Q_ill, R_ill = np.linalg.qr(X_ill)
w_qr = np.linalg.solve(R_ill, Q_ill.T @ y_ill)
w_lstsq = np.linalg.lstsq(X_ill, y_ill)[0]
print("QR weights: ", w_qr)
print("lstsq weights:", w_lstsq)
try:
w_norm = np.linalg.solve(X_ill.T @ X_ill, X_ill.T @ y_ill)
print("normal eqs: ", w_norm)
except np.linalg.LinAlgError as err:
print("normal eqs failed:", err)
Output
cond(X): 1.41e+08
cond(X.T @ X): inf
QR weights: [1. 1.]
lstsq weights: [1. 1.]
normal eqs failed: Singular matrix

On this classic Läuchli test matrix, 1+ε2=1+10−161 + \varepsilon^2 = 1 + 10^{-16} rounds to 1.01.0 in float64, so X_ill.T @ X_ill collapses to a matrix of all ones and fails completely. Both np.linalg.qr and np.linalg.lstsq recover the exact weights [1., 1.].

Determinants: volume scaling and when a matrix collapses space

Section titled “Determinants: volume scaling and when a matrix collapses space”

For a square p×pp \times p matrix AA, the determinant det⁡(A)\det(A) is a single scalar measuring the signed volume scaling factor of the transformation AA:

  • ∣det⁡(A)∣\lvert \det(A) \rvert is the factor by which AA multiplies area (in 2-D) or volume (in pp-D).
  • A negative determinant means AA flips orientation (a reflection).
  • det⁡(A)=0\det(A) = 0 means AA squashes space into a lower dimension (zero volume): AA is singular (not invertible) and has rank less than pp.
  • Product rule: det⁡(AB)=det⁡(A)det⁡(B)\det(AB) = \det(A)\det(B), and for any orthogonal matrix, ∣det⁡(Q)∣=1\lvert \det(Q) \rvert = 1.

In statistics, the multivariate Gaussian probability density divides by det⁡(Σ)\sqrt{\det(\Sigma)} to normalize for the volume of the covariance ellipse. In high dimensions, det⁡(Σ)\det(\Sigma) easily overflows or underflows float64, so numerical code uses np.linalg.slogdet(A) to compute the sign and log⁡∣det⁡(A)∣\log\lvert\det(A)\rvert directly.

for name, mat in transforms:
print(f"{name:24s} det = {np.linalg.det(mat):6.3f}")
cov_high = np.eye(50) * 0.1
sign, logdet = np.linalg.slogdet(cov_high)
print("direct det(0.1 * I_50):", np.linalg.det(cov_high))
print("slogdet sign & logdet: ", sign, round(float(logdet), 4))
Output
Scaling det = 1.260
Rotation (35 deg) det = 1.000
Shear det = 1.000
Projection onto x-axis det = 0.000
direct det(0.1 * I_50): 9.999999999999234e-51
slogdet sign & logdet: 1.0 -115.1293

Scaling by 1.8 and 0.7 scales area by 1.8×0.7=1.261.8 \times 0.7 = 1.26. Rotation preserves area (det⁡=1\det = 1), shear preserves area (det⁡=1\det = 1), and projection collapses area to 0 (det⁡=0\det = 0). For 0.1I500.1 I_{50}, the true determinant 10−5010^{-50} is tiny, while slogdet stays clean at 50ln⁡(0.1)≈−115.1350 \ln(0.1) \approx -115.13.

Eigenvalues and eigenvectors: directions that only stretch

Section titled “Eigenvalues and eigenvectors: directions that only stretch”

Most vectors change direction when multiplied by a square matrix AA. An eigenvector v≠0\mathbf{v} \neq \mathbf{0} is a special direction that stays on its own line—AA only stretches, shrinks, or flips it by a scalar eigenvalue λ\lambda:

Av=λv  ⟺  (A−λI)v=0A\mathbf{v} = \lambda\mathbf{v} \iff (A - \lambda I)\mathbf{v} = \mathbf{0}

Two useful identities connect eigenvalues to cheap matrix summaries:

  • The trace (sum of diagonal entries) equals the sum of eigenvalues: tr⁡(A)=∑iλi\operatorname{tr}(A) = \sum_i \lambda_i.
  • The determinant equals the product of eigenvalues: det⁡(A)=∏iλi\det(A) = \prod_i \lambda_i.

In NumPy, use np.linalg.eig(A) for general square matrices (which may have complex eigenvalues, like a rotation matrix that has no real invariant axis) and np.linalg.eigh(S) for symmetric matrices.

M = np.array([[3.0, 1.0], [1.0, 2.0]])
eigvals, eigvecs = np.linalg.eigh(M)
print("eigenvalues:", eigvals)
print("trace vs sum:", np.trace(M), round(float(eigvals.sum()), 4))
det_m = round(float(np.linalg.det(M)), 4)
print("det vs prod: ", det_m, round(float(eigvals.prod()), 4))
for i in range(2):
v = eigvecs[:, i]
print(f"check A @ v{i} == lam{i} * v{i}:", np.allclose(M @ v, eigvals[i] * v))
Output
eigenvalues: [1.382 3.618]
trace vs sum: 5.0 5.0
det vs prod: 5.0 5.0
check A @ v0 == lam0 * v0: True
check A @ v1 == lam1 * v1: True

Notice that eigh returns eigenvalues sorted in ascending order and stores eigenvectors as columns (eigvecs[:, i]), not rows.

Symmetric matrices, positive definiteness and covariance geometry

Section titled “Symmetric matrices, positive definiteness and covariance geometry”

Real data analysis produces symmetric matrices everywhere: Gram matrices X⊤XX^\top X, covariance matrices Σ\Sigma, correlation matrices, and Hessians of smooth loss functions. Symmetric matrices (S=S⊤S = S^\top) obey the spectral theorem:

  1. Every eigenvalue of SS is guaranteed to be real.
  2. Eigenvectors can always be chosen to form an orthonormal basis QQ (Q⊤Q=IQ^\top Q = I).
  3. SS factors cleanly as S=QΛQ⊤S = Q \Lambda Q^\top, where Λ=diag⁡(λ1,…,λp)\Lambda = \operatorname{diag}(\lambda_1, \dots, \lambda_p).

A symmetric matrix SS is a positive definite matrix if the quadratic form x⊤Sx>0\mathbf{x}^\top S \mathbf{x} > 0 for every nonzero vector x\mathbf{x}—equivalently, if every eigenvalue is strictly positive (λi>0\lambda_i > 0). It is positive semi-definite if λi≥0\lambda_i \ge 0.

For a centered data matrix XcX_c, the sample covariance matrix Σ=1n−1Xc⊤Xc\Sigma = \frac{1}{n - 1} X_c^\top X_c satisfies:

u⊤Σu=1n−1∥Xcu∥22≥0\mathbf{u}^\top \Sigma \mathbf{u} = \frac{1}{n - 1} \lVert X_c \mathbf{u} \rVert_2^2 \ge 0

That means u⊤Σu\mathbf{u}^\top \Sigma \mathbf{u} is literally the variance of the data when projected onto unit direction u\mathbf{u}! Therefore, the eigenvector with the largest eigenvalue is the direction of maximum variance (PC1), and its eigenvalue is that variance.

Z_two = houses[["sqft", "bathrooms"]].to_numpy(dtype=float)
Z_two = (Z_two - Z_two.mean(axis=0)) / Z_two.std(axis=0)
Sigma = np.cov(Z_two, rowvar=False)
vals, vecs = np.linalg.eigh(Sigma)
# Sort descending so index 0 is largest variance direction
order = np.argsort(vals)[::-1]
vals, vecs = vals[order], vecs[:, order]
print("covariance matrix:\n", Sigma)
print("eigenvalues (descending):", vals)
print("positive definite?", bool(np.all(vals > 0)))
print("eigenvectors orthogonal?", np.allclose(vecs.T @ vecs, np.eye(2)))
proj_var = np.var(Z_two @ vecs[:, 0], ddof=1)
print(
"variance along PC1 vs lambda_1:",
round(float(proj_var), 4),
round(float(vals[0]), 4),
)
Output
covariance matrix:
[[1.0003 0.8458]
[0.8458 1.0003]]
eigenvalues (descending): [1.8461 0.1546]
positive definite? True
eigenvectors orthogonal? True
variance along PC1 vs lambda_1: 1.8461 1.8461

Because eigh exploits symmetry, it is faster than eig, guarantees real outputs (no +0j noise), and guarantees orthogonal eigenvectors even when eigenvalues are equal.

Singular Value Decomposition (SVD): the universal matrix factorization

Section titled “Singular Value Decomposition (SVD): the universal matrix factorization”

Eigen-decomposition only works for square matrices, and only guarantees orthogonal eigenvectors when the matrix is symmetric. Singular Value Decomposition (SVD) works for every matrix A∈Rm×nA \in \mathbb{R}^{m \times n}—rectangular, wide, tall, or rank-deficient:

A=UΣV⊤A = U \Sigma V^\top

With reduced SVD (full_matrices=False, r=min⁡(m,n)r = \min(m, n)):

  • U∈Rm×rU \in \mathbb{R}^{m \times r} has orthonormal columns (left singular vectors, spanning row/output space).
  • Σ=diag⁡(σ1,…,σr)\Sigma = \operatorname{diag}(\sigma_1, \dots, \sigma_r) holds the singular values sorted descending (σ1≥σ2≥⋯≥σr≥0\sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_r \ge 0).
  • V⊤∈Rr×nV^\top \in \mathbb{R}^{r \times n} has orthonormal rows (right singular vectors, spanning input/feature space).

Geometrically, SVD says every linear map is just three elementary steps: rotate in input space (V⊤V^\top), stretch along perpendicular axes (Σ\Sigma), and rotate into output space (UU). Algebraically, SVD is tightly linked to eigen-decomposition: the right singular vectors VV are the eigenvectors of A⊤AA^\top A, and the squared singular values σi2\sigma_i^2 are the eigenvalues of A⊤AA^\top A—computed without ever squaring the condition number.

flowchart TD
    A["Matrix A (m x n)"] --> B{"Square & symmetric?"}
    B -- "Yes (cov, corr, Hessian)" --> C["np.linalg.eigh(A)<br/>S = Q Lambda Q.T"]
    B -- "No" --> D{"Tall & full rank for OLS?"}
    D -- "Yes (fast, stable)" --> E["np.linalg.qr(A)<br/>R w = Q.T y"]
    D -- "No / general / rank-deficient" --> F["np.linalg.svd(A, full_matrices=False)<br/>A = U Sigma V.T"]
U, s, Vt = np.linalg.svd(Z_two, full_matrices=False)
print("shapes U, s, Vt:", U.shape, s.shape, Vt.shape)
print("reconstruct max err:", f"{np.max(np.abs(U @ np.diag(s) @ Vt - Z_two)):.2e}")
s_to_eig = (s**2) / (len(Z_two) - 1)
print("s^2 / (n-1) vs eigh:", np.round(s_to_eig, 4), np.round(vals, 4))
print("matches eigh?", np.allclose(s_to_eig, vals))
Output
shapes U, s, Vt: (3000, 2) (2,) (2, 2)
reconstruct max err: 5.66e-15
s^2 / (n-1) vs eigh: [1.8461 0.1546] [1.8461 0.1546]
matches eigh? True

Look at that agreement: σi2/(n−1)\sigma_i^2 / (n - 1) matches the covariance eigenvalues vals to full precision, and Vt.T matches the covariance eigenvectors (up to a ±1\pm 1 sign flip, because if v\mathbf{v} is an eigenvector, −v-\mathbf{v} is too).

Low-rank approximations, the Moore–Penrose pseudoinverse and Eckart–Young

Section titled “Low-rank approximations, the Moore–Penrose pseudoinverse and Eckart–Young”

Rewrite SVD as a sum of rr rank-1 outer products, ordered from largest signal to smallest:

A=∑i=1rσi uivi⊤A = \sum_{i=1}^{r} \sigma_i \, \mathbf{u}_i \mathbf{v}_i^\top

Keeping only the top kk terms creates a low-rank approximation Ak=UkΣkVk⊤A_k = U_k \Sigma_k V_k^\top. How good is it? Measure matrix error with the Frobenius norm ∥E∥F=∑i,jEij2=∑iσi(E)2\lVert E \rVert_F = \sqrt{\sum_{i,j} E_{ij}^2} = \sqrt{\sum_i \sigma_i(E)^2}. The Eckart–Young theorem proves that AkA_k is the optimal rank-kk approximation to AA—no other rank-kk matrix can achieve a smaller Frobenius (or spectral) error—and its exact error is the tail of discarded singular values:

∥A−Ak∥F=∑i=k+1rσi2\lVert A - A_k \rVert_F = \sqrt{\sum_{i=k+1}^{r} \sigma_i^2}

SVD also generalizes the inverse to any rectangular or rank-deficient matrix via the Moore–Penrose pseudoinverse:

A+=VΣ+U⊤A^+ = V \Sigma^+ U^\top

where Σ+\Sigma^+ replaces each nonzero singular value σi\sigma_i with 1/σi1/\sigma_i and leaves tiny/zero singular values as 0. Solving w=A+y\mathbf{w} = A^+ \mathbf{y} always produces the unique minimum-norm least-squares solution, even when columns are collinear. That is precisely what np.linalg.lstsq and np.linalg.pinv compute under the hood.

A_rankdef = np.array(
[[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0]]
)
U_r, s_r, Vt_r = np.linalg.svd(A_rankdef, full_matrices=False)
tol = max(A_rankdef.shape) * np.finfo(float).eps * s_r[0]
s_inv = np.where(s_r > tol, 1.0 / s_r, 0.0)
pinv_manual = (Vt_r.T * s_inv) @ U_r.T
print("singular values:", s_r)
print("matches np.linalg.pinv?", np.allclose(pinv_manual, np.linalg.pinv(A_rankdef)))
Output
singular values: [8.5399 1.0342 0. ]
matches np.linalg.pinv? True

Example 1 — Visualize 2D linear transformations and covariance ellipses

Section titled “Example 1 — Visualize 2D linear transformations and covariance ellipses”

Goal: Show how the eigenvectors and eigenvalues of a sample covariance matrix define the axes and spread of real housing data (sqft vs. bathrooms in data/houses.csv).

Step 1 — Standardize the two features and decompose their covariance matrix

Section titled “Step 1 — Standardize the two features and decompose their covariance matrix”

We already standardized sqft and bathrooms into Z_two and computed Sigma, vals, and vecs above. Let’s inspect the exact orientation and correlation of the two principal directions.

# Orient PC1 into the positive quadrant (sign of an eigenvector is arbitrary)
if vecs[0, 0] < 0:
vecs[:, 0] = -vecs[:, 0]
angle_deg = np.rad2deg(np.arctan2(vecs[1, 0], vecs[0, 0]))
print(f"correlation sqft-bathrooms: {Sigma[0, 1]:.4f}")
print(
f"PC1 direction: {vecs[:, 0]} (angle {angle_deg:.1f} deg, "
f"std {np.sqrt(vals[0]):.3f})"
)
print(f"PC2 direction: {vecs[:, 1]} (std {np.sqrt(vals[1]):.3f})")
Output
correlation sqft-bathrooms: 0.8458
PC1 direction: [0.7071 0.7071] (angle 45.0 deg, std 1.359)
PC2 direction: [ 0.7071 -0.7071] (std 0.393)

Because both features have unit variance and positive correlation, the first eigenvector runs along the 45∘45^\circ diagonal (sqft and bathrooms growing together), while the second runs perpendicular to it (sqft growing faster than bathrooms).

Step 2 — Transform the unit circle into the 1-sigma and 2-sigma covariance ellipses

Section titled “Step 2 — Transform the unit circle into the 1-sigma and 2-sigma covariance ellipses”

A matrix L=QΛ1/2L = Q \Lambda^{1/2} transforms the unit circle into the 1-standard-deviation ellipse of the covariance matrix, because LL⊤=QΛQ⊤=ΣL L^\top = Q \Lambda Q^\top = \Sigma.

L = vecs @ np.diag(np.sqrt(vals))
ell_1 = L @ circle
ell_2 = 2.0 * ell_1
fig, ax = plt.subplots(figsize=(5.5, 5.0))
ax.scatter(Z_two[:, 0], Z_two[:, 1], s=8, alpha=0.22, color="tab:blue", label="houses")
ax.plot(ell_1[0], ell_1[1], color="tab:red", lw=2, label="1-sigma ellipse")
ax.plot(ell_2[0], ell_2[1], "--", color="tab:orange", lw=1.8, label="2-sigma ellipse")
for idx, (lbl, col) in enumerate([("PC1", "darkred"), ("PC2", "darkgreen")]):
arrow = 2.0 * np.sqrt(vals[idx]) * vecs[:, idx]
ax.annotate(
"",
xy=arrow,
xytext=(0, 0),
arrowprops={"arrowstyle": "->", "color": col, "lw": 2.5},
)
ax.text(arrow[0] * 1.08, arrow[1] * 1.08, lbl, color=col, fontweight="bold")
ax.set_xlim(-3.5, 4.5)
ax.set_ylim(-3.5, 4.5)
ax.set_aspect("equal")
ax.set_xlabel("standardized sqft")
ax.set_ylabel("standardized bathrooms")
ax.set_title("Covariance ellipse from eigendecomposition")
ax.legend(loc="upper left")
plt.show()
Scatter plot of 3,000 standardized house sqft versus bathrooms points overlaid with red 1-sigma and dashed orange 2-sigma ellipses tilted along the 45-degree diagonal, with dark red PC1 and dark green PC2 arrows along the major and minor axes.
The matrix Q Lambda^(1/2) maps the unit circle directly onto the 1-sigma covariance ellipse.

Notice how the ellipse wraps the tilted point cloud tightly: the linear transformation L=QΛ1/2L = Q\Lambda^{1/2} literally turns isotropic (circular) unit data into correlated data with covariance Σ\Sigma.

Common mistakes:

  • Scaling the unit circle by λi\lambda_i instead of λi\sqrt{\lambda_i}: eigenvalues of Σ\Sigma are variances, so the semi-axis lengths are standard deviations λi\sqrt{\lambda_i}.
  • Treating rows of vecs as eigenvectors instead of columns (vecs[:, i]).

Example 2 — Detect collinearity with rank and condition numbers

Section titled “Example 2 — Detect collinearity with rank and condition numbers”

Goal: Diagnose near-collinearity among monthly_charges, tenure_months, and total_charges in data/customers.csv and see how collinearity inflates regression weight instability.

Step 1 — Inspect rank, singular values and condition number on customer billing columns

Section titled “Step 1 — Inspect rank, singular values and condition number on customer billing columns”

Drop the 10 new customers with missing total_charges, standardize the numeric billing features, and check rank and condition numbers before and after adding a redundant feature (est_total = monthly_charges * tenure_months).

cust_clean = customers.dropna(subset=["total_charges"]).copy()
cust_clean["est_total"] = cust_clean["monthly_charges"] * cust_clean["tenure_months"]
cols_base = ["age", "tenure_months", "monthly_charges", "total_charges"]
cols_collinear = cols_base + ["est_total"]
def inspect_matrix(df: pd.DataFrame, cols: list[str], label: str) -> np.ndarray:
X_raw = df[cols].to_numpy(dtype=float)
Z = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
s = np.linalg.svd(Z, compute_uv=False)
rank = np.linalg.matrix_rank(Z)
print(f"{label}: rank={rank}/{Z.shape[1]}, cond={s[0] / s[-1]:.2f}")
print(" singular values:", np.round(s, 3))
return Z
Z_base = inspect_matrix(cust_clean, cols_base, "base 4 cols ")
Z_coll = inspect_matrix(cust_clean, cols_collinear, "with est_total ")
Output
base 4 cols : rank=4/4, cond=5.93
singular values: [98.505 70.655 70.63 16.614]
with est_total : rank=5/5, cond=63.34
singular values: [120.842 70.655 70.63 19.047 1.908]

Look at the smallest singular value: adding est_total makes the smallest singular value plunge toward zero because total_charges is already within roughly 6% of monthly_charges * tenure_months. The condition number jumps dramatically.

Step 2 — Measure how collinearity amplifies coefficient sensitivity

Section titled “Step 2 — Measure how collinearity amplifies coefficient sensitivity”

Compute the Variance Inflation Factor (VIF) for each column—how much the variance of its OLS weight increases compared to orthogonal predictors. For standardized features with correlation matrix RR, VIFj=(R−1)jj\text{VIF}_j = (R^{-1})_{jj}.

R_base = np.corrcoef(Z_base, rowvar=False)
R_coll = np.corrcoef(Z_coll, rowvar=False)
vif_base = np.diag(np.linalg.inv(R_base))
vif_coll = np.diag(np.linalg.inv(R_coll))
for col, val in zip(cols_base, vif_base, strict=True):
print(f"base {col:16s} VIF = {val:7.2f}")
for col, val in zip(cols_collinear, vif_coll, strict=True):
print(f"collinear {col:16s} VIF = {val:7.2f}")
Output
base age VIF = 1.00
base tenure_months VIF = 7.96
base monthly_charges VIF = 2.34
base total_charges VIF = 9.30
collinear age VIF = 1.00
collinear tenure_months VIF = 8.08
collinear monthly_charges VIF = 2.37
collinear total_charges VIF = 682.47
collinear est_total VIF = 693.01

Even in the 4-column table, tenure_months and total_charges have elevated VIFs. Once est_total enters, the VIF of total_charges and est_total explodes past 680—meaning any small noise in the target causes massive, opposing swings in their fitted weights.

Common mistakes:

  • Computing np.linalg.cond on unstandardized columns: mixing age (range 18–80) and total_charges (range 30–8,300) inflates the condition number just from units, hiding real collinearity.
  • Dropping a feature solely because pairwise correlation is 0.8 without checking VIF or singular values (multicollinearity can involve three or more columns even when no pair exceeds 0.8).

Example 3 — Derive OLS as an orthogonal projection and verify residuals are perpendicular to X

Section titled “Example 3 — Derive OLS as an orthogonal projection and verify residuals are perpendicular to X”

Goal: Fit a log-price linear model on data/houses.csv via QR factorization, prove geometrically that the residual vector is orthogonal to every feature column, and compare QR stability against normal equations.

Step 1 — Build the design matrix and solve via QR factorization

Section titled “Step 1 — Build the design matrix and solve via QR factorization”

Use standardized numeric features plus a column of ones, then compute X=QRX = QR and solve Rw=Q⊤yR\mathbf{w} = Q^\top \mathbf{y}.

h_cols = [
"sqft",
"bedrooms",
"bathrooms",
"condition",
"distance_to_center_km",
"has_pool",
]
X_h = houses[h_cols].to_numpy(dtype=float)
X_h = (X_h - X_h.mean(axis=0)) / X_h.std(axis=0)
A_h = np.column_stack([np.ones(len(houses)), X_h])
y_h = np.log(houses["price"].to_numpy(dtype=float))
Q_h, R_h = np.linalg.qr(A_h)
w_qr_h = np.linalg.solve(R_h, Q_h.T @ y_h)
w_ls_h = np.linalg.lstsq(A_h, y_h)[0]
print("QR weights: ", np.round(w_qr_h, 4))
print("max |w_qr - w_ls|: ", f"{np.max(np.abs(w_qr_h - w_ls_h)):.2e}")
Output
QR weights: [12.9195 0.3501 -0.024 0.0515 0.143 -0.1932 0.0789]
max |w_qr - w_ls|: 1.42e-14

QR and lstsq agree to roughly 15 decimal places.

Step 2 — Verify residual orthogonality and the Pythagorean decomposition of variance

Section titled “Step 2 — Verify residual orthogonality and the Pythagorean decomposition of variance”

Compute y^=Aw=Q(Q⊤y)\hat{\mathbf{y}} = A\mathbf{w} = Q(Q^\top \mathbf{y}) and r=y−y^\mathbf{r} = \mathbf{y} - \hat{\mathbf{y}}. Check that A⊤r≈0A^\top \mathbf{r} \approx \mathbf{0} and that ∥y−yˉ∥22=∥y^−yˉ∥22+∥r∥22\lVert \mathbf{y} - \bar{y} \rVert_2^2 = \lVert \hat{\mathbf{y}} - \bar{y} \rVert_2^2 + \lVert \mathbf{r} \rVert_2^2, which is the geometric origin of R2R^2!

y_hat_h = Q_h @ (Q_h.T @ y_h)
resid_h = y_h - y_hat_h
print("max |A.T @ resid|:", f"{np.max(np.abs(A_h.T @ resid_h)):.2e}")
print("mean(resid): ", f"{resid_h.mean():.2e}")
sst = np.sum((y_h - y_h.mean()) ** 2)
sse = np.sum((y_hat_h - y_h.mean()) ** 2)
ssr = np.sum(resid_h**2)
print(f"SST = {sst:.4f}, SSE + SSR = {sse + ssr:.4f}, R^2 = {sse / sst:.4f}")
Output
max |A.T @ resid|: 3.58e-11
mean(resid): 1.19e-14
SST = 825.0468, SSE + SSR = 825.0468, R^2 = 0.7211

Because column 0 of A_h is all ones, A_h[:, 0] @ resid_h == 0 forces the residuals to have zero mean. And because y^−yˉ\hat{\mathbf{y}} - \bar{y} lies in the column space while r\mathbf{r} is orthogonal to it, R2=SSE/SST=cos⁡2θR^2 = \text{SSE} / \text{SST} = \cos^2\theta is literally the squared cosine of the angle between the centered target and its projection!

Common mistakes:

  • Forgetting the intercept column of ones: without it, residuals are still perpendicular to XX, but resid.mean() is no longer guaranteed to be 0 and SST=SSE+SSR\text{SST} = \text{SSE} + \text{SSR} breaks.
  • Calling np.linalg.qr(A, mode="complete") on a 3,000-row matrix: that allocates a 3000×30003000 \times 3000 dense QQ. The default mode="reduced" returns the compact 3000×p3000 \times p matrix.

Example 4 — Eigen-decomposition of the feature correlation matrix and PCA

Section titled “Example 4 — Eigen-decomposition of the feature correlation matrix and PCA”

Goal: Show that PCA on standardized features of data/houses.csv is mathematically identical to eigen-decomposition of the correlation matrix and to SVD of the standardized data matrix.

Step 1 — Compute correlation eigen-decomposition and SVD side by side

Section titled “Step 1 — Compute correlation eigen-decomposition and SVD side by side”

Select 7 complete numeric features from houses.csv, standardize them, and compute principal directions via three paths: eigh on the correlation matrix, svd on Z, and sklearn.decomposition.PCA.

pca_cols = [
"sqft",
"bedrooms",
"bathrooms",
"year_built",
"garage_spaces",
"condition",
"distance_to_center_km",
]
Z_p = houses[pca_cols].to_numpy(dtype=float)
Z_p = (Z_p - Z_p.mean(axis=0)) / Z_p.std(axis=0)
# Path 1: eigh on correlation matrix
corr_p = np.corrcoef(Z_p, rowvar=False)
evals_p, evecs_p = np.linalg.eigh(corr_p)
idx = np.argsort(evals_p)[::-1]
evals_p, evecs_p = evals_p[idx], evecs_p[:, idx]
var_ratio_eig = evals_p / evals_p.sum()
# Path 2: SVD on Z_p
_, s_p, Vt_p = np.linalg.svd(Z_p, full_matrices=False)
var_ratio_svd = (s_p**2) / np.sum(s_p**2)
# Path 3: scikit-learn PCA
sk_pca = PCA().fit(Z_p)
print("explained variance (eigh):", np.round(var_ratio_eig, 4))
print("matches SVD? ", np.allclose(var_ratio_eig, var_ratio_svd))
print("matches PCA? ", np.allclose(var_ratio_eig, sk_pca.explained_variance_ratio_))
Output
explained variance (eigh): [0.4098 0.2432 0.1382 0.1065 0.064 0.0237 0.0148]
matches SVD? True
matches PCA? True

Step 2 — Compare loadings up to sign and interpret the top two components

Section titled “Step 2 — Compare loadings up to sign and interpret the top two components”

Eigenvectors are unique only up to a sign flip (±1\pm 1), so align the sign of each eigenvector to scikit-learn’s components_ and print the loadings of PC1 and PC2.

loadings = pd.DataFrame(
{"PC1": sk_pca.components_[0], "PC2": sk_pca.components_[1]},
index=pca_cols,
)
# Check absolute dot product between eigh columns and sklearn rows equals 1
cos_align = np.abs(np.sum(evecs_p.T * sk_pca.components_, axis=1))
print("min |cos(eigh, sklearn)|:", f"{cos_align.min():.6f}")
print(loadings.round(3))
Output
min |cos(eigh, sklearn)|: 1.000000
PC1 PC2
sqft 0.539 -0.180
bedrooms 0.545 -0.199
bathrooms 0.544 -0.202
year_built 0.215 0.576
garage_spaces 0.153 0.260
condition 0.136 0.455
distance_to_center_km 0.170 0.529

The cosine alignment is 1.000000 on every component. PC1 loads heavily on sqft, bedrooms, and bathrooms (overall house size, explaining 41% of total variance), while PC2 loads positively on year_built, distance_to_center_km, and condition (newer suburban homes farther from the city center in better condition vs. older urban homes, explaining another 24%).

Common mistakes:

  • Comparing eigenvectors directly with np.allclose(evecs_p.T, sk_pca.components_) without accounting for sign flips: both v and -v represent the same principal axis.
  • Running PCA on raw unstandardized features: sqft has variance ~500,000 while condition has variance ~0.9, so PC1 would simply copy sqft.

Example 5 — Compress the stores by months sales matrix with truncated SVD

Section titled “Example 5 — Compress the stores by months sales matrix with truncated SVD”

Goal: Factor the 12×2412 \times 24 stores-by-months revenue matrix from data/sales.csv with SVD, verify the Eckart–Young Frobenius error formula at every rank kk, and visualize the singular value spectrum.

Step 1 — Pivot monthly revenue per store and compute SVD

Section titled “Step 1 — Pivot monthly revenue per store and compute SVD”

Aggregate data/sales.csv into a matrix with 12 rows (store_id) and 24 columns (YYYY-MM).

sales_m = sales.assign(month=sales["order_date"].str.slice(0, 7))
rev_mat = sales_m.pivot_table(
index="store_id", columns="month", values="revenue", aggfunc="sum", fill_value=0.0
)
M_rev = rev_mat.to_numpy(dtype=float)
U_m, s_m, Vt_m = np.linalg.svd(M_rev, full_matrices=False)
print("matrix shape:", M_rev.shape, "rank:", np.linalg.matrix_rank(M_rev))
print("top 6 singular values:", np.round(s_m[:6], 1))
Output
matrix shape: (12, 24) rank: 12
top 6 singular values: [235247.3 25609.5 21027.7 18594.6 17537.9 15906. ]

Step 2 — Compare actual reconstruction error against the Eckart–Young formula

Section titled “Step 2 — Compare actual reconstruction error against the Eckart–Young formula”

For k=1,2,3,4,6k = 1, 2, 3, 4, 6, reconstruct Mk=U:,:kdiag⁡(s:k)V:k,:⊤M_k = U_{:, :k} \operatorname{diag}(s_{:k}) V^\top_{:k, :}, compare ∥M−Mk∥F\lVert M - M_k \rVert_F to ∑i>ksi2\sqrt{\sum_{i>k} s_i^2}, and measure the share of squared Frobenius energy captured.

total_energy = np.sum(s_m**2)
for k in [1, 2, 3, 4, 6]:
M_k = (U_m[:, :k] * s_m[:k]) @ Vt_m[:k, :]
err_actual = np.linalg.norm(M_rev - M_k, ord="fro")
err_theory = np.sqrt(np.sum(s_m[k:] ** 2))
captured = np.sum(s_m[:k] ** 2) / total_energy * 100
params = k * (M_rev.shape[0] + M_rev.shape[1] + 1)
print(
f"k={k}: frob_err={err_actual:8.1f} (theory {err_theory:8.1f}), "
f"energy={captured:5.2f}%, stored={params}/{M_rev.size}"
)
Output
k=1: frob_err= 51668.0 (theory 51668.0), energy=95.40%, stored=37/288
k=2: frob_err= 44874.7 (theory 44874.7), energy=96.53%, stored=74/288
k=3: frob_err= 39643.1 (theory 39643.1), energy=97.29%, stored=111/288
k=4: frob_err= 35011.6 (theory 35011.6), energy=97.89%, stored=148/288
k=6: frob_err= 25792.2 (theory 25792.2), energy=98.85%, stored=222/288

Look how sharply the spectrum drops: rank 1 alone captures 95.4% of the matrix energy with only 37 stored numbers (instead of 288) because every store follows the same seasonal calendar (November–December spikes and gradual growth) scaled by store floor area (size_sqm). Rank 2 picks up the main exception—store S12 in Denver, which opened in June 2023 and had zero revenue in the first 5 months!

Step 3 — Plot the singular value spectrum and cumulative energy

Section titled “Step 3 — Plot the singular value spectrum and cumulative energy”
cum_energy = np.cumsum(s_m**2) / total_energy * 100
ranks = np.arange(1, len(s_m) + 1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.5, 3.6))
ax1.bar(ranks, s_m / 1000, color="tab:blue")
ax1.set_xlabel("singular value index k")
ax1.set_ylabel("singular value (thousand USD)")
ax1.set_title("Singular value spectrum (12 stores x 24 months)")
ax1.set_xticks(ranks)
ax2.plot(ranks, cum_energy, "o-", color="tab:green", lw=2)
ax2.axhline(99.0, linestyle="--", color="gray", lw=1, label="99% energy")
ax2.set_xlabel("rank k")
ax2.set_ylabel("cumulative energy (%)")
ax2.set_title("Low-rank compression curve")
ax2.set_xticks(ranks)
ax2.set_ylim(94, 100.5)
ax2.legend()
fig.tight_layout()
plt.show()
Left panel shows a bar chart of 12 singular values with k=1 towering at about 235 thousand USD and k=2 through k=12 below 26 thousand USD; right panel shows cumulative energy starting at 95.4 percent at k=1, rising steadily, and crossing 99 percent at k=7.
Singular value spectrum and cumulative energy of the stores-by-months revenue matrix.

Common mistakes:

  • Computing U_m[:, :k] @ np.diag(s_m[:k]) @ Vt_m[:k, :] on huge matrices: broadcasting (U_m[:, :k] * s_m[:k]) @ Vt_m[:k, :] avoids allocating an extra k×kk \times k diagonal matrix.
  • Forgetting that s is squared when computing variance or Frobenius energy (σi2\sigma_i^2, not σi\sigma_i).

Example 6 — Build a latent review-term space with SVD and compare to TruncatedSVD

Section titled “Example 6 — Build a latent review-term space with SVD and compare to TruncatedSVD”

Goal: Apply sparse truncated SVD (Latent Semantic Indexing) to the 3,000 product reviews in data/reviews.csv, verify that scipy.sparse.linalg.svds matches scikit-learn’s TruncatedSVD, and inspect the discovered semantic topics.

Step 1 — Build the sparse TF-IDF document-term matrix

Section titled “Step 1 — Build the sparse TF-IDF document-term matrix”

Vectorize reviews["text"] into a sparse matrix T∈R3000×VT \in \mathbb{R}^{3000 \times V}. Because TT is sparse (mostly zeros), dense np.linalg.svd would waste memory and time; sparse svds computes only the top kk singular triplets.

vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)
T_tfidf = vec.fit_transform(reviews["text"])
terms = np.array(vec.get_feature_names_out())
density = T_tfidf.nnz / (T_tfidf.shape[0] * T_tfidf.shape[1]) * 100
print(f"TF-IDF shape: {T_tfidf.shape}, non-zeros: {T_tfidf.nnz} ({density:.2f}% dense)")
Output
TF-IDF shape: (3000, 281), non-zeros: 24434 (2.90% dense)

Step 2 — Run scipy.sparse.linalg.svds and verify against TruncatedSVD

Section titled “Step 2 — Run scipy.sparse.linalg.svds and verify against TruncatedSVD”

Note one critical quirk: svds returns singular values in ascending order, whereas TruncatedSVD returns them in descending order. Reverse svds before comparing.

k_topics = 5
U_sp, s_sp, Vt_sp = svds(T_tfidf, k=k_topics, random_state=42)
order_sp = np.argsort(s_sp)[::-1]
s_sp, Vt_sp = s_sp[order_sp], Vt_sp[order_sp]
tsvd = TruncatedSVD(n_components=k_topics, algorithm="arpack", random_state=42)
tsvd.fit(T_tfidf)
print("svds singular values: ", np.round(s_sp, 4))
print("TruncatedSVD singular values:", np.round(tsvd.singular_values_, 4))
print("singular values match?", np.allclose(s_sp, tsvd.singular_values_, atol=1e-5))
Output
svds singular values: [12.8937 8.3255 8.1585 7.9415 7.9296]
TruncatedSVD singular values: [12.8937 8.3255 8.1585 7.9415 7.9296]
singular values match? True

Step 3 — Inspect the top words along each right singular vector

Section titled “Step 3 — Inspect the top words along each right singular vector”

Each row of Vt_sp is a unit vector in term space. Its largest-magnitude entries reveal the dominant cluster of co-occurring review words.

for i in range(k_topics):
row = Vt_sp[i]
# Flip sign so the largest-magnitude term is positive for readable printing
if abs(row.min()) > abs(row.max()):
row = -row
top_idx = np.argsort(row)[::-1][:6]
print(f"axis {i + 1} (sigma={s_sp[i]:.2f}): {', '.join(terms[top_idx])}")
Output
axis 1 (sigma=12.89): price, quality, great, material, recommend, feels
axis 2 (sigma=8.33): battery, sturdy, charge, built, holds, fast
axis 3 (sigma=8.16): sturdy, built, friends, definitely, recommend, size
axis 4 (sigma=7.94): price, point, beat, lower, stores, hard
axis 5 (sigma=7.93): feels, material, premium, quality, solid, cheap

Without a single label or manual rule, SVD separates distinct review themes (overall value and quality, battery life and durability, recommendation and fit, competitive pricing, and material feel) purely from word co-occurrence geometry.

Common mistakes:

  • Forgetting that scipy.sparse.linalg.svds returns singular values in ascending order; always reverse them with [::-1].
  • Centering a sparse TF-IDF matrix by subtracting column means: subtracting a dense mean destroys sparsity and blows up RAM. TruncatedSVD intentionally works on the uncentered sparse matrix.
Mistake Symptom Fix
Solving OLS with inv(X.T @ X) @ X.T @ y Massive rounding errors or LinAlgError on correlated features Use np.linalg.lstsq(X, y) or QR factorization R w = Q.T y
Using np.linalg.eig on a symmetric matrix Tiny complex parts (+0j), unsorted eigenvalues, non-orthogonal vectors on ties Always use np.linalg.eigh for symmetric matrices (covariance, correlation, Gram)
Indexing evecs[i] instead of evecs[:, i] A @ v != lam * v and wrong PCA projections Remember NumPy stores eigenvectors in columns (evecs[:, i]), whereas svd returns right singular vectors in rows of Vt (Vt[i])
Checking det(A) == 0 for singularity False positives on well-conditioned small-scale matrices or overflow in high dimensions Check np.linalg.matrix_rank(A) and np.linalg.cond(A), or use np.linalg.slogdet(A)
Comparing eigenvectors with == or allclose directly Fails when two solvers return v and -v Compare abs(u @ v) to 1.0, or align signs using the largest-magnitude entry
Computing cond(X) or PCA on unscaled features Feature with largest numeric unit dominates condition number and PC1 Standardize features first (zero mean, unit standard deviation)
Assuming svds returns descending singular values Selecting the smallest singular components instead of the largest Sort svds outputs with idx = np.argsort(s)[::-1]
  • Computer graphics and 3-D game engines: Every camera movement, object rotation, scaling, and shadow projection is a chain of 4×44 \times 4 matrix multiplications, using orthogonal rotation matrices so models never warp or shrink.
  • Image, audio, and video compression: Truncated SVD and orthogonal basis transforms (such as the Discrete Cosine Transform in JPEG and MP3) discard small-energy components while keeping perceptual fidelity high.
  • Search engines and network analysis: Google’s original PageRank models web browsing as a Markov transition matrix and computes its principal eigenvector via power iteration; spectral clustering partitions social and road networks using eigenvectors of the graph Laplacian.
  • Robotics and structural engineering: Robot arm kinematics use orthogonal transformations and pseudoinverses (SVD) to convert target hand positions into joint angles, while finite-element stress analysis solves huge sparse symmetric positive definite linear systems.
  • A matrix AA is a linear transformation whose columns show where the basis vectors land; its rank is the dimension of its column space, and a nonzero null space signals linearly dependent features.
  • Orthonormal matrices satisfy Q⊤Q=IQ^\top Q = I, preserve lengths and angles, and turn coordinates and projections into simple matrix products (P=QQ⊤P = QQ^\top).
  • Ordinary least squares is the orthogonal projection of y\mathbf{y} onto col⁡(X)\operatorname{col}(X), making residuals perpendicular to every feature column (X⊤r=0X^\top \mathbf{r} = \mathbf{0}).
  • QR factorization solves least squares via Rw=Q⊤yR\mathbf{w} = Q^\top \mathbf{y} without forming X⊤XX^\top X, avoiding the κ(X)2\kappa(X)^2 condition-number explosion.
  • The determinant measures signed volume scaling; eigenvalues and eigenvectors identify invariant stretch directions, and the spectral theorem guarantees real eigenvalues and orthogonal eigenvectors for every symmetric matrix.
  • Positive definite covariance matrices define ellipsoids whose axes are eigenvectors and whose semi-axis lengths are λi\sqrt{\lambda_i}.
  • SVD (A=UΣV⊤A = U\Sigma V^\top) works on any matrix, powers numerically stable PCA, gives the optimal low-rank approximation (Eckart–Young), and defines the Moore–Penrose pseudoinverse A+=VΣ+U⊤A^+ = V\Sigma^+ U^\top.

Q1. A matrix AA has 6 columns, and np.linalg.matrix_rank(A) returns 4. What is the dimension of its null space, and what does that mean for linear regression on AA?

Answer

By the rank–nullity theorem, dim⁡(null⁡(A))=6−4=2\dim(\operatorname{null}(A)) = 6 - 4 = 2. Two columns are redundant linear combinations of the others, so infinitely many weight vectors produce the exact same predictions AwA\mathbf{w}. Normal equations solve(A.T @ A, A.T @ y) will fail or blow up; you need lstsq (minimum-norm solution), Ridge regularization, or feature pruning.

Q2. Why does multiplying a vector by an orthogonal matrix QQ leave its Euclidean length unchanged?

Answer

Because Q⊤Q=IQ^\top Q = I, we have ∥Qx∥22=(Qx)⊤(Qx)=x⊤Q⊤Qx=x⊤x=∥x∥22\lVert Q\mathbf{x} \rVert_2^2 = (Q\mathbf{x})^\top (Q\mathbf{x}) = \mathbf{x}^\top Q^\top Q \mathbf{x} = \mathbf{x}^\top \mathbf{x} = \lVert \mathbf{x} \rVert_2^2. Geometrically, an orthogonal matrix is a rigid rotation or reflection.

Q3. How do you verify in one line of NumPy that a least-squares fit y^=Xw\hat{\mathbf{y}} = X\mathbf{w} really is the orthogonal projection of y\mathbf{y} onto col⁡(X)\operatorname{col}(X)?

Answer

Check np.allclose(X.T @ (y - X @ w), 0). If the residual vector is orthogonal to every column of XX, its dot product with each column is zero (up to floating-point tolerance).

Q4. Suppose a design matrix XX has condition number κ(X)=105\kappa(X) = 10^5. What is the approximate condition number of X⊤XX^\top X, and which solver should you prefer?

Answer

κ(X⊤X)=κ(X)2=1010\kappa(X^\top X) = \kappa(X)^2 = 10^{10}. Prefer QR factorization or SVD (np.linalg.lstsq), which work directly on XX with condition number 10510^5 instead of squaring it to 101010^{10}.

Q5. A 2×22 \times 2 transformation matrix has determinant −3.5-3.5. What does that tell you geometrically about how it transforms shapes?

Answer

It scales every 2-D area by a factor of 3.53.5 and flips orientation (it includes a reflection). Because the determinant is nonzero, the transformation is invertible.

Q6. Why should you call np.linalg.eigh instead of np.linalg.eig on a sample covariance matrix?

Answer

A covariance matrix is symmetric, so by the spectral theorem its eigenvalues are guaranteed real and its eigenvectors can be chosen mutually orthogonal. eigh exploits symmetry for speed, guarantees real floating-point outputs without +0j artifacts, sorts eigenvalues ascending, and guarantees orthonormal eigenvectors even for repeated eigenvalues.

Q7. How can you check whether a symmetric matrix SS is positive definite in NumPy?

Answer

Compute its eigenvalues with vals = np.linalg.eigvalsh(S) and check np.all(vals > 0) (or attempt Cholesky factorization np.linalg.cholesky(S), which succeeds if and only if SS is symmetric positive definite).

Q8. How are the singular values of a centered data matrix XcX_c (with nn rows) related to the eigenvalues of its sample covariance matrix Σ=1n−1Xc⊤Xc\Sigma = \frac{1}{n-1} X_c^\top X_c?

Answer

The eigenvalues of Σ\Sigma are λi=σi2/(n−1)\lambda_i = \sigma_i^2 / (n - 1), where σi\sigma_i are the singular values of XcX_c. Both methods yield the same principal directions and explained variance ratios, but SVD avoids forming Xc⊤XcX_c^\top X_c.

Q9. A matrix MM has singular values [10, 4, 2, 1]. Without building the reconstructed matrix, what is the exact Frobenius norm error ∥M−M2∥F\lVert M - M_2 \rVert_F of its best rank-2 approximation?

Answer

By the Eckart–Young theorem, the error equals the square root of the sum of squared discarded singular values: 22+12=5≈2.236\sqrt{2^2 + 1^2} = \sqrt{5} \approx 2.236.

Q10. When np.linalg.svd(A, full_matrices=False) returns U, s, Vt, how do you compute the Moore–Penrose pseudoinverse A+A^+, and what do you do with tiny singular values near zero?

Answer

Invert only the singular values above a numerical tolerance (setting smaller ones to 0.0), then compute (Vt.T * s_inv) @ U.T. Zeroing tiny singular values prevents division by floating-point noise from blowing up the solution.

Your progress

0 / 4 done

  • Exercises: 25 exercises (warm-up, core, and challenge) with hints, assertions, and full solutions.
  • Mini-project: build a from-scratch PCA, Ridge, and collinearity auditor in pure NumPy.
  • Cheat sheet: quick lookup table, matrix decomposition guide, and gotchas.
  • Next module: 47. Calculus and optimization for ML builds derivatives, Jacobians, Hessians, and optimizers on top of these linear algebra tools.