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.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Math |
|---|---|---|
| count linearly independent columns | np.linalg.matrix_rank(X) |
|
| find null-space dimension | X.shape[1] - np.linalg.matrix_rank(X) |
|
| measure numerical fragility | np.linalg.cond(X) |
|
| compute a 2-D rotation matrix | [[cos(t), -sin(t)], [sin(t), cos(t)]] |
|
| check if columns are orthonormal | np.allclose(Q.T @ Q, np.eye(p)) |
|
project vector y onto vector a |
((a @ y) / (a @ a)) * a |
|
project y onto orthonormal basis Q |
Q @ (Q.T @ y) |
|
| compute reduced QR factorization | Q, R = np.linalg.qr(X) |
|
| solve least squares via QR | np.linalg.solve(R, Q.T @ y) |
|
| solve general least squares safely | np.linalg.lstsq(X, y)[0] |
|
| compute signed volume scaling | np.linalg.det(A) |
|
| compute stable log-determinant | sign, logdet = np.linalg.slogdet(A) |
|
| eigendecompose a symmetric matrix | vals, vecs = np.linalg.eigh(S) |
|
| get symmetric eigenvalues only | np.linalg.eigvalsh(S) |
|
sort eigh descending |
idx = np.argsort(vals)[::-1] |
|
| test positive definiteness | np.all(np.linalg.eigvalsh(S) > 0) |
|
| compute reduced SVD | U, s, Vt = np.linalg.svd(A, full_matrices=False) |
|
| compute singular values only | np.linalg.svd(A, compute_uv=False) |
|
build rank-k approximation |
(U[:, :k] * s[:k]) @ Vt[:k, :] |
|
| get exact Eckart–Young Frobenius error | np.sqrt(np.sum(s[k:] ** 2)) |
|
| compute Moore–Penrose pseudoinverse | np.linalg.pinv(A) |
|
| fit Ridge regression via SVD | Vt.T @ ((s / (s**2 + lam)) * (U.T @ y)) |
|
compute VIF from standardized Z |
np.diag(np.linalg.inv(np.corrcoef(Z, rowvar=False))) |
|
compute sparse top-k SVD |
scipy.sparse.linalg.svds(M, k=k) (then reverse!) |
top singular triplets |
Transformations, rank and determinants
Section titled “Transformations, rank and determinants”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))rotate (2, 1) by 90 deg: [-1. 2.]det(R90): 1.0rank: 2 null dim: 1slogdet(0.5 * I_20): 1.0 -13.8629Orthogonality, projections and QR
Section titled “Orthogonality, projections and QR”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 formedy_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))w_qr: [1.13 0.98]Q orthonormal: TrueA.T @ resid == 0: TrueKey projection identities (when has orthonormal columns spanning ):
- Projection matrix:
- Symmetry and idempotence: and
- Residual orthogonality:
- Pythagorean theorem:
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 1Sigma = np.cov(Z, rowvar=False)
vals, vecs = np.linalg.eigh(Sigma) # real eigenvalues, orthogonal columnsorder = np.argsort(vals)[::-1] # flip to descending ordervals, 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))eigenvalues: [1.8831 0.8817 0.1823]positive definite: Truespectral reconstruction ok: TrueSVD, 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 checkX_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 yy_reg = X_c @ np.array([2.0, -1.0, 0.5]) + rng.normal(0, 0.2, size=len(X_c))lam = 10.0w_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))Eckart-Young match: TrueRidge SVD weights: [ 1.6646 -0.6902 0.4424]matches closed form: TrueChoosing a matrix decomposition
Section titled “Choosing a matrix decomposition”| Decomposition | Formula | Matrix requirement | Primary ML / data use | NumPy / SciPy call |
|---|---|---|---|---|
| Cholesky | Square, symmetric, positive definite | Fast normal equations when well-conditioned, sampling correlated Gaussians | np.linalg.cholesky(S) |
|
| QR | Tall (), full column rank | Numerically stable OLS without forming , orthonormalization | np.linalg.qr(X) |
|
| Symmetric Eigen | Square, symmetric | Covariance/correlation geometry, spectral clustering, Hessian curvature | np.linalg.eigh(S) |
|
| General Eigen | Square | Markov chains, PageRank, dynamical systems | np.linalg.eig(A) |
|
| Reduced SVD | Any shape, any rank | PCA, low-rank compression, pseudoinverse, Ridge shrinkage, rank/condition check | np.linalg.svd(A, full_matrices=False) |
|
| Sparse SVD | Large sparse matrix | Latent Semantic Indexing (TF-IDF), recommender systems | scipy.sparse.linalg.svds(A, k=k) |
Gotchas
Section titled “Gotchas”- Eigenvectors are columns, right singular vectors are rows:
eighreturns eigenvectors invecs[:, i], whilesvdreturns right singular vectors inVt[i, :](the transpose!). - Sorting direction differs across functions:
eighandscipy.sparse.linalg.svdsreturn values in ascending order;np.linalg.svdand scikit-learnPCA/TruncatedSVDreturn them in descending order. - Sign ambiguity: Both and are valid eigenvectors or singular vectors. Compare directions with
abs(u @ v)instead ofnp.allclose(u, v). - Never square the condition number unnecessarily: Forming
X.T @ Xsquares . Useqr,svd, orlstsqdirectly onX. - Standardize before diagnostics: Unstandardized columns with different units (like
sqftvs.bedrooms) makecond(X)and PCA reflect measurement scale rather than correlation. - Do not use
det(A) == 0to test invertibility: Determinants scale as in dimensions and underflow/overflow easily. Usematrix_rank,cond, orslogdet. - Avoid dense
np.diag(s)inside SVD reconstructions: Write(U[:, :k] * s[:k]) @ Vt[:k, :]to save memory and time.