46. Linear algebra in depth — Exercises
These 25 exercises practice every idea in 46. Linear algebra in depth. They use the course datasets data/houses.csv, data/customers.csv, data/sales.csv, and data/reviews.csv (see the data dictionary).
How to work:
- Copy the setup block and the starter code into a script (for example
exercise.py). - Replace each to-do comment with your implementation and run it from the folder containing
data/. - Open one hint at a time when stuck. Compare with the solution only after testing your own attempt.
Every exercise runs after these lines in a fresh namespace.
import numpy as npimport pandas as pd
np.set_printoptions(precision=4, suppress=True)Warm-up
Section titled “Warm-up”M46-W01 · Apply 2D rotation and scaling
Section titled “M46-W01 · Apply 2D rotation and scaling”Build a 2-D scaling matrix that stretches by 2.0 and shrinks by 0.5, and a rotation matrix that rotates counterclockwise by 60 degrees. Apply first and then (composite matrix ) to the point . Print the transformed point and the determinant of .
transformed point: [1.2679 6.1962]det(R @ S): 1.0p = np.array([3.0, 4.0])# TODO: build S (scale x by 2.0, y by 0.5) and R (rotate 60 degrees counterclockwise)# TODO: compute M = R @ S, transform p, and print the result and det(M)Hint 1
Convert 60 degrees to radians with np.deg2rad(60). The rotation matrix is [[cos(t), -sin(t)], [sin(t), cos(t)]].
Hint 2
Applying first and second means . The determinant of equals .
Solution
p = np.array([3.0, 4.0])S = np.array([[2.0, 0.0], [0.0, 0.5]])theta = np.deg2rad(60)R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])M = R @ Sp_out = M @ pdet_m = float(np.linalg.det(M))print("transformed point:", np.round(p_out, 4))print("det(R @ S): ", round(det_m, 4))assert np.allclose(p_out, R @ (S @ p))assert np.isclose(det_m, 1.0)transformed point: [1.2679 6.1962]det(R @ S): 1.0How it works:
- Scaling sends
(3, 4)to(6, 2). - Rotating
(6, 2)counterclockwise by producesR @ S @ p. - Because and , the composite area factor is
1.0.
M46-W02 · Predict the output: rank, trace and determinant
Section titled “M46-W02 · Predict the output: rank, trace and determinant”Predict the output: work out each printed line on paper before running the code. Notice that row 2 of B is twice row 1.
A = np.array([[4.0, 0.0], [0.0, -2.0]])B = np.array([[1.0, 3.0], [2.0, 6.0]])print("A rank:", np.linalg.matrix_rank(A))print("A trace:", np.trace(A))print("A det:", round(float(np.linalg.det(A)), 4))print("B rank:", np.linalg.matrix_rank(B))print("B det:", round(float(np.linalg.det(B)), 4))Acceptance criteria:
- Write your five predictions line by line before running the code.
- Your predictions match the Output in the solution, and you can explain why
det(A)is negative whiledet(B)is zero.
Hint 1
For a diagonal matrix, the trace is the sum of the diagonal entries and the determinant is their product.
Hint 2
When one row of a matrix is a scalar multiple of the other, the matrix squashes 2-D space onto a 1-D line, so its rank is 1 and its area scaling factor is 0.
Solution
A = np.array([[4.0, 0.0], [0.0, -2.0]])B = np.array([[1.0, 3.0], [2.0, 6.0]])print("A rank:", np.linalg.matrix_rank(A))print("A trace:", np.trace(A))print("A det:", round(float(np.linalg.det(A)), 4))print("B rank:", np.linalg.matrix_rank(B))print("B det:", round(float(np.linalg.det(B)), 4))assert np.linalg.matrix_rank(A) == 2assert np.linalg.matrix_rank(B) == 1assert np.isclose(np.linalg.det(B), 0.0)A rank: 2A trace: 2.0A det: -8.0B rank: 1B det: 0.0How it works:
Ais diagonal with nonzero entries 4 and -2, so its rank is 2, its trace is4 + (-2) = 2.0, and its determinant is4 * (-2) = -8.0(the minus sign reflects the -axis).Bhas linearly dependent rows (row 2 = 2 * row 1), so its rank drops to 1 and its determinant collapses to0.0.
M46-W03 · Diagnose rank and null-space dimension
Section titled “M46-W03 · Diagnose rank and null-space dimension”Load data/houses.csv and take the first 100 rows of sqft, bedrooms, and bathrooms. Add a fourth column total_rooms = bedrooms + bathrooms and a fifth column sqft_x2 = 2 * sqft. Print the shape, matrix rank, and null-space dimension of the 5-column matrix.
shape: (100, 5) rank: 3 null_dim: 2houses = pd.read_csv("data/houses.csv").iloc[:100]# TODO: build the 5-column matrix [sqft, bedrooms, bathrooms, total_rooms, sqft_x2]# TODO: compute rank and null-space dimension and print themHint 1
Use np.column_stack([...]) to assemble the 5 float columns.
Hint 2
By the rank–nullity theorem, null_dim = X.shape[1] - np.linalg.matrix_rank(X).
Solution
houses = pd.read_csv("data/houses.csv").iloc[:100]sqft = houses["sqft"].to_numpy(dtype=float)beds = houses["bedrooms"].to_numpy(dtype=float)baths = houses["bathrooms"].to_numpy(dtype=float)X = np.column_stack([sqft, beds, baths, beds + baths, 2.0 * sqft])
rank = int(np.linalg.matrix_rank(X))null_dim = X.shape[1] - rankprint("shape:", X.shape, "rank:", rank, "null_dim:", null_dim)assert X.shape == (100, 5)assert rank == 3 and null_dim == 2shape: (100, 5) rank: 3 null_dim: 2How it works:
- The first three columns are linearly independent, giving a 3-D column space.
- Both
total_roomsandsqft_x2lie inside the span of the first three columns, so rank stays 3 and the null space has dimension5 - 3 = 2.
M46-W04 · Project a vector onto a line
Section titled “M46-W04 · Project a vector onto a line”Project the vector onto the direction . Print the scalar coefficient , the projection , the residual , and verify that .
c: 2.0y_hat: [2. 4. 4.]resid: [ 2. -2. 1.]orthogonal: Truey = np.array([4.0, 2.0, 5.0])a = np.array([1.0, 2.0, 2.0])# TODO: compute c = (a @ y) / (a @ a), y_hat, resid, and print themHint 1
The projection formula onto a single vector is .
Hint 2
Check orthogonality with np.isclose(a @ resid, 0.0).
Solution
y = np.array([4.0, 2.0, 5.0])a = np.array([1.0, 2.0, 2.0])c = float((a @ y) / (a @ a))y_hat = c * aresid = y - y_hatprint("c:", round(c, 4))print("y_hat:", y_hat)print("resid:", resid)print("orthogonal:", bool(np.isclose(a @ resid, 0.0)))assert np.isclose(a @ resid, 0.0)assert np.isclose( np.linalg.norm(y) ** 2, np.linalg.norm(y_hat) ** 2 + np.linalg.norm(resid) ** 2,)c: 2.0y_hat: [2. 4. 4.]resid: [ 2. -2. 1.]orthogonal: TrueHow it works:
- and , so .
- The residual has dot product with .
M46-W05 · Verify an orthogonal matrix preserves lengths and angles
Section titled “M46-W05 · Verify an orthogonal matrix preserves lengths and angles”Construct the 3-D Householder reflection matrix using . Check that , and verify on and that and .
Q.T @ Q == I: Truelength preserved: True 5.099dot preserved: True -21.0det(Q): -1.0v = np.array([1.0, -2.0, 2.0])x = np.array([3.0, 1.0, -4.0])y = np.array([-1.0, 2.0, 5.0])# TODO: build Householder matrix Q = I - 2 * outer(v, v) / (v @ v)# TODO: verify orthogonality, length preservation, and dot-product preservationHint 1
Use np.outer(v, v) to form .
Hint 2
Compare np.linalg.norm(Q @ x) to np.linalg.norm(x) and (Q @ x) @ (Q @ y) to x @ y.
Solution
v = np.array([1.0, -2.0, 2.0])x = np.array([3.0, 1.0, -4.0])y = np.array([-1.0, 2.0, 5.0])Q = np.eye(3) - 2.0 * np.outer(v, v) / (v @ v)
orth_ok = np.allclose(Q.T @ Q, np.eye(3))len_ok = np.isclose(np.linalg.norm(Q @ x), np.linalg.norm(x))dot_ok = np.isclose((Q @ x) @ (Q @ y), x @ y)print("Q.T @ Q == I:", orth_ok)print("length preserved:", len_ok, round(float(np.linalg.norm(Q @ x)), 4))print("dot preserved: ", dot_ok, round(float((Q @ x) @ (Q @ y)), 4))print("det(Q): ", round(float(np.linalg.det(Q)), 4))assert orth_ok and len_ok and dot_okassert np.isclose(np.linalg.det(Q), -1.0)Q.T @ Q == I: Truelength preserved: True 5.099dot preserved: True -21.0det(Q): -1.0How it works:
- Householder reflections are the building blocks of
np.linalg.qrinside LAPACK. - Every Householder matrix is symmetric and orthogonal with determinant
-1.0(a reflection across the plane perpendicular to ).
M46-W06 · Symmetric eigendecomposition with eigh
Section titled “M46-W06 · Symmetric eigendecomposition with eigh”Compute the eigenvalues and eigenvectors of the symmetric matrix using np.linalg.eigh. Sort them in descending eigenvalue order, print the eigenvalues, and verify .
eigenvalues (desc): [6. 1.]spectral reconstruction ok: TrueS = np.array([[5.0, 2.0], [2.0, 2.0]])# TODO: call np.linalg.eigh(S), sort descending, verify Q @ diag(vals) @ Q.T == SHint 1
Sort indices descending with idx = np.argsort(vals)[::-1], then slice vals = vals[idx] and vecs = vecs[:, idx].
Hint 2
Reconstruct with vecs @ np.diag(vals) @ vecs.T and check with np.allclose.
Solution
S = np.array([[5.0, 2.0], [2.0, 2.0]])vals, vecs = np.linalg.eigh(S)idx = np.argsort(vals)[::-1]vals, vecs = vals[idx], vecs[:, idx]recon_ok = np.allclose(vecs @ np.diag(vals) @ vecs.T, S)print("eigenvalues (desc):", vals)print("spectral reconstruction ok:", recon_ok)assert np.allclose(vals, [6.0, 1.0])assert recon_okeigenvalues (desc): [6. 1.]spectral reconstruction ok: TrueHow it works:
- The characteristic equation gives exact eigenvalues
6and1. - Reordering columns of
vecsalongsidevalspreserves .
M46-W07 · Check positive definiteness of a covariance matrix
Section titled “M46-W07 · Check positive definiteness of a covariance matrix”Load data/houses.csv, standardize sqft, bedrooms, bathrooms, and condition, and compute the sample covariance matrix . Check whether is positive definite using np.linalg.eigvalsh, and verify that np.linalg.cholesky(Sigma) succeeds and reproduces .
min eigenvalue: 0.1036positive definite: TrueCholesky L @ L.T == Sigma: Truehouses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition"]# TODO: standardize cols, compute covariance matrix Sigma# TODO: check eigvalsh > 0 and verify cholesky L @ L.T == SigmaHint 1
Use np.cov(Z, rowvar=False) after standardizing Z = (X - X.mean(axis=0)) / X.std(axis=0).
Hint 2
L = np.linalg.cholesky(Sigma) succeeds if and only if Sigma is symmetric positive definite.
Solution
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition"]X = houses[cols].to_numpy(dtype=float)Z = (X - X.mean(axis=0)) / X.std(axis=0)Sigma = np.cov(Z, rowvar=False)
eigs = np.linalg.eigvalsh(Sigma)L = np.linalg.cholesky(Sigma)chol_ok = np.allclose(L @ L.T, Sigma)print("min eigenvalue:", round(float(eigs.min()), 4))print("positive definite:", bool(np.all(eigs > 0)))print("Cholesky L @ L.T == Sigma:", chol_ok)assert np.all(eigs > 0) and chol_okmin eigenvalue: 0.1036positive definite: TrueCholesky L @ L.T == Sigma: TrueHow it works:
- Every eigenvalue of
Sigmais strictly positive (the smallest is positive because no column is an exact linear combination of the others). - Cholesky factorization confirms positive definiteness directly.
M46-W08 · Reconstruct a matrix from reduced SVD
Section titled “M46-W08 · Reconstruct a matrix from reduced SVD”Compute the reduced SVD (full_matrices=False) of the matrix A = np.arange(1.0, 13.0).reshape(4, 3). Print the shapes of U, s, and Vt, the singular values, and verify that (U * s) @ Vt matches A to 1e-12.
shapes: (4, 3) (3,) (3, 3)singular values: [25.4624 1.2907 0. ]exact match: TrueA = np.arange(1.0, 13.0).reshape(4, 3)# TODO: compute reduced SVD, print shapes and singular values, verify reconstructionHint 1
U, s, Vt = np.linalg.svd(A, full_matrices=False). Notice s is returned as a 1-D vector.
Hint 2
(U * s) @ Vt multiplies each column of U by its singular value via broadcasting before multiplying by Vt.
Solution
A = np.arange(1.0, 13.0).reshape(4, 3)U, s, Vt = np.linalg.svd(A, full_matrices=False)recon = (U * s) @ Vtmax_err = float(np.max(np.abs(A - recon)))print("shapes:", U.shape, s.shape, Vt.shape)print("singular values:", np.round(s, 4))print("exact match:", max_err < 1e-12)assert U.shape == (4, 3) and s.shape == (3,) and Vt.shape == (3, 3)assert max_err < 1e-12shapes: (4, 3) (3,) (3, 3)singular values: [25.4624 1.2907 0. ]exact match: TrueHow it works:
- Because rows of
Aincrease by a constant step[3, 3, 3],Ahas rank 2, which is why the third singular value is0.0. - Broadcasting
U * sscales each column ofUcleanly without allocatingnp.diag(s).
M46-C01 · Implement modified Gram–Schmidt
Section titled “M46-C01 · Implement modified Gram–Schmidt”Write a function mgs_qr(A) implementing modified Gram–Schmidt for a tall full-rank matrix A of shape (m, p). Test it on a seeded random (20, 4) matrix (np.random.default_rng(42).normal(size=(20, 4))). Print the maximum absolute errors of Q.T @ Q - I and Q @ R - A, and verify that R is upper triangular.
orthonormality ok: Truereconstruction ok: TrueR upper triangular: TrueR diagonal: [3.6099 3.2261 3.6546 2.8494]def mgs_qr(A: np.ndarray) -> tuple[np.ndarray, np.ndarray]: # TODO: return orthonormal Q (m, p) and upper-triangular R (p, p) raise NotImplementedError
rng = np.random.default_rng(42)A = rng.normal(size=(20, 4))# TODO: call mgs_qr(A) and verify orthonormality, reconstruction, and upper triangularityHint 1
For each column j, copy v = A[:, j].astype(float).copy(), then for i in range(j) compute R[i, j] = Q[:, i] @ v and update v = v - R[i, j] * Q[:, i].
Hint 2
After the inner loop, R[j, j] = np.linalg.norm(v) and Q[:, j] = v / R[j, j]. Check upper triangularity with np.allclose(np.tril(R, k=-1), 0).
Solution
def mgs_qr(A: np.ndarray) -> tuple[np.ndarray, np.ndarray]: 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
rng = np.random.default_rng(42)A = rng.normal(size=(20, 4))Q, R = mgs_qr(A)orth_err = float(np.max(np.abs(Q.T @ Q - np.eye(4))))recon_err = float(np.max(np.abs(Q @ R - A)))upper_ok = bool(np.allclose(np.tril(R, k=-1), 0.0))print("orthonormality ok:", orth_err < 1e-13)print("reconstruction ok:", recon_err < 1e-13)print("R upper triangular:", upper_ok)print("R diagonal:", np.round(np.diag(R), 4))assert orth_err < 1e-13 and recon_err < 1e-13 and upper_okorthonormality ok: Truereconstruction ok: TrueR upper triangular: TrueR diagonal: [3.6099 3.2261 3.6546 2.8494]How it works:
- Updating
vafter each single projection (modified Gram–Schmidt) keepsQorthonormal to near machine precision. - Each diagonal entry
R[j, j]is the length of columnj’s component perpendicular to all previous columns.
M46-C02 · Solve OLS via QR factorization on house prices
Section titled “M46-C02 · Solve OLS via QR factorization on house prices”Load data/houses.csv. Standardize sqft, bathrooms, condition, and distance_to_center_km, prepend a column of ones to form design matrix A, and set y = np.log(price). Solve OLS using np.linalg.qr and np.linalg.solve(R, Q.T @ y). Print the weights, verify agreement with np.linalg.lstsq, and verify that A.T @ (y - A @ w) is zero to 1e-9.
weights: [12.9195 0.3589 0.0377 0.1439 -0.1935]matches lstsq: Trueresiduals orthogonal to A: Truehouses = pd.read_csv("data/houses.csv")cols = ["sqft", "bathrooms", "condition", "distance_to_center_km"]# TODO: standardize cols, add ones column, compute log price# TODO: solve via QR, compare with lstsq, check residual orthogonalityHint 1
Q, R = np.linalg.qr(A) followed by w_qr = np.linalg.solve(R, Q.T @ y).
Hint 2
Compute residuals r = y - A @ w_qr and check np.allclose(A.T @ r, 0, atol=1e-9).
Solution
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bathrooms", "condition", "distance_to_center_km"]X = houses[cols].to_numpy(dtype=float)Z = (X - X.mean(axis=0)) / X.std(axis=0)A = np.column_stack([np.ones(len(houses)), Z])y = np.log(houses["price"].to_numpy(dtype=float))
Q, R = np.linalg.qr(A)w_qr = np.linalg.solve(R, Q.T @ y)w_ls = np.linalg.lstsq(A, y)[0]resid = y - A @ w_qr
print("weights:", np.round(w_qr, 4))print("matches lstsq:", bool(np.allclose(w_qr, w_ls, atol=1e-12)))print("residuals orthogonal to A:", bool(np.allclose(A.T @ resid, 0.0, atol=1e-9)))assert np.allclose(w_qr, w_ls, atol=1e-12)assert np.allclose(A.T @ resid, 0.0, atol=1e-9)weights: [12.9195 0.3589 0.0377 0.1439 -0.1935]matches lstsq: Trueresiduals orthogonal to A: TrueHow it works:
- Substituting into the normal equations cancels and leaves .
- Because
w_qrminimizes , the residual is perpendicular to every column ofA, including the constant column of ones.
M46-C03 · Fix the bug: eig vs. eigh and eigenvector indexing
Section titled “M46-C03 · Fix the bug: eig vs. eigh and eigenvector indexing”Fix the bug: the snippet below tries to compute the top principal component direction and variance of a symmetric correlation matrix R, but it has two classic NumPy linear-algebra bugs: it uses eig without sorting descending, and it slices a row of vecs instead of a column. Fix both bugs using np.linalg.eigh, print the largest eigenvalue and its eigenvector (oriented so its first entry is positive), and verify R @ pc1 == lam1 * pc1.
lam1: 2.0369pc1: [0.626 0.6495 0.4317]eigenvector equation ok: TrueR = np.array([[1.0, 0.8, 0.3], [0.8, 1.0, 0.4], [0.3, 0.4, 1.0]])# BUGGY CODE:# vals, vecs = np.linalg.eig(R)# lam1, pc1 = vals[0], vecs[0]# TODO: fix using np.linalg.eigh, sort descending, take column 0, orient pc1[0] > 0Hint 1
np.linalg.eigh(R) returns eigenvalues in ascending order, so the largest eigenvalue is at index -1 (or index 0 after reversing with [::-1]).
Hint 2
Eigenvectors are columns: vecs[:, -1]. Flip its sign if pc1[0] < 0.
Solution
R = np.array([[1.0, 0.8, 0.3], [0.8, 1.0, 0.4], [0.3, 0.4, 1.0]])vals, vecs = np.linalg.eigh(R)idx = np.argsort(vals)[::-1]vals, vecs = vals[idx], vecs[:, idx]
lam1 = float(vals[0])pc1 = vecs[:, 0].copy()if pc1[0] < 0: pc1 = -pc1
print("lam1:", round(lam1, 4))print("pc1: ", np.round(pc1, 4))print("eigenvector equation ok:", bool(np.allclose(R @ pc1, lam1 * pc1)))assert np.allclose(R @ pc1, lam1 * pc1)assert np.isclose(np.linalg.norm(pc1), 1.0)assert lam1 == vals.max()lam1: 2.0369pc1: [0.626 0.6495 0.4317]eigenvector equation ok: TrueHow it works:
eighguarantees real eigenvalues and orthonormal columns; reversing the sort puts the largest eigenvalue at index 0.- Taking
vecs[:, 0]selects the first eigenvector column rather than mixing entries from three different eigenvectors.
M46-C04 · Audit customer billing collinearity with singular values
Section titled “M46-C04 · Audit customer billing collinearity with singular values”Interpret a result: load data/customers.csv, drop rows where total_charges is missing, and standardize age, tenure_months, monthly_charges, and total_charges. Compute the singular values, condition number, and the right singular vector corresponding to the smallest singular value (oriented so the total_charges loading is positive). Print them and verify which features drive the near-linear dependence.
condition number: 5.929smallest singular value: 16.614 age : +0.0024 tenure_months : -0.6475 monthly_charges : -0.2842 total_charges : +0.7071customers = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"])cols = ["age", "tenure_months", "monthly_charges", "total_charges"]# TODO: standardize cols, compute SVD, print condition number and smallest right singular vectorHint 1
_, s, Vt = np.linalg.svd(Z, full_matrices=False). The smallest singular value is s[-1] and its right singular vector is Vt[-1].
Hint 2
A right singular vector with tiny satisfies , so its large-magnitude entries reveal the exact combination of features causing collinearity.
Solution
customers = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"])cols = ["age", "tenure_months", "monthly_charges", "total_charges"]X = customers[cols].to_numpy(dtype=float)Z = (X - X.mean(axis=0)) / X.std(axis=0)
_, s, Vt = np.linalg.svd(Z, full_matrices=False)v_min = Vt[-1].copy()if v_min[-1] < 0: v_min = -v_min
print("condition number:", round(float(s[0] / s[-1]), 3))print("smallest singular value:", round(float(s[-1]), 3))for name, coef in zip(cols, v_min, strict=True): print(f" {name:16s}: {coef:+.4f}")assert abs(v_min[0]) < 0.05 # age is independent of billing collinearityassert abs(v_min[-1]) > 0.7 # total_charges dominates the null-like directioncondition number: 5.929smallest singular value: 16.614 age : +0.0024 tenure_months : -0.6475 monthly_charges : -0.2842 total_charges : +0.7071How it works:
- The last right singular vector gives the approximate linear relation
0.71 * total_charges - 0.65 * tenure_months - 0.28 * monthly_charges ≈ 0. - Notice
agehas weight nearly0.00: it does not participate in the billing collinearity at all.
M46-C05 · Build and verify an orthogonal projection matrix
Section titled “M46-C05 · Build and verify an orthogonal projection matrix”Given the tall matrix X below and vector y, compute an orthonormal basis Q for via np.linalg.qr, form the projection matrix , and verify four properties: symmetry (), idempotence (), rank equal to , and the Pythagorean identity .
symmetric: True idempotent: Truetrace(P) == rank(X): 2.0 2Pythagoras holds: True ||r||: 1.2247X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0]])y = np.array([1.0, 2.5, 2.0, 4.5, 5.0])# TODO: build Q via qr, form P = Q @ Q.T, verify symmetry, idempotence, trace, PythagorasHint 1
Q, _ = np.linalg.qr(X) gives a (5, 2) matrix, so P = Q @ Q.T is (5, 5).
Hint 2
The eigenvalues of any orthogonal projection matrix are only 1 (repeated times) and 0, so its trace equals its rank.
Solution
X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0]])y = np.array([1.0, 2.5, 2.0, 4.5, 5.0])Q, _ = np.linalg.qr(X)P = Q @ Q.T
y_hat = P @ yr = y - y_hatsym_ok = np.allclose(P, P.T)idem_ok = np.allclose(P @ P, P)trace_p = round(float(np.trace(P)), 4)pyth_ok = np.isclose( np.linalg.norm(y) ** 2, np.linalg.norm(y_hat) ** 2 + np.linalg.norm(r) ** 2,)
print("symmetric:", sym_ok, "idempotent:", idem_ok)print("trace(P) == rank(X):", trace_p, np.linalg.matrix_rank(X))print("Pythagoras holds:", pyth_ok, "||r||:", round(float(np.linalg.norm(r)), 4))assert sym_ok and idem_ok and pyth_ok and np.isclose(np.trace(P), 2.0)symmetric: True idempotent: Truetrace(P) == rank(X): 2.0 2Pythagoras holds: True ||r||: 1.2247How it works:
- : projecting twice does nothing after the first projection.
- In real ML code you rarely form the matrix explicitly; instead you compute
Q @ (Q.T @ y)in instead of .
M46-C06 · Determinant as area scaling and stable slogdet
Section titled “M46-C06 · Determinant as area scaling and stable slogdet”Part A: transform the unit square vertices [(0, 0), (1, 0), (1, 1), (0, 1)] with A = np.array([[2.0, 1.0], [0.5, 3.0]]). Compute the area of the resulting parallelogram using the 2-D cross product of the two column vectors of A (|a1_x * a2_y - a1_y * a2_x|) and show it equals abs(det(A)).
Part B: for C = 0.05 * np.eye(300), show that np.linalg.det(C) underflows to 0.0, while np.linalg.slogdet(C) recovers the exact log-determinant .
parallelogram area vs |det(A)|: 5.5 5.5det(0.05 * I_300) underflows: 0.0slogdet vs 300*ln(0.05): -898.7197 -898.7197A = np.array([[2.0, 1.0], [0.5, 3.0]])C = 0.05 * np.eye(300)# TODO: compare parallelogram area to abs(det(A)), and det(C) to slogdet(C)Hint 1
The two edges of the transformed unit square are c1 = A[:, 0] and c2 = A[:, 1]. Their parallelogram area is abs(c1[0] * c2[1] - c1[1] * c2[0]).
Hint 2
Compare logdet from np.linalg.slogdet(C) against 300 * np.log(0.05).
Solution
A = np.array([[2.0, 1.0], [0.5, 3.0]])c1, c2 = A[:, 0], A[:, 1]area = abs(float(c1[0] * c2[1] - c1[1] * c2[0]))det_a = abs(float(np.linalg.det(A)))
C = 0.05 * np.eye(300)det_c = float(np.linalg.det(C))sign, logdet_c = np.linalg.slogdet(C)exact_logdet = float(300 * np.log(0.05))
print("parallelogram area vs |det(A)|:", round(area, 4), round(det_a, 4))print("det(0.05 * I_300) underflows: ", det_c)print( "slogdet vs 300*ln(0.05): ", round(float(logdet_c), 4), round(exact_logdet, 4),)assert np.isclose(area, det_a)assert det_c == 0.0assert sign == 1.0 and np.isclose(logdet_c, exact_logdet)parallelogram area vs |det(A)|: 5.5 5.5det(0.05 * I_300) underflows: 0.0slogdet vs 300*ln(0.05): -898.7197 -898.7197How it works:
- is smaller than the smallest float64 number (), so
detsilently returns0.0even thoughCis invertible with condition number1.0. slogdetworks in log space and matches cleanly.
M46-C07 · Compress category monthly sales and check Eckart–Young
Section titled “M46-C07 · Compress category monthly sales and check Eckart–Young”Load data/sales.csv and build the matrix of monthly revenue by category (rows = category, columns = YYYY-MM). Compute its reduced SVD. For ranks , print the actual Frobenius reconstruction error , the Eckart–Young tail , and the percentage of total Frobenius energy retained.
k=1: err= 61900.8, EY= 61900.8, energy=98.14%k=2: err= 30588.4, EY= 30588.4, energy=99.55%k=3: err= 11438.3, EY= 11438.3, energy=99.94%sales = pd.read_csv("data/sales.csv")# TODO: pivot category x YYYY-MM sum of revenue, compute SVD# TODO: check actual Frobenius error vs Eckart-Young formula for k = 1, 2, 3Hint 1
Create month = sales["order_date"].str.slice(0, 7) and pivot with index="category", columns="month", values="revenue", aggfunc="sum".
Hint 2
Rank- reconstruction is (U[:, :k] * s[:k]) @ Vt[:k, :]. Total energy is np.sum(s**2).
Solution
sales = pd.read_csv("data/sales.csv")sales_m = sales.assign(month=sales["order_date"].str.slice(0, 7))mat = sales_m.pivot_table( index="category", columns="month", values="revenue", aggfunc="sum", fill_value=0.0).to_numpy(dtype=float)
U, s, Vt = np.linalg.svd(mat, full_matrices=False)total_energy = float(np.sum(s**2))for k in (1, 2, 3): mk = (U[:, :k] * s[:k]) @ Vt[:k, :] err_actual = float(np.linalg.norm(mat - mk, ord="fro")) err_ey = float(np.sqrt(np.sum(s[k:] ** 2))) pct = float(np.sum(s[:k] ** 2)) / total_energy * 100 print(f"k={k}: err={err_actual:8.1f}, EY={err_ey:8.1f}, energy={pct:5.2f}%") assert np.isclose(err_actual, err_ey, atol=1e-7)k=1: err= 61900.8, EY= 61900.8, energy=98.14%k=2: err= 30588.4, EY= 30588.4, energy=99.55%k=3: err= 11438.3, EY= 11438.3, energy=99.94%How it works:
- Rank 1 captures over 98% of the category-by-month revenue energy because Electronics dominates every month with a shared November–December spike.
- Rank 2 picks up seasonal contrast such as Sports peaking in summer rather than winter.
M46-C08 · Build the Moore–Penrose pseudoinverse from SVD
Section titled “M46-C08 · Build the Moore–Penrose pseudoinverse from SVD”Write my_pinv(A) using np.linalg.svd(A, full_matrices=False) with tolerance max(A.shape) * np.finfo(float).eps * s[0]. Test it on the rank-deficient matrix A below, verify it matches np.linalg.pinv(A), and check that w = my_pinv(A) @ y gives the minimum-norm least-squares solution (matches np.linalg.lstsq(A, y)[0]).
matches np.linalg.pinv: Truew_pinv: [ 1.1212 -0.2424 0.8788]matches lstsq: Truedef my_pinv(A: np.ndarray) -> np.ndarray: # TODO: compute V @ Sigma^+ @ U.T using reduced SVD and numerical tolerance raise NotImplementedError
A = np.array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.0, 1.0, 1.0], [1.0, 1.0, 2.0]])y = np.array([3.0, 6.0, 2.0, 4.0])# TODO: test my_pinv against np.linalg.pinv and np.linalg.lstsqHint 1
Set s_inv = np.where(s > tol, 1.0 / s, 0.0) and return (Vt.T * s_inv) @ U.T.
Hint 2
Check both np.allclose(P, np.linalg.pinv(A)) and np.allclose(P @ y, np.linalg.lstsq(A, y)[0]).
Solution
def my_pinv(A: np.ndarray) -> np.ndarray: U, s, Vt = np.linalg.svd(A, full_matrices=False) tol = max(A.shape) * np.finfo(float).eps * s[0] s_inv = np.where(s > tol, 1.0 / s, 0.0) return (Vt.T * s_inv) @ U.T
A = np.array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.0, 1.0, 1.0], [1.0, 1.0, 2.0]])y = np.array([3.0, 6.0, 2.0, 4.0])A_pinv = my_pinv(A)w_pinv = A_pinv @ yw_ls = np.linalg.lstsq(A, y)[0]
print("matches np.linalg.pinv:", bool(np.allclose(A_pinv, np.linalg.pinv(A))))print("w_pinv:", np.round(w_pinv, 4))print("matches lstsq:", bool(np.allclose(w_pinv, w_ls)))assert np.allclose(A_pinv, np.linalg.pinv(A))assert np.allclose(w_pinv, w_ls)matches np.linalg.pinv: Truew_pinv: [ 1.1212 -0.2424 0.8788]matches lstsq: TrueHow it works:
- Because column 3 equals column 1 plus column 2,
Ahas rank 2 and its third singular value is zero. - Zeroing
1 / s[2]projects the solution onto the row space ofA, guaranteeing the unique least-squares vector of smallest L2 norm.
M46-C09 · Predict the output: singular values vs. eigenvalues of
Section titled “M46-C09 · Predict the output: singular values vs. eigenvalues of X⊤XX^\top XX⊤X”Predict the output: without running the code first, predict all four lines printed below for the matrix X.
X = np.array([[3.0, 0.0], [0.0, 4.0], [0.0, 0.0]])s = np.linalg.svd(X, compute_uv=False)eigs = np.linalg.eigvalsh(X.T @ X)[::-1]print("singular values of X:", s)print("eigenvalues of X.T @ X:", eigs)print("s**2 == eigs:", np.allclose(s**2, eigs))print("Frobenius norm of X:", round(float(np.linalg.norm(X, ord="fro")), 4))Acceptance criteria:
- Write your four predictions line by line before running the code.
- Your predictions match the Output in the solution, and you can explain why the singular values are sorted
[4.0, 3.0]rather than[3.0, 4.0].
Hint 1
, whose eigenvalues are 16 and 9.
Hint 2
np.linalg.svd always sorts singular values descending, and the Frobenius norm is .
Solution
X = np.array([[3.0, 0.0], [0.0, 4.0], [0.0, 0.0]])s = np.linalg.svd(X, compute_uv=False)eigs = np.linalg.eigvalsh(X.T @ X)[::-1]print("singular values of X:", s)print("eigenvalues of X.T @ X:", eigs)print("s**2 == eigs:", np.allclose(s**2, eigs))print("Frobenius norm of X:", round(float(np.linalg.norm(X, ord="fro")), 4))assert np.allclose(s, [4.0, 3.0])assert np.allclose(s**2, eigs)assert np.isclose(np.linalg.norm(X, ord="fro"), 5.0)singular values of X: [4. 3.]eigenvalues of X.T @ X: [16. 9.]s**2 == eigs: TrueFrobenius norm of X: 5.0How it works:
- Singular values of are the square roots of the eigenvalues of , always returned in descending order (
[4., 3.]). - The Frobenius norm equals .
M46-C10 · Implement PCA from scratch via SVD
Section titled “M46-C10 · Implement PCA from scratch via SVD”Write pca_svd(X, n_components) that centers X, computes its reduced SVD, and returns (Z_proj, components, explained_ratio) where Z_proj has shape (n, n_components). Test it on the standardized columns sqft, bedrooms, bathrooms, year_built, and distance_to_center_km from data/houses.csv with n_components=3, and verify that explained_ratio and the projected columns (up to sign) match sklearn.decomposition.PCA(n_components=3).
explained ratios: [0.5591 0.2831 0.1036]ratios match sklearn: Truescores match up to sign: Truefrom sklearn.decomposition import PCA
def pca_svd(X: np.ndarray, n_components: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: # TODO: center X, compute reduced SVD, return projected scores, components, explained ratios raise NotImplementedError
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "year_built", "distance_to_center_km"]# TODO: standardize cols, run pca_svd(Z, 3), verify against sklearn PCAHint 1
After centering Xc = X - X.mean(axis=0) and running U, s, Vt = np.linalg.svd(Xc, full_matrices=False), the projected scores are U[:, :k] * s[:k] (equivalently Xc @ Vt[:k].T).
Hint 2
To compare projected columns up to sign, check np.allclose(np.abs(Z_proj), np.abs(sk_proj), atol=1e-10).
Solution
from sklearn.decomposition import PCA
def pca_svd( X: np.ndarray, n_components: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: Xc = X - X.mean(axis=0) U, s, Vt = np.linalg.svd(Xc, full_matrices=False) Z_proj = U[:, :n_components] * s[:n_components] components = Vt[:n_components] explained_ratio = (s[:n_components] ** 2) / np.sum(s**2) return Z_proj, components, explained_ratio
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "year_built", "distance_to_center_km"]X = houses[cols].to_numpy(dtype=float)Z = (X - X.mean(axis=0)) / X.std(axis=0)
scores, comps, ratios = pca_svd(Z, 3)sk = PCA(n_components=3)sk_scores = sk.fit_transform(Z)
print("explained ratios:", np.round(ratios, 4))print("ratios match sklearn:", bool(np.allclose(ratios, sk.explained_variance_ratio_)))print("scores match up to sign:", bool(np.allclose(np.abs(scores), np.abs(sk_scores))))assert np.allclose(ratios, sk.explained_variance_ratio_, atol=1e-10)assert np.allclose(np.abs(scores), np.abs(sk_scores), atol=1e-10)explained ratios: [0.5591 0.2831 0.1036]ratios match sklearn: Truescores match up to sign: TrueHow it works:
U[:, :k] * s[:k]equalsXc @ Vt[:k].Tdirectly from and .- Notice
sklearn.decomposition.PCAuses SVD internally for the exact same stability reason.
M46-C11 · Solve Ridge regression via SVD shrinkage
Section titled “M46-C11 · Solve Ridge regression via SVD shrinkage”Write ridge_svd(X, y, lam) that centers X and y (so the intercept is unpenalized) and computes Ridge weights via and intercept . Test it on data/houses.csv (features sqft, bedrooms, bathrooms, condition, target log(price)) with lam = 50.0 and verify exact agreement with both the closed-form normal equation and sklearn.linear_model.Ridge(alpha=50.0).
w_svd: [ 0.3257 -0.0048 0.0548 0.106 ] b: 12.9195matches normal eq: Truematches sklearn: Truefrom sklearn.linear_model import Ridge
def ridge_svd(X: np.ndarray, y: np.ndarray, lam: float) -> tuple[np.ndarray, float]: # TODO: center X and y, compute reduced SVD, apply sigma / (sigma^2 + lam) shrinkage raise NotImplementedError
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition"]# TODO: standardize cols, solve for lam = 50.0, verify against closed form and sklearn RidgeHint 1
With U, s, Vt = np.linalg.svd(Xc, full_matrices=False), compute w = Vt.T @ ((s / (s**2 + lam)) * (U.T @ yc)).
Hint 2
For the closed-form check on centered Xc and yc, solve (Xc.T @ Xc + lam * np.eye(p)) w = Xc.T @ yc.
Solution
from sklearn.linear_model import Ridge
def ridge_svd(X: np.ndarray, y: np.ndarray, lam: float) -> tuple[np.ndarray, float]: x_mean = X.mean(axis=0) y_mean = float(y.mean()) Xc = X - x_mean yc = y - y_mean U, s, Vt = np.linalg.svd(Xc, full_matrices=False) w = Vt.T @ ((s / (s**2 + lam)) * (U.T @ yc)) b = y_mean - float(x_mean @ w) return w, b
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition"]X_raw = houses[cols].to_numpy(dtype=float)Z = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)y = np.log(houses["price"].to_numpy(dtype=float))
lam = 50.0w_svd, b_svd = ridge_svd(Z, y, lam)w_eq = np.linalg.solve(Z.T @ Z + lam * np.eye(Z.shape[1]), Z.T @ (y - y.mean()))sk = Ridge(alpha=lam).fit(Z, y)
print("w_svd:", np.round(w_svd, 4), "b:", round(b_svd, 4))print("matches normal eq:", bool(np.allclose(w_svd, w_eq, atol=1e-10)))print("matches sklearn: ", bool(np.allclose(w_svd, sk.coef_, atol=1e-10)))assert np.allclose(w_svd, w_eq, atol=1e-10)assert np.allclose(w_svd, sk.coef_, atol=1e-10)assert np.isclose(b_svd, sk.intercept_, atol=1e-10)w_svd: [ 0.3257 -0.0048 0.0548 0.106 ] b: 12.9195matches normal eq: Truematches sklearn: TrueHow it works:
- Substituting into turns the inverse into a diagonal scaling .
- Small singular values () get damped strongly toward zero, which is why Ridge stabilizes collinear features.
M46-C12 · Choose a solver for an ill-conditioned Vandermonde matrix
Section titled “M46-C12 · Choose a solver for an ill-conditioned Vandermonde matrix”Choose a method and justify it: build a degree-11 polynomial Vandermonde matrix V = np.vander(t, N=12, increasing=True) on t = np.linspace(0.0, 1.0, 50) and a noise-free target y = V @ w_true where w_true = np.ones(12). Print cond(V) and cond(V.T @ V), then solve with both normal equations (np.linalg.solve(V.T @ V, V.T @ y)) and QR (np.linalg.qr). Print the max absolute weight error of each solver and assert that QR is at least 1,000 times more accurate.
cond(V): 1.17e+08cond(V.T @ V): 1.17e+08^2 -> 1.35e+16normal eq max error: 1.13e-01QR max error: 6.58e-09QR >1000x more accurate: Truet = np.linspace(0.0, 1.0, 50)V = np.vander(t, N=12, increasing=True)w_true = np.ones(12)y = V @ w_true# TODO: print cond(V), cond(V.T @ V), and max weight error for normal eqs vs QRHint 1
Compute err_norm = np.max(np.abs(w_norm - w_true)) and err_qr = np.max(np.abs(w_qr - w_true)).
Hint 2
cond(V) is around , so cond(V.T @ V) reaches , destroying float64 precision in normal equations.
Solution
t = np.linspace(0.0, 1.0, 50)V = np.vander(t, N=12, increasing=True)w_true = np.ones(12)y = V @ w_true
cond_v = float(np.linalg.cond(V))cond_vtv = float(np.linalg.cond(V.T @ V))
w_norm = np.linalg.solve(V.T @ V, V.T @ y)Q, R = np.linalg.qr(V)w_qr = np.linalg.solve(R, Q.T @ y)
err_norm = float(np.max(np.abs(w_norm - w_true)))err_qr = float(np.max(np.abs(w_qr - w_true)))print(f"cond(V): {cond_v:.2e}")print(f"cond(V.T @ V): {cond_v:.2e}^2 -> {cond_vtv:.2e}")print(f"normal eq max error: {err_norm:.2e}")print(f"QR max error: {err_qr:.2e}")print("QR >1000x more accurate:", err_norm > 1000 * err_qr)assert err_norm > 1000 * err_qrcond(V): 1.17e+08cond(V.T @ V): 1.17e+08^2 -> 1.35e+16normal eq max error: 1.13e-01QR max error: 6.58e-09QR >1000x more accurate: TrueHow it works:
- Powers on look nearly identical in shape, pushing above and past .
- Because QR never squares the condition number, it stays accurate by many orders of magnitude—always choose QR or SVD (
lstsq) over normal equations on polynomial or correlated features.
Challenge
Section titled “Challenge”M46-X01 · Power iteration with deflation for top two eigenvectors
Section titled “M46-X01 · Power iteration with deflation for top two eigenvectors”Implement power_iteration(S, n_iter=200) that finds the dominant eigenvalue and unit eigenvector of a symmetric positive definite matrix S by repeatedly multiplying and evaluating the Rayleigh quotient . Then apply Hotelling deflation () and run power iteration a second time to recover . Test on the correlation matrix of sqft, bedrooms, bathrooms, year_built, condition, and distance_to_center_km from data/houses.csv, and assert both eigenvalues and eigenvectors match np.linalg.eigh to 1e-6.
lam1: 2.824493 (eigh: 2.824493), |cos|=1.000000lam2: 1.646573 (eigh: 1.646573), |cos|=1.000000v1 orthogonal to v2: Truedef power_iteration(S: np.ndarray, n_iter: int = 200) -> tuple[float, np.ndarray]: # TODO: start from seeded unit vector, iterate v = S @ v / norm(S @ v) raise NotImplementedError
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km"]# TODO: build correlation matrix, find top 2 eigenpairs with deflation, verify against eighHint 1
Initialize with v = np.random.default_rng(42).normal(size=S.shape[0]) and v /= np.linalg.norm(v). After looping n_iter times, compute lam = float(v @ S @ v).
Hint 2
Deflation S2 = S - lam1 * np.outer(v1, v1) zeroes out the component while leaving every other eigenvalue and orthogonal eigenvector untouched.
Solution
def power_iteration(S: np.ndarray, n_iter: int = 200) -> tuple[float, np.ndarray]: v = np.random.default_rng(42).normal(size=S.shape[0]) v = v / np.linalg.norm(v) for _ in range(n_iter): w = S @ v v = w / np.linalg.norm(w) lam = float(v @ S @ v) return lam, v
houses = pd.read_csv("data/houses.csv")cols = [ "sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km",]R = np.corrcoef(houses[cols].to_numpy(dtype=float), rowvar=False)
lam1, v1 = power_iteration(R, n_iter=200)R_deflated = R - lam1 * np.outer(v1, v1)lam2, v2 = power_iteration(R_deflated, n_iter=200)
vals, vecs = np.linalg.eigh(R)idx = np.argsort(vals)[::-1]vals, vecs = vals[idx], vecs[:, idx]
cos1 = abs(float(v1 @ vecs[:, 0]))cos2 = abs(float(v2 @ vecs[:, 1]))print(f"lam1: {lam1:.6f} (eigh: {vals[0]:.6f}), |cos|={cos1:.6f}")print(f"lam2: {lam2:.6f} (eigh: {vals[1]:.6f}), |cos|={cos2:.6f}")print("v1 orthogonal to v2:", bool(np.isclose(v1 @ v2, 0.0, atol=1e-6)))assert np.isclose(lam1, vals[0], atol=1e-6) and np.isclose(lam2, vals[1], atol=1e-6)assert cos1 > 1 - 1e-6 and cos2 > 1 - 1e-6lam1: 2.824493 (eigh: 2.824493), |cos|=1.000000lam2: 1.646573 (eigh: 1.646573), |cos|=1.000000v1 orthogonal to v2: TrueHow it works:
- Repeated multiplication by amplifies the component along by relative to , converging rapidly whenever .
- Subtracting turns the largest eigenvalue into
0, making the new dominant eigenvalue.
M46-X02 · Compute Variance Inflation Factors using QR factorization
Section titled “M46-X02 · Compute Variance Inflation Factors using QR factorization”Write vif_qr(Z) for a standardized (zero-mean, unit-std) matrix Z that computes each column’s Variance Inflation Factor using only np.linalg.qr (no inv or solve). Test it on data/customers.csv (drop NaN total_charges) for age, tenure_months, monthly_charges, total_charges, and est_total = monthly_charges * tenure_months, and assert it matches np.diag(np.linalg.inv(np.corrcoef(Z, rowvar=False))) to 1e-4.
age VIF = 1.00tenure_months VIF = 8.08monthly_charges VIF = 2.37total_charges VIF = 682.47est_total VIF = 693.01matches inv(R) diagonal: Truedef vif_qr(Z: np.ndarray) -> np.ndarray: # TODO: for each column j, project z_j onto col(Z_{-j}) using QR and compute 1/(1 - R^2) raise NotImplementedError
customers = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"]).copy()customers["est_total"] = customers["monthly_charges"] * customers["tenure_months"]cols = ["age", "tenure_months", "monthly_charges", "total_charges", "est_total"]# TODO: standardize cols, compute vif_qr(Z), and compare to correlation-matrix inverseHint 1
Drop column j with others = np.delete(Z, j, axis=1). Because Z is already zero-mean, no intercept column is needed when regressing z_j on others.
Hint 2
Compute Q, _ = np.linalg.qr(others), z_hat = Q @ (Q.T @ z_j), and r2 = 1.0 - np.sum((z_j - z_hat) ** 2) / np.sum(z_j**2).
Solution
def vif_qr(Z: np.ndarray) -> np.ndarray: p = Z.shape[1] vifs = np.empty(p, dtype=float) for j in range(p): others = np.delete(Z, j, axis=1) Q, _ = np.linalg.qr(others) z_j = Z[:, j] z_hat = Q @ (Q.T @ z_j) r2 = 1.0 - float(np.sum((z_j - z_hat) ** 2)) / float(np.sum(z_j**2)) vifs[j] = 1.0 / (1.0 - r2) return vifs
customers = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"]).copy()customers["est_total"] = customers["monthly_charges"] * customers["tenure_months"]cols = ["age", "tenure_months", "monthly_charges", "total_charges", "est_total"]X = customers[cols].to_numpy(dtype=float)Z = (X - X.mean(axis=0)) / X.std(axis=0)
vifs = vif_qr(Z)vifs_inv = np.diag(np.linalg.inv(np.corrcoef(Z, rowvar=False)))for name, v in zip(cols, vifs, strict=True): print(f"{name:16s} VIF = {v:7.2f}")print("matches inv(R) diagonal:", bool(np.allclose(vifs, vifs_inv, rtol=1e-4)))assert np.allclose(vifs, vifs_inv, rtol=1e-4)age VIF = 1.00tenure_months VIF = 8.08monthly_charges VIF = 2.37total_charges VIF = 682.47est_total VIF = 693.01matches inv(R) diagonal: TrueHow it works:
- Regressing standardized column on the remaining columns via QR gives directly as the squared projection ratio without ever squaring the condition number in .
- Even when two columns are nearly duplicates (
total_chargesandest_total), QR stays stable.
M46-X03 · Implement PCA and ZCA whitening transforms
Section titled “M46-X03 · Implement PCA and ZCA whitening transforms”Whitening transforms correlated zero-mean features into uncorrelated features with unit covariance (). Using reduced SVD on sqft, bedrooms, bathrooms, and condition from data/houses.csv:
- PCA whitening:
- ZCA whitening: (rotates back to the original feature axes!)
Verify both produce sample covariance equal to , and compute the mean diagonal correlation to show that ZCA stays much closer to the original feature meanings than PCA whitening.
cov(Z_pca) == I: True cov(Z_zca) == I: Truemean |diag corr| with original (PCA): 0.2887mean diag corr with original (ZCA): 0.8454houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition"]# TODO: standardize cols into Z, compute U, s, Vt = svd(Z, full_matrices=False)# TODO: build Z_pca and Z_zca, verify cov == I, compare mean diagonal correlation with ZHint 1
n = len(Z). Then Z_pca = np.sqrt(n - 1) * U and Z_zca = Z_pca @ Vt.
Hint 2
For each column j, compute np.corrcoef(Z[:, j], Z_w[:, j])[0, 1] and take the mean across j = 0..3.
Solution
houses = pd.read_csv("data/houses.csv")cols = ["sqft", "bedrooms", "bathrooms", "condition"]X = houses[cols].to_numpy(dtype=float)Z = (X - X.mean(axis=0)) / X.std(axis=0)n = len(Z)
U, _, Vt = np.linalg.svd(Z, full_matrices=False)Z_pca = np.sqrt(n - 1) * UZ_zca = Z_pca @ Vt
cov_pca_ok = np.allclose(np.cov(Z_pca, rowvar=False), np.eye(4), atol=1e-12)cov_zca_ok = np.allclose(np.cov(Z_zca, rowvar=False), np.eye(4), atol=1e-12)
diag_pca = [abs(float(np.corrcoef(Z[:, j], Z_pca[:, j])[0, 1])) for j in range(4)]diag_zca = [float(np.corrcoef(Z[:, j], Z_zca[:, j])[0, 1]) for j in range(4)]
print("cov(Z_pca) == I:", cov_pca_ok, "cov(Z_zca) == I:", cov_zca_ok)print("mean |diag corr| with original (PCA):", round(float(np.mean(diag_pca)), 4))print("mean diag corr with original (ZCA):", round(float(np.mean(diag_zca)), 4))assert cov_pca_ok and cov_zca_okassert np.mean(diag_zca) > np.mean(diag_pca)cov(Z_pca) == I: True cov(Z_zca) == I: Truemean |diag corr| with original (PCA): 0.2887mean diag corr with original (ZCA): 0.8454How it works:
- Since , multiplying by yields exact sample covariance .
- Multiplying by the orthogonal matrix preserves covariance while aligning every whitened coordinate as closely as possible to its original feature (used in computer vision so whitened images still look like images).
M46-X04 · Latent Semantic Indexing query search on reviews
Section titled “M46-X04 · Latent Semantic Indexing query search on reviews”Build a minimal Latent Semantic Indexing (LSI) search engine on data/reviews.csv:
- Vectorize
reviews["text"]withTfidfVectorizer(stop_words="english", min_df=5, max_df=0.5). - Compute top
k = 10sparse SVD components withscipy.sparse.linalg.svds(T, k=10, random_state=42)(remember to reverse to descending order!). - Represent each document in the 10-D latent space by
D = U * sand project the query"battery life dies quickly"into the same latent space via (equivalentlyvec.transform([query]) @ Vt.T). - Rank reviews by cosine similarity to in latent space, and print the top 3
review_id, cosine score, and first 52 characters of text.
R02645 (0.991) The battery life barely lasts 5 hours.R01762 (0.991) The battery life is much worse than advertised.R01701 (0.991) Battery life is about as advertised.from scipy.sparse.linalg import svdsfrom sklearn.feature_extraction.text import TfidfVectorizer
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)query = "battery life dies quickly"# TODO: fit TfidfVectorizer, compute top-10 svds (sorted descending)# TODO: project query into latent space, rank by cosine similarity, print top 3 matchesHint 1
D = U * s is the (3000, 10) document embedding matrix (T @ Vt.T), and q_lat = (vec.transform([query]) @ Vt.T).ravel() is the (10,) query embedding.
Hint 2
Compute cosine similarity safely by guarding zero-norm rows: norms = np.linalg.norm(D, axis=1); cos = np.divide(D @ q_lat, norms * np.linalg.norm(q_lat), out=np.zeros(len(D)), where=norms > 0).
Solution
from scipy.sparse.linalg import svdsfrom sklearn.feature_extraction.text import TfidfVectorizer
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)T = vec.fit_transform(reviews["text"])
U, s, Vt = svds(T, k=10, random_state=42)order = np.argsort(s)[::-1]U, s, Vt = U[:, order], s[order], Vt[order]
D = U * sq_lat = (vec.transform(["battery life dies quickly"]) @ Vt.T).ravel()norms = np.linalg.norm(D, axis=1)cos = np.divide( D @ q_lat, norms * np.linalg.norm(q_lat), out=np.zeros(len(D)), where=norms > 0,)top3 = np.argsort(cos)[::-1][:3]for idx in top3: snippet = reviews.loc[idx, "text"].replace("\n", " ")[:52] print(f"{reviews.loc[idx, 'review_id']} ({cos[idx]:.3f}) {snippet}")assert all("battery" in reviews.loc[i, "text"].lower() or cos[i] > 0.8 for i in top3)R02645 (0.991) The battery life barely lasts 5 hours.R01762 (0.991) The battery life is much worse than advertised.R01701 (0.991) Battery life is about as advertised.How it works:
- Notice
"dies"and"quickly"might not even appear verbatim in every battery review, yet LSI projects both the query and reviews onto the shared latent battery axis. - Computing cosine similarity in 10 dimensions is fast and captures synonym co-occurrence automatically.
M46-X05 · Total Least Squares via SVD vs. Ordinary Least Squares
Section titled “M46-X05 · Total Least Squares via SVD vs. Ordinary Least Squares”Ordinary Least Squares minimizes vertical errors (assuming is noise-free and only is noisy). When both and have sensor noise, Total Least Squares (TLS) minimizes perpendicular (orthogonal) distances to the fitted line. Given centered data M = np.column_stack([x - x.mean(), y - y.mean()]), the unit normal vector to the best orthogonal line is the last right singular vector Vt[-1] of M, giving slope .
Simulate 200 noisy observations from true slope 2.0 where both and have Gaussian noise (rng = np.random.default_rng(42)). Compare the OLS slope, the TLS slope, and the mean squared orthogonal distance of each line, verifying that TLS achieves both a smaller orthogonal error and a slope closer to the true 2.0 (avoiding OLS attenuation bias!).
OLS: slope=1.7058, mean_orth_sq=0.3817TLS: slope=1.8912, mean_orth_sq=0.3531rng = np.random.default_rng(42)x_true = rng.uniform(-3.0, 3.0, size=200)y_true = 2.0 * x_true + 1.0x_obs = x_true + rng.normal(0.0, 0.6, size=200)y_obs = y_true + rng.normal(0.0, 0.6, size=200)# TODO: compute OLS slope & intercept, TLS slope & intercept via SVD of centered [x_obs, y_obs]# TODO: compare mean squared orthogonal distance and closeness to true slope 2.0Hint 1
Center both variables: xc = x_obs - x_obs.mean(), yc = y_obs - y_obs.mean(), form M = np.column_stack([xc, yc]), and run _, _, Vt = np.linalg.svd(M, full_matrices=False). Then nx, ny = Vt[-1] and m_tls = -nx / ny.
Hint 2
The perpendicular distance from (x, y) to line y = m*x + b is |m*x - y + b| / sqrt(m**2 + 1).
Solution
rng = np.random.default_rng(42)x_true = rng.uniform(-3.0, 3.0, size=200)y_true = 2.0 * x_true + 1.0x_obs = x_true + rng.normal(0.0, 0.6, size=200)y_obs = y_true + rng.normal(0.0, 0.6, size=200)
# OLSA = np.column_stack([np.ones_like(x_obs), x_obs])b_ols, m_ols = np.linalg.lstsq(A, y_obs)[0]
# TLS via last right singular vector (minimum variance direction)M = np.column_stack([x_obs - x_obs.mean(), y_obs - y_obs.mean()])_, _, Vt = np.linalg.svd(M, full_matrices=False)nx, ny = Vt[-1]m_tls = float(-nx / ny)b_tls = float(y_obs.mean() - m_tls * x_obs.mean())
def mean_orth_sq(m: float, b: float) -> float: return float(np.mean(((m * x_obs - y_obs + b) ** 2) / (m**2 + 1.0)))
err_ols = mean_orth_sq(float(m_ols), float(b_ols))err_tls = mean_orth_sq(m_tls, b_tls)print(f"OLS: slope={m_ols:.4f}, mean_orth_sq={err_ols:.4f}")print(f"TLS: slope={m_tls:.4f}, mean_orth_sq={err_tls:.4f}")assert err_tls < err_olsassert abs(m_tls - 2.0) < abs(m_ols - 2.0)OLS: slope=1.7058, mean_orth_sq=0.3817TLS: slope=1.8912, mean_orth_sq=0.3531How it works:
- Because is measured with noise, OLS suffers from attenuation bias—pulling the estimated slope down toward 0.
- The last right singular vector minimizes subject to , which is literally the sum of squared perpendicular distances from every data point to the line!