Skip to content

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 np
import pandas as pd
from scipy import linalg
houses = pd.read_csv("data/houses.csv")
customers = pd.read_csv("data/customers.csv")
sales = pd.read_csv("data/sales.csv")
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 L1L_1, L2L_2, L∞L_\infty norms np.linalg.norm(v, ord=1 / 2 / np.inf) default is L2L_2
matrix Frobenius or spectral norm np.linalg.norm(A, "fro") / ord=2 spectral norm =σmax⁡(A)= \sigma_{\max}(A)
solve a square linear system Ax=bAx = b np.linalg.solve(A, b) faster and cleaner than inv(A) @ b
solve least squares min⁡∥Xw−y∥22\min \Vert Xw - y \Vert_2^2 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) κ>104\kappa > 10^4 signals ill-conditioning
orthonormal basis for column space Q, R = np.linalg.qr(X, mode="reduced") Q⊤Q=IQ^\top Q = I; 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 λi>0\lambda_i > 0
full or reduced SVD A=UΣV⊤A = U \Sigma V^\top U, s, Vt = np.linalg.svd(A, full_matrices=False) Vt is already transposed (V⊤V^\top)
Moore–Penrose pseudoinverse A+A^+ np.linalg.pinv(A) replaces nonzero σi\sigma_i with 1/σi1/\sigma_i
best rank-kk matrix approximation (U[:, :k] * s[:k]) @ Vt[:k, :] Eckart–Young optimal in Frobenius & spectral norm
Operation Math Shapes NumPy
inner (dot) product u⊤v=∑iuiviu^\top v = \sum_i u_i v_i (n,),(n,)→scalar(n,), (n,) \to \text{scalar} u @ v or np.dot(u, v)
outer product uv⊤u v^\top (m,),(n,)→(m,n)(m,), (n,) \to (m, n) np.outer(u, v)
matrix multiply (AB)ij=∑kAikBkj(AB)_{ij} = \sum_k A_{ik} B_{kj} (m,k)×(k,n)→(m,n)(m, k) \times (k, n) \to (m, n) A @ B
Hadamard (elementwise) (A⊙B)ij=AijBij(A \odot B)_{ij} = A_{ij} B_{ij} (m,n)×(m,n)→(m,n)(m, n) \times (m, n) \to (m, n) A * B
transpose (A⊤)ij=Aji(A^\top)_{ij} = A_{ji} (m,n)→(n,m)(m, n) \to (n, m) A.T
trace tr(A)=∑iAii=∑iλi\mathrm{tr}(A) = \sum_i A_{ii} = \sum_i \lambda_i (n,n)→scalar(n, n) \to \text{scalar} np.trace(A)
determinant det⁡(A)=∏iλi\det(A) = \prod_i \lambda_i (volume scale) (n,n)→scalar(n, n) \to \text{scalar} np.linalg.det(A)
vector LpL_p norm ∥v∥p=(∑i∣vi∣p)1/p\Vert v \Vert_p = (\sum_i \vert v_i \vert^p)^{1/p} (n,)→R≥0(n,) \to \mathbb{R}_{\ge 0} np.linalg.norm(v, ord=p)
Frobenius norm ∥A∥F=∑i,jAij2=∑iσi2\Vert A \Vert_F = \sqrt{\sum_{i,j} A_{ij}^2} = \sqrt{\sum_i \sigma_i^2} (m,n)→R≥0(m, n) \to \mathbb{R}_{\ge 0} np.linalg.norm(A, "fro")
spectral norm ∥A∥2=max⁡∥x∥2=1∥Ax∥2=σmax⁡\Vert A \Vert_2 = \max_{\Vert x \Vert_2 = 1} \Vert Ax \Vert_2 = \sigma_{\max} (m,n)→R≥0(m, n) \to \mathbb{R}_{\ge 0} np.linalg.norm(A, ord=2)

Key algebraic identities: (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top, (AB)−1=B−1A−1(AB)^{-1} = B^{-1} A^{-1}, tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA), det⁡(AB)=det⁡(A)det⁡(B)\det(AB) = \det(A)\det(B), and det⁡(A⊤)=det⁡(A)\det(A^\top) = \det(A).

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))
Output
L1, L2, Linf: [7.0, 5.0, 4.0]
cosine similarity: -0.3333

Rank, span, conditioning and linear systems

Section titled “Rank, span, conditioning and linear systems”

For an m×nm \times n matrix AA:

  • Rank r=rank(A)≤min⁡(m,n)r = \mathrm{rank}(A) \le \min(m, n) is the number of linearly independent columns (and rows), equal to the number of nonzero singular values.
  • Rank–Nullity Theorem: rank(A)+dim⁡(ker⁡A)=n\mathrm{rank}(A) + \dim(\ker A) = n.
  • Condition number: κ2(A)=σmax⁡(A)/σmin⁡(A)≥1\kappa_2(A) = \sigma_{\max}(A) / \sigma_{\min}(A) \ge 1. Each order of magnitude in κ\kappa can cost roughly one decimal digit of accuracy when solving Ax=bAx = b. Notice that forming normal equations X⊤XX^\top X squares the condition number: κ(X⊤X)=κ(X)2\kappa(X^\top X) = \kappa(X)^2.
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 drop
rank_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)))
Output
raw cond vs standardized cond: 181.8 5.93
rank of 3 features: 3
rank with exact combo: 3

