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 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.
What you will learn
Section titled “What you will learn”- 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.
Prerequisites
Section titled “Prerequisites”- NumPy arrays, broadcasting,
@,solve, andlstsq: 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, anddata/reviews.csv, documented in the data dictionary.
Concepts
Section titled “Concepts”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 pltimport numpy as npimport pandas as pdfrom scipy.sparse.linalg import svdsfrom sklearn.decomposition import PCA, TruncatedSVDfrom 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 that maps every vector to a new vector while preserving vector addition and scalar multiplication:
Geometrically, every linear transformation keeps the origin fixed and keeps straight parallel grid lines straight and evenly spaced. The columns of tell you everything: column 1 is where the horizontal unit vector lands, and column 2 is where lands.
Four 2-D matrices illustrate the building blocks of all matrix transformations:
| Transformation | Matrix | What it does to the unit circle |
|---|---|---|
| Scaling | Stretches by 1.8 and shrinks by 0.7 | |
| Rotation by | Turns every point counterclockwise without changing lengths | |
| Shear | Slants horizontal layers proportionally to | |
| Projection onto -axis | 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()
When a model applies a linear layer 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 has columns . Four closely linked definitions describe what those columns can express:
- The span of is the set of all linear combinations .
- 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 —every prediction vector a linear model can possibly produce.
- Vectors have linear independence when no column can be written as a linear combination of the others: only when .
- 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 is the dimension of its column space—the number of linearly independent columns. The null space (or kernel) of is the set of all nonzero (plus zero) vectors satisfying . By the rank–nullity theorem:
Whenever a feature is an exact linear combination of others (such as including sqft and sqm = 0.0929 * sqft in the same regression), and the null space contains nonzero directions along which weights can slide infinitely without changing .
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)))independent shape and rank: (200, 2) 2dependent shape and rank: (200, 3) 2max |X_dep @ null_vec|: 0.0X_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 leaves every prediction unchanged.
Orthogonality, orthonormal bases and Gram–Schmidt
Section titled “Orthogonality, orthonormal bases and Gram–Schmidt”Two vectors and are orthogonal vectors when their dot product is zero (): geometrically, they meet at a angle. An orthonormal basis is a basis of mutually orthogonal unit vectors ( if else ). Stacking them as columns of gives . When is square (), it is an orthogonal matrix, meaning and multiplying by preserves every vector length and angle ().
Why do numerical algorithms love orthonormal columns? Computing coordinates in an orthonormal basis needs no matrix inversion—just a dot product: .
The Gram–Schmidt process turns any linearly independent columns into an orthonormal basis 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)max |Q.T @ Q - I|: 2.60e-16max |Q @ R - A|: 3.32e-17R: [[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 () 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 and a subspace , what point is closest to in Euclidean distance? The orthogonal projection of onto : the unique point such that the residual vector is perpendicular to every column of .
- Onto a single nonzero vector : .
- Onto a subspace with orthonormal basis : .
- Onto directly: requiring yields the normal equations and the projection matrix .
Every orthogonal projection matrix satisfies two algebraic signatures: it is symmetric () and idempotent (, because projecting a point that is already in the subspace does not move it). And because , the Pythagorean theorem holds in -dimensional space:
y_vec = np.array([2.0, 3.0, 1.0, 4.0])P = Q_mgs @ Q_mgs.Ty_hat = P @ y_vecresid = 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) ** 2rhs = np.linalg.norm(y_hat) ** 2 + np.linalg.norm(resid) ** 2print("Pythagoras ||y||^2 vs ||y_hat||^2 + ||r||^2:", round(lhs, 4), round(rhs, 4))max |P @ P - P|: 2.22e-16max |A.T @ r|: 1.55e-15Pythagoras ||y||^2 vs ||y_hat||^2 + ||r||^2: 30.0 30.0Ordinary least squares is not a trick from calculus alone—it is geometry. Minimizing simply drops a perpendicular from onto the flat subspace spanned by the feature columns.
QR factorization and why lstsq stays stable when fails
Section titled “QR factorization and why lstsq stays stable when X⊤XX^\top XX⊤X fails”Writing (called QR factorization, where has orthonormal columns and is upper triangular) simplifies the normal equations dramatically:
Because is upper triangular, solving takes fast back-substitution, and you never form . Why does avoiding matter so much?
The condition number measures how much tiny input perturbations or floating-point rounding errors get amplified when solving a linear system. Forming squares the condition number: . In 64-bit floats (about 16 digits of precision), if , then and normal equations lose every single digit of accuracy, while QR and SVD (np.linalg.lstsq) still retain roughly 8 accurate digits.
eps = 1e-8X_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)cond(X): 1.41e+08cond(X.T @ X): infQR weights: [1. 1.]lstsq weights: [1. 1.]normal eqs failed: Singular matrixOn this classic Läuchli test matrix, rounds to 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 matrix , the determinant is a single scalar measuring the signed volume scaling factor of the transformation :
- is the factor by which multiplies area (in 2-D) or volume (in -D).
- A negative determinant means flips orientation (a reflection).
- means squashes space into a lower dimension (zero volume): is singular (not invertible) and has rank less than .
- Product rule: , and for any orthogonal matrix, .
In statistics, the multivariate Gaussian probability density divides by to normalize for the volume of the covariance ellipse. In high dimensions, easily overflows or underflows float64, so numerical code uses np.linalg.slogdet(A) to compute the sign and directly.
for name, mat in transforms: print(f"{name:24s} det = {np.linalg.det(mat):6.3f}")
cov_high = np.eye(50) * 0.1sign, 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))Scaling det = 1.260Rotation (35 deg) det = 1.000Shear det = 1.000Projection onto x-axis det = 0.000direct det(0.1 * I_50): 9.999999999999234e-51slogdet sign & logdet: 1.0 -115.1293Scaling by 1.8 and 0.7 scales area by . Rotation preserves area (), shear preserves area (), and projection collapses area to 0 (). For , the true determinant is tiny, while slogdet stays clean at .
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 . An eigenvector is a special direction that stays on its own line— only stretches, shrinks, or flips it by a scalar eigenvalue :
Two useful identities connect eigenvalues to cheap matrix summaries:
- The trace (sum of diagonal entries) equals the sum of eigenvalues: .
- The determinant equals the product of eigenvalues: .
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))eigenvalues: [1.382 3.618]trace vs sum: 5.0 5.0det vs prod: 5.0 5.0check A @ v0 == lam0 * v0: Truecheck A @ v1 == lam1 * v1: TrueNotice 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 , covariance matrices , correlation matrices, and Hessians of smooth loss functions. Symmetric matrices () obey the spectral theorem:
- Every eigenvalue of is guaranteed to be real.
- Eigenvectors can always be chosen to form an orthonormal basis ().
- factors cleanly as , where .
A symmetric matrix is a positive definite matrix if the quadratic form for every nonzero vector —equivalently, if every eigenvalue is strictly positive (). It is positive semi-definite if .
For a centered data matrix , the sample covariance matrix satisfies:
That means is literally the variance of the data when projected onto unit direction ! 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 directionorder = 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),)covariance matrix: [[1.0003 0.8458] [0.8458 1.0003]]eigenvalues (descending): [1.8461 0.1546]positive definite? Trueeigenvectors orthogonal? Truevariance along PC1 vs lambda_1: 1.8461 1.8461Because 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 —rectangular, wide, tall, or rank-deficient:
With reduced SVD (full_matrices=False, ):
- has orthonormal columns (left singular vectors, spanning row/output space).
- holds the singular values sorted descending ().
- 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 (), stretch along perpendicular axes (), and rotate into output space (). Algebraically, SVD is tightly linked to eigen-decomposition: the right singular vectors are the eigenvectors of , and the squared singular values are the eigenvalues of —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))shapes U, s, Vt: (3000, 2) (2,) (2, 2)reconstruct max err: 5.66e-15s^2 / (n-1) vs eigh: [1.8461 0.1546] [1.8461 0.1546]matches eigh? TrueLook at that agreement: matches the covariance eigenvalues vals to full precision, and Vt.T matches the covariance eigenvectors (up to a sign flip, because if is an eigenvector, 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 rank-1 outer products, ordered from largest signal to smallest:
Keeping only the top terms creates a low-rank approximation . How good is it? Measure matrix error with the Frobenius norm . The Eckart–Young theorem proves that is the optimal rank- approximation to —no other rank- matrix can achieve a smaller Frobenius (or spectral) error—and its exact error is the tail of discarded singular values:
SVD also generalizes the inverse to any rectangular or rank-deficient matrix via the Moore–Penrose pseudoinverse:
where replaces each nonzero singular value with and leaves tiny/zero singular values as 0. Solving 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)))singular values: [8.5399 1.0342 0. ]matches np.linalg.pinv? TrueWorked examples
Section titled “Worked examples”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})")correlation sqft-bathrooms: 0.8458PC1 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 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 transforms the unit circle into the 1-standard-deviation ellipse of the covariance matrix, because .
L = vecs @ np.diag(np.sqrt(vals))ell_1 = L @ circleell_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()
Notice how the ellipse wraps the tilted point cloud tightly: the linear transformation literally turns isotropic (circular) unit data into correlated data with covariance .
Common mistakes:
- Scaling the unit circle by instead of : eigenvalues of are variances, so the semi-axis lengths are standard deviations .
- Treating rows of
vecsas 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 ")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 , .
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}")base age VIF = 1.00base tenure_months VIF = 7.96base monthly_charges VIF = 2.34base total_charges VIF = 9.30collinear age VIF = 1.00collinear tenure_months VIF = 8.08collinear monthly_charges VIF = 2.37collinear total_charges VIF = 682.47collinear est_total VIF = 693.01Even 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.condon unstandardized columns: mixingage(range 18–80) andtotal_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 and solve .
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}")QR weights: [12.9195 0.3501 -0.024 0.0515 0.143 -0.1932 0.0789]max |w_qr - w_ls|: 1.42e-14QR 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 and . Check that and that , which is the geometric origin of !
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}")max |A.T @ resid|: 3.58e-11mean(resid): 1.19e-14SST = 825.0468, SSE + SSR = 825.0468, R^2 = 0.7211Because column 0 of A_h is all ones, A_h[:, 0] @ resid_h == 0 forces the residuals to have zero mean. And because lies in the column space while is orthogonal to it, 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 , but
resid.mean()is no longer guaranteed to be 0 and breaks. - Calling
np.linalg.qr(A, mode="complete")on a 3,000-row matrix: that allocates a dense . The defaultmode="reduced"returns the compact 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 matrixcorr_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 PCAsk_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_))explained variance (eigh): [0.4098 0.2432 0.1382 0.1065 0.064 0.0237 0.0148]matches SVD? Truematches PCA? TrueStep 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 (), 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 1cos_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))min |cos(eigh, sklearn)|: 1.000000 PC1 PC2sqft 0.539 -0.180bedrooms 0.545 -0.199bathrooms 0.544 -0.202year_built 0.215 0.576garage_spaces 0.153 0.260condition 0.136 0.455distance_to_center_km 0.170 0.529The 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: bothvand-vrepresent the same principal axis. - Running PCA on raw unstandardized features:
sqfthas variance ~500,000 whileconditionhas variance ~0.9, so PC1 would simply copysqft.
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 stores-by-months revenue matrix from data/sales.csv with SVD, verify the Eckart–Young Frobenius error formula at every rank , 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))matrix shape: (12, 24) rank: 12top 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 , reconstruct , compare to , 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}" )k=1: frob_err= 51668.0 (theory 51668.0), energy=95.40%, stored=37/288k=2: frob_err= 44874.7 (theory 44874.7), energy=96.53%, stored=74/288k=3: frob_err= 39643.1 (theory 39643.1), energy=97.29%, stored=111/288k=4: frob_err= 35011.6 (theory 35011.6), energy=97.89%, stored=148/288k=6: frob_err= 25792.2 (theory 25792.2), energy=98.85%, stored=222/288Look 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 * 100ranks = 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()
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 diagonal matrix. - Forgetting that
sis squared when computing variance or Frobenius energy (, not ).
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 . Because is sparse (mostly zeros), dense np.linalg.svd would waste memory and time; sparse svds computes only the top 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]) * 100print(f"TF-IDF shape: {T_tfidf.shape}, non-zeros: {T_tfidf.nnz} ({density:.2f}% dense)")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 = 5U_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))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? TrueStep 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])}")axis 1 (sigma=12.89): price, quality, great, material, recommend, feelsaxis 2 (sigma=8.33): battery, sturdy, charge, built, holds, fastaxis 3 (sigma=8.16): sturdy, built, friends, definitely, recommend, sizeaxis 4 (sigma=7.94): price, point, beat, lower, stores, hardaxis 5 (sigma=7.93): feels, material, premium, quality, solid, cheapWithout 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.svdsreturns 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.
TruncatedSVDintentionally works on the uncentered sparse matrix.
Pitfalls
Section titled “Pitfalls”| 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] |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Computer graphics and 3-D game engines: Every camera movement, object rotation, scaling, and shadow projection is a chain of 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.
Summary
Section titled “Summary”- A matrix 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 , preserve lengths and angles, and turn coordinates and projections into simple matrix products ().
- Ordinary least squares is the orthogonal projection of onto , making residuals perpendicular to every feature column ().
- QR factorization solves least squares via without forming , avoiding the 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 .
- SVD () works on any matrix, powers numerically stable PCA, gives the optimal low-rank approximation (Eckart–Young), and defines the Moore–Penrose pseudoinverse .
Self-check questions
Section titled “Self-check questions”Q1. A matrix 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 ?
Answer
By the rank–nullity theorem, . Two columns are redundant linear combinations of the others, so infinitely many weight vectors produce the exact same predictions . 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 leave its Euclidean length unchanged?
Answer
Because , we have . 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 really is the orthogonal projection of onto ?
Answer
Check np.allclose(X.T @ (y - X @ w), 0). If the residual vector is orthogonal to every column of , its dot product with each column is zero (up to floating-point tolerance).
Q4. Suppose a design matrix has condition number . What is the approximate condition number of , and which solver should you prefer?
Answer
. Prefer QR factorization or SVD (np.linalg.lstsq), which work directly on with condition number instead of squaring it to .
Q5. A transformation matrix has determinant . What does that tell you geometrically about how it transforms shapes?
Answer
It scales every 2-D area by a factor of 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 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 is symmetric positive definite).
Q8. How are the singular values of a centered data matrix (with rows) related to the eigenvalues of its sample covariance matrix ?
Answer
The eigenvalues of are , where are the singular values of . Both methods yield the same principal directions and explained variance ratios, but SVD avoids forming .
Q9. A matrix has singular values [10, 4, 2, 1]. Without building the reconstructed matrix, what is the exact Frobenius norm error 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: .
Q10. When np.linalg.svd(A, full_matrices=False) returns U, s, Vt, how do you compute the Moore–Penrose pseudoinverse , 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.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- 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.