Skip to content

46. Linear algebra in depth — Cheat sheet

The essentials of module 46 on one page: every matrix concept paired with its formula and NumPy/SciPy idiom. Every runnable code block on this page is verified against its output.

I want to… Use… Math
count linearly independent columns np.linalg.matrix_rank(X) rank⁡(X)\operatorname{rank}(X)
find null-space dimension X.shape[1] - np.linalg.matrix_rank(X) p−rank⁡(X)p - \operatorname{rank}(X)
measure numerical fragility np.linalg.cond(X) κ(X)=σmax⁡/σmin⁡\kappa(X) = \sigma_{\max} / \sigma_{\min}
compute a 2-D rotation matrix [[cos(t), -sin(t)], [sin(t), cos(t)]] R(θ)R(\theta)
check if columns are orthonormal np.allclose(Q.T @ Q, np.eye(p)) Q⊤Q=IQ^\top Q = I
project vector y onto vector a ((a @ y) / (a @ a)) * a a⊤ya⊤aa\frac{\mathbf{a}^\top\mathbf{y}}{\mathbf{a}^\top\mathbf{a}}\mathbf{a}
project y onto orthonormal basis Q Q @ (Q.T @ y) QQ⊤yQQ^\top\mathbf{y}
compute reduced QR factorization Q, R = np.linalg.qr(X) X=QRX = QR
solve least squares via QR np.linalg.solve(R, Q.T @ y) Rw=Q⊤yR\mathbf{w} = Q^\top\mathbf{y}
solve general least squares safely np.linalg.lstsq(X, y)[0] min⁡w∥Xw−y∥22\min_\mathbf{w}\lVert X\mathbf{w} - \mathbf{y}\rVert_2^2
compute signed volume scaling np.linalg.det(A) det⁡(A)\det(A)
compute stable log-determinant sign, logdet = np.linalg.slogdet(A) log⁡∣det⁡(A)∣\log\lvert\det(A)\rvert
eigendecompose a symmetric matrix vals, vecs = np.linalg.eigh(S) S=QΛQ⊤S = Q\Lambda Q^\top
get symmetric eigenvalues only np.linalg.eigvalsh(S) λ1≤⋯≤λp\lambda_1 \le \dots \le \lambda_p
sort eigh descending idx = np.argsort(vals)[::-1] λ1≥⋯≥λp\lambda_1 \ge \dots \ge \lambda_p
test positive definiteness np.all(np.linalg.eigvalsh(S) > 0) x⊤Sx>0\mathbf{x}^\top S\mathbf{x} > 0
compute reduced SVD U, s, Vt = np.linalg.svd(A, full_matrices=False) A=UΣV⊤A = U\Sigma V^\top
compute singular values only np.linalg.svd(A, compute_uv=False) σ1≥⋯≥σr\sigma_1 \ge \dots \ge \sigma_r
build rank-k approximation (U[:, :k] * s[:k]) @ Vt[:k, :] Ak=UkΣkVk⊤A_k = U_k\Sigma_k V_k^\top
get exact Eckart–Young Frobenius error np.sqrt(np.sum(s[k:] ** 2)) ∥A−Ak∥F\lVert A - A_k \rVert_F
compute Moore–Penrose pseudoinverse np.linalg.pinv(A) A+=VΣ+U⊤A^+ = V\Sigma^+ U^\top
fit Ridge regression via SVD Vt.T @ ((s / (s**2 + lam)) * (U.T @ y)) ∑iσiσi2+λ(ui⊤y)vi\sum_i \frac{\sigma_i}{\sigma_i^2+\lambda}(\mathbf{u}_i^\top\mathbf{y})\mathbf{v}_i
compute VIF from standardized Z np.diag(np.linalg.inv(np.corrcoef(Z, rowvar=False))) VIFj=(R−1)jj\text{VIF}_j = (R^{-1})_{jj}
compute sparse top-k SVD scipy.sparse.linalg.svds(M, k=k) (then reverse!) top kk singular triplets
import numpy as np
np.set_printoptions(precision=4, suppress=True)
theta = np.deg2rad(90)
R90 = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
print("rotate (2, 1) by 90 deg:", R90 @ np.array([2.0, 1.0]))
print("det(R90):", round(float(np.linalg.det(R90)), 4)) # area preserved
# col 3 = col 1 + col 2 (linearly dependent)
X = np.array([[1.0, 2.0, 3.0], [2.0, 1.0, 3.0], [3.0, 0.0, 3.0]])
rank = np.linalg.matrix_rank(X)
print("rank:", rank, "null dim:", X.shape[1] - rank)
sign, logdet = np.linalg.slogdet(np.eye(20) * 0.5)
print("slogdet(0.5 * I_20):", sign, round(float(logdet), 4))
Output
rotate (2, 1) by 90 deg: [-1. 2.]
det(R90): 1.0
rank: 2 null dim: 1
slogdet(0.5 * I_20): 1.0 -13.8629
A = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0]])
y = np.array([1.2, 2.1, 2.9, 4.2])
Q, R = np.linalg.qr(A) # reduced QR: Q is (4, 2), R is (2, 2)
w_qr = np.linalg.solve(R, Q.T @ y) # no X.T @ X formed
y_hat = Q @ (Q.T @ y) # orthogonal projection onto col(A)
resid = y - y_hat
print("w_qr:", w_qr)
print("Q orthonormal:", np.allclose(Q.T @ Q, np.eye(2)))
print("A.T @ resid == 0:", np.allclose(A.T @ resid, 0))
Output
w_qr: [1.13 0.98]
Q orthonormal: True
A.T @ resid == 0: True