A vector bb projected onto the column space of a full-rank matrix XX is y^=Xw^=Pb\hat{y} = X \hat{w} = P b where the orthogonal projection matrix is P=X(X⊤X)−1X⊤P = X (X^\top X)^{-1} X^\top. Its defining property is that the residual r=b−y^r = b - \hat{y} is perpendicular to every column of XX:

X⊤(y−Xw^)=0  ⟹  X⊤Xw^=X⊤yX^\top (y - X\hat{w}) = 0 \implies X^\top X \hat{w} = X^\top y

Factoring X=QRX = Q R (with Q⊤Q=IQ^\top Q = I and RR upper triangular) avoids squaring the condition number: Rw^=Q⊤yR \hat{w} = Q^\top y is solved directly by back-substitution, and P=QQ⊤P = Q Q^\top.

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 equations
Q, 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}")
Output
QR weights: [12.9195 0.3468 -0.0195 0.0508 0.1079]
max diff QR vs lstsq: 1.24e-14
max diff QR vs normal eq: 1.24e-14
max |X.T @ resid|: 3.51e-11

Eigenvalues, symmetric matrices and positive definiteness

Section titled “Eigenvalues, symmetric matrices and positive definiteness”

An eigenvector v≠0v \ne 0 satisfies Av=λvA v = \lambda v: the transformation AA only stretches vv by λ\lambda.

  • Spectral Theorem: Every real symmetric matrix S=S⊤S = S^\top has real eigenvalues and an orthonormal eigenbasis: S=QΛQ⊤S = Q \Lambda Q^\top with Q⊤Q=IQ^\top Q = I.
  • Positive definiteness (SPD): SS is positive definite (S≻0S \succ 0) iff x⊤Sx>0x^\top S x > 0 for all x≠0x \ne 0, iff all λi>0\lambda_i > 0, iff a unique Cholesky factor S=LL⊤S = L L^\top exists. Covariance and correlation matrices are always positive semi-definite (λi≥0\lambda_i \ge 0).
Z = (feat - feat.mean(0)) / feat.std(0)
corr = (Z.T @ Z) / len(Z) # 4x4 feature correlation matrix
vals, vecs = np.linalg.eigh(corr) # ascending order for symmetric matrices
vals, 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))
Output
eigenvalues: [2.7378 0.9908 0.1678 0.1035]
variance share: [0.6844 0.2477 0.042 0.0259]
reconstructed corr matches: True
Cholesky L @ L.T matches: True

Every m×nm \times n matrix AA (square or rectangular, full-rank or singular) factors into:

A=UΣV⊤=∑i=1rσiuivi⊤,σ1≥σ2≥⋯≥σr>0A = U \Sigma V^\top = \sum_{i=1}^{r} \sigma_i u_i v_i^\top, \qquad \sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_r > 0
  • Columns of UU (left singular vectors) are orthonormal eigenvectors of AA⊤A A^\top; columns of VV (right singular vectors) are orthonormal eigenvectors of A⊤AA^\top A; σi=λi(A⊤A)\sigma_i = \sqrt{\lambda_i(A^\top A)}.
  • Eckart–Young Theorem: Keeping only the top kk terms Ak=UkΣkVk⊤A_k = U_k \Sigma_k V_k^\top gives the closest rank-kk matrix in Frobenius and spectral norm, with error ∥A−Ak∥F=∑i>kσi2\Vert A - A_k \Vert_F = \sqrt{\sum_{i > k} \sigma_i^2}.
  • Ridge regression via SVD: For X=UΣV⊤X = U \Sigma V^\top, the Ridge solution (X⊤X+λI)−1X⊤y(X^\top X + \lambda I)^{-1} X^\top y shrinks each singular direction by σiσi2+λ\frac{\sigma_i}{\sigma_i^2 + \lambda}:
w^ridge=Vdiag⁡ ⁣(σiσi2+λ)U⊤y\hat{w}_{\text{ridge}} = V \operatorname{diag}\!\left(\frac{\sigma_i}{\sigma_i^2 + \lambda}\right) U^\top y
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))
Output
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.1863
Function Input requirement Returns When to use
np.linalg.solve(A, b) square, nonsingular xx exact linear system; never inv(A) @ b
np.linalg.lstsq(X, y, rcond=None) any (m,n)(m, n) x, residuals, rank, s least squares, over/underdetermined
np.linalg.qr(X, mode="reduced") any (m,n)(m, n) 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 (m,n)(m, n) 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 (m,n)(m, n) A+A^+ minimum-norm least-squares inverse
scipy.linalg.solve_triangular(R, b) triangular R xx back-substitution after QR or Cholesky
scipy.sparse.linalg.svds(A, k) large sparse matrix top-kk singular triplets TF-IDF / user-item matrices (LSA)
Trap Symptom Fix
using A * B for matrix multiplication silent elementwise product or broadcast error use A @ B
solving Ax=bAx = b 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 κ(X)2\kappa(X)^2; wild weights standardize and use np.linalg.lstsq or QR
forgetting svd returns Vt (V⊤V^\top), 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)