Linear algebra
Linear algebra is the working language of numerical Python, least squares, PCA, embeddings, and neural networks. This sheet covers notation, matrix identities, decompositions, and the np.linalg / scipy.linalg API. All runnable blocks share one session using data/houses.csv, data/customers.csv, and data/sales.csv:
import numpy as npimport pandas as pdfrom scipy import linalg
houses = pd.read_csv("data/houses.csv")customers = pd.read_csv("data/customers.csv")sales = pd.read_csv("data/sales.csv")Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| multiply matrices or matrix-vector | A @ B, A @ x |
never * (that is elementwise) |
| compute dot product or cosine similarity | u @ v, (u @ v) / (norm(u) * norm(v)) |
np.linalg.norm |
| vector , , norms | np.linalg.norm(v, ord=1 / 2 / np.inf) |
default is |
| matrix Frobenius or spectral norm | np.linalg.norm(A, "fro") / ord=2 |
spectral norm |
| solve a square linear system | np.linalg.solve(A, b) |
faster and cleaner than inv(A) @ b |
| solve least squares | np.linalg.lstsq(X, y, rcond=None) |
SVD-based; handles rank deficiency |
| check linear independence / collinearity | np.linalg.matrix_rank(X), np.linalg.cond(X) |
signals ill-conditioning |
| orthonormal basis for column space | Q, R = np.linalg.qr(X, mode="reduced") |
; stable OLS |
| eigenvalues of a symmetric matrix | vals, vecs = np.linalg.eigh(S) |
real, sorted ascending, orthonormal vecs |
| test symmetric positive definiteness | np.linalg.cholesky(S) |
succeeds iff all |
| full or reduced SVD | U, s, Vt = np.linalg.svd(A, full_matrices=False) |
Vt is already transposed () |
| Moore–Penrose pseudoinverse | np.linalg.pinv(A) |
replaces nonzero with |
| best rank- matrix approximation | (U[:, :k] * s[:k]) @ Vt[:k, :] |
Eckart–Young optimal in Frobenius & spectral norm |
Shapes, products and norms
Section titled “Shapes, products and norms”| Operation | Math | Shapes | NumPy |
|---|---|---|---|
| inner (dot) product | u @ v or np.dot(u, v) |
||
| outer product | np.outer(u, v) |
||
| matrix multiply | A @ B |
||
| Hadamard (elementwise) | A * B |
||
| transpose | A.T |
||
| trace | np.trace(A) |
||
| determinant | (volume scale) | np.linalg.det(A) |
|
| vector norm | np.linalg.norm(v, ord=p) |
||
| Frobenius norm | np.linalg.norm(A, "fro") |
||
| spectral norm | np.linalg.norm(A, ord=2) |
Key algebraic identities: , , , , and .
u = np.array([3.0, -4.0, 0.0])v = np.array([1.0, 2.0, 2.0])cos_sim = (u @ v) / (np.linalg.norm(u) * np.linalg.norm(v))print("L1, L2, Linf:", [float(np.linalg.norm(u, p)) for p in (1, 2, np.inf)])print("cosine similarity:", round(float(cos_sim), 4))L1, L2, Linf: [7.0, 5.0, 4.0]cosine similarity: -0.3333Rank, span, conditioning and linear systems
Section titled “Rank, span, conditioning and linear systems”For an matrix :
- Rank is the number of linearly independent columns (and rows), equal to the number of nonzero singular values.
- Rank–Nullity Theorem: .
- Condition number: . Each order of magnitude in can cost roughly one decimal digit of accuracy when solving . Notice that forming normal equations squares the condition number: .
sub = customers[["monthly_charges", "tenure_months", "total_charges"]].dropna()raw = sub.to_numpy()std = (raw - raw.mean(axis=0)) / raw.std(axis=0)# Add an exact linear combination to show rank droprank_def = np.column_stack([std, std[:, 0] + 2 * std[:, 1]])
print( "raw cond vs standardized cond:", round(np.linalg.cond(raw), 1), round(np.linalg.cond(std), 2),)print("rank of 3 features:", int(np.linalg.matrix_rank(std)))print("rank with exact combo:", int(np.linalg.matrix_rank(rank_def)))raw cond vs standardized cond: 181.8 5.93rank of 3 features: 3rank with exact combo: 3Orthogonality, projections and QR
Section titled “Orthogonality, projections and QR”A vector projected onto the column space of a full-rank matrix is where the orthogonal projection matrix is . Its defining property is that the residual is perpendicular to every column of :
Factoring (with and upper triangular) avoids squaring the condition number: is solved directly by back-substitution, and .
feat = houses[["sqft", "bedrooms", "bathrooms", "condition"]].to_numpy(dtype=float)X = np.column_stack([np.ones(len(feat)), (feat - feat.mean(0)) / feat.std(0)])y = np.log(houses["price"].to_numpy(dtype=float))
# Compare QR, SVD lstsq, and normal equationsQ, R = np.linalg.qr(X, mode="reduced")w_qr = linalg.solve_triangular(R, Q.T @ y)w_lstsq, _, _, _ = np.linalg.lstsq(X, y, rcond=None)w_norm = np.linalg.solve(X.T @ X, X.T @ y)resid = y - X @ w_qr
print("QR weights:", np.round(w_qr, 4))print("max diff QR vs lstsq:", f"{np.max(np.abs(w_qr - w_lstsq)):.2e}")print("max diff QR vs normal eq:", f"{np.max(np.abs(w_qr - w_norm)):.2e}")print("max |X.T @ resid|:", f"{np.max(np.abs(X.T @ resid)):.2e}")QR weights: [12.9195 0.3468 -0.0195 0.0508 0.1079]max diff QR vs lstsq: 1.24e-14max diff QR vs normal eq: 1.24e-14max |X.T @ resid|: 3.51e-11Eigenvalues, symmetric matrices and positive definiteness
Section titled “Eigenvalues, symmetric matrices and positive definiteness”An eigenvector satisfies : the transformation only stretches by .
- Spectral Theorem: Every real symmetric matrix has real eigenvalues and an orthonormal eigenbasis: with .
- Positive definiteness (SPD): is positive definite () iff for all , iff all , iff a unique Cholesky factor exists. Covariance and correlation matrices are always positive semi-definite ().
Z = (feat - feat.mean(0)) / feat.std(0)corr = (Z.T @ Z) / len(Z) # 4x4 feature correlation matrixvals, vecs = np.linalg.eigh(corr) # ascending order for symmetric matricesvals, vecs = vals[::-1], vecs[:, ::-1] # sort descending (PCA order)L = np.linalg.cholesky(corr) # succeeds iff strictly positive definite
print("eigenvalues:", np.round(vals, 4))print("variance share:", np.round(vals / vals.sum(), 4))print("reconstructed corr matches:", np.allclose(vecs @ np.diag(vals) @ vecs.T, corr))print("Cholesky L @ L.T matches:", np.allclose(L @ L.T, corr))eigenvalues: [2.7378 0.9908 0.1678 0.1035]variance share: [0.6844 0.2477 0.042 0.0259]reconstructed corr matches: TrueCholesky L @ L.T matches: TrueSingular Value Decomposition (SVD)
Section titled “Singular Value Decomposition (SVD)”Every matrix (square or rectangular, full-rank or singular) factors into:
- Columns of (left singular vectors) are orthonormal eigenvectors of ; columns of (right singular vectors) are orthonormal eigenvectors of ; .
- Eckart–Young Theorem: Keeping only the top terms gives the closest rank- matrix in Frobenius and spectral norm, with error .
- Ridge regression via SVD: For , the Ridge solution shrinks each singular direction by :
sales["month"] = sales["order_date"].str.slice(0, 7)mat = ( sales.pivot_table( index="store_id", columns="month", values="revenue", aggfunc="sum" ) .fillna(0.0) .to_numpy())U, s, Vt = np.linalg.svd(mat, full_matrices=False)energy = np.cumsum(s**2) / np.sum(s**2)rank2 = (U[:, :2] * s[:2]) @ Vt[:2, :]rel_err = np.linalg.norm(mat - rank2, "fro") / np.linalg.norm(mat, "fro")
print("matrix shape:", mat.shape)print("top 4 singular values:", np.round(s[:4], 1))print("cumulative energy (k=1..3):", np.round(energy[:3], 4))print("rank-2 relative Frobenius error:", round(float(rel_err), 4))matrix shape: (12, 24)top 4 singular values: [235247.3 25609.5 21027.7 18594.6]cumulative energy (k=1..3): [0.954 0.9653 0.9729]rank-2 relative Frobenius error: 0.1863NumPy and SciPy linalg reference
Section titled “NumPy and SciPy linalg reference”| Function | Input requirement | Returns | When to use |
|---|---|---|---|
np.linalg.solve(A, b) |
square, nonsingular | exact linear system; never inv(A) @ b |
|
np.linalg.lstsq(X, y, rcond=None) |
any | x, residuals, rank, s |
least squares, over/underdetermined |
np.linalg.qr(X, mode="reduced") |
any | Q, R |
orthonormal basis, stable regression |
np.linalg.eigh(S) |
symmetric / Hermitian | ascending vals, vecs |
covariance, correlation, graph Laplacian |
np.linalg.eig(A) |
any square | vals, vecs (may be complex) |
Markov chains, non-symmetric operators |
np.linalg.svd(A, full_matrices=False) |
any | U, s, Vt |
PCA, low-rank approximation, diagnostics |
np.linalg.cholesky(S) |
symmetric positive definite | lower triangular L |
SPD check, fast SPD solve (cho_solve), MVN sampling |
np.linalg.pinv(A) |
any | minimum-norm least-squares inverse | |
scipy.linalg.solve_triangular(R, b) |
triangular R |
back-substitution after QR or Cholesky | |
scipy.sparse.linalg.svds(A, k) |
large sparse matrix | top- singular triplets | TF-IDF / user-item matrices (LSA) |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
using A * B for matrix multiplication |
silent elementwise product or broadcast error | use A @ B |
solving with np.linalg.inv(A) @ b |
slower and loses numerical accuracy | use np.linalg.solve(A, b) |
solving OLS via (X.T @ X) on unscaled features |
squares condition number ; wild weights | standardize and use np.linalg.lstsq or QR |
forgetting svd returns Vt (), not V |
transposed loadings when projecting X @ V |
project with X @ Vt.T (or U * s) |
calling np.linalg.eig on a symmetric covariance matrix |
tiny imaginary parts (+0j) and unsorted eigenvalues |
use np.linalg.eigh (real, sorted, faster) |
reading eigh eigenvalues assuming descending order |
first column is the smallest variance direction | reverse with vals[::-1], vecs[:, ::-1] |
checking det(A) == 0 to test singularity |
underflows to 0.0 on well-conditioned large matrices |
use np.linalg.matrix_rank(A) or np.linalg.cond(A) |
computing U @ np.diag(s) @ Vt on large matrices |
wastes memory building a dense diagonal matrix | broadcast (U * s) @ Vt |
| forgetting to center columns before SVD for PCA | first singular vector points toward the mean, not max variance | subtract column means: Xc = X - X.mean(axis=0) |
Learn more
Section titled “Learn more”- Module 23: NumPy
- Module 32: math for ML
- Module 46: linear algebra in depth
- Master cheat sheet: NumPy and calculus and optimization