Key projection identities (when QQ has orthonormal columns spanning col⁡(A)\operatorname{col}(A)):

  • Projection matrix: P=QQ⊤=A(A⊤A)−1A⊤P = QQ^\top = A(A^\top A)^{-1}A^\top
  • Symmetry and idempotence: P⊤=PP^\top = P and P2=PP^2 = P
  • Residual orthogonality: A⊤(y−y^)=0A^\top(\mathbf{y} - \hat{\mathbf{y}}) = \mathbf{0}
  • Pythagorean theorem: ∥y∥22=∥y^∥22+∥y−y^∥22\lVert \mathbf{y} \rVert_2^2 = \lVert \hat{\mathbf{y}} \rVert_2^2 + \lVert \mathbf{y} - \hat{\mathbf{y}} \rVert_2^2

Eigenvalues, positive definiteness and covariance

Section titled “Eigenvalues, positive definiteness and covariance”
rng = np.random.default_rng(42)
Z = rng.normal(size=(200, 3))
Z[:, 1] = 0.8 * Z[:, 0] + 0.6 * Z[:, 1] # correlate features 0 and 1
Sigma = np.cov(Z, rowvar=False)
vals, vecs = np.linalg.eigh(Sigma) # real eigenvalues, orthogonal columns
order = np.argsort(vals)[::-1] # flip to descending order
vals, vecs = vals[order], vecs[:, order]
print("eigenvalues:", vals)
print("positive definite:", bool(np.all(vals > 0)))
print("spectral reconstruction ok:", np.allclose(vecs @ np.diag(vals) @ vecs.T, Sigma))
Output
eigenvalues: [1.8831 0.8817 0.1823]
positive definite: True
spectral reconstruction ok: True

SVD, low-rank approximation, pseudoinverse and Ridge

Section titled “SVD, low-rank approximation, pseudoinverse and Ridge”
X_c = Z - Z.mean(axis=0)
U, s, Vt = np.linalg.svd(X_c, full_matrices=False)
# Rank-1 approximation and Eckart-Young error check
X_1 = (U[:, :1] * s[:1]) @ Vt[:1, :]
err_frob = np.linalg.norm(X_c - X_1, ord="fro")
err_ey = np.sqrt(np.sum(s[1:] ** 2))
print("Eckart-Young match:", np.isclose(err_frob, err_ey))
# Ridge regression via SVD shrinkage vs closed-form (X.T @ X + lam I)^-1 X.T y
y_reg = X_c @ np.array([2.0, -1.0, 0.5]) + rng.normal(0, 0.2, size=len(X_c))
lam = 10.0
w_ridge_svd = Vt.T @ ((s / (s**2 + lam)) * (U.T @ y_reg))
w_ridge_eq = np.linalg.solve(X_c.T @ X_c + lam * np.eye(3), X_c.T @ y_reg)
print("Ridge SVD weights:", w_ridge_svd)
print("matches closed form:", np.allclose(w_ridge_svd, w_ridge_eq))
Output
Eckart-Young match: True
Ridge SVD weights: [ 1.6646 -0.6902 0.4424]
matches closed form: True
Decomposition Formula Matrix requirement Primary ML / data use NumPy / SciPy call
Cholesky S=LL⊤S = LL^\top Square, symmetric, positive definite Fast normal equations when well-conditioned, sampling correlated Gaussians np.linalg.cholesky(S)
QR X=QRX = QR Tall (n≥pn \ge p), full column rank Numerically stable OLS without forming X⊤XX^\top X, orthonormalization np.linalg.qr(X)
Symmetric Eigen S=QΛQ⊤S = Q\Lambda Q^\top Square, symmetric Covariance/correlation geometry, spectral clustering, Hessian curvature np.linalg.eigh(S)
General Eigen A=VΛV−1A = V\Lambda V^{-1} Square Markov chains, PageRank, dynamical systems np.linalg.eig(A)
Reduced SVD A=UΣV⊤A = U\Sigma V^\top Any shape, any rank PCA, low-rank compression, pseudoinverse, Ridge shrinkage, rank/condition check np.linalg.svd(A, full_matrices=False)
Sparse SVD A≈UkΣkVk⊤A \approx U_k\Sigma_k V_k^\top Large sparse matrix Latent Semantic Indexing (TF-IDF), recommender systems scipy.sparse.linalg.svds(A, k=k)
  • Eigenvectors are columns, right singular vectors are rows: eigh returns eigenvectors in vecs[:, i], while svd returns right singular vectors in Vt[i, :] (the transpose!).
  • Sorting direction differs across functions: eigh and scipy.sparse.linalg.svds return values in ascending order; np.linalg.svd and scikit-learn PCA/TruncatedSVD return them in descending order.
  • Sign ambiguity: Both v\mathbf{v} and −v-\mathbf{v} are valid eigenvectors or singular vectors. Compare directions with abs(u @ v) instead of np.allclose(u, v).
  • Never square the condition number unnecessarily: Forming X.T @ X squares κ(X)\kappa(X). Use qr, svd, or lstsq directly on X.
  • Standardize before diagnostics: Unstandardized columns with different units (like sqft vs. bedrooms) make cond(X) and PCA reflect measurement scale rather than correlation.
  • Do not use det(A) == 0 to test invertibility: Determinants scale as cpc^p in pp dimensions and underflow/overflow easily. Use matrix_rank, cond, or slogdet.
  • Avoid dense np.diag(s) inside SVD reconstructions: Write (U[:, :k] * s[:k]) @ Vt[:k, :] to save memory and time.