Skip to content

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:

  1. Copy the setup block and the starter code into a script (for example exercise.py).
  2. Replace each to-do comment with your implementation and run it from the folder containing data/.
  3. 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 np
import pandas as pd
np.set_printoptions(precision=4, suppress=True)
Warm-up

Build a 2-D scaling matrix SS that stretches xx by 2.0 and shrinks yy by 0.5, and a rotation matrix RR that rotates counterclockwise by 60 degrees. Apply SS first and then RR (composite matrix M=RSM = RS) to the point p=(3.0,4.0)\mathbf{p} = (3.0, 4.0). Print the transformed point and the determinant of MM.

Expected output
transformed point: [1.2679 6.1962]
det(R @ S): 1.0
Starter
p = 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 SS first and RR second means R(Sp)=(RS)pR(S\mathbf{p}) = (RS)\mathbf{p}. The determinant of RSRS equals det⁡(R)det⁡(S)=1×(2.0×0.5)=1.0\det(R)\det(S) = 1 \times (2.0 \times 0.5) = 1.0.

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 @ S
p_out = M @ p
det_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)
Output
transformed point: [1.2679 6.1962]
det(R @ S): 1.0

How it works:

  1. Scaling sends (3, 4) to (6, 2).
  2. Rotating (6, 2) counterclockwise by 60∘60^\circ produces R @ S @ p.
  3. Because det⁡(R)=1\det(R) = 1 and det⁡(S)=2.0×0.5=1.0\det(S) = 2.0 \times 0.5 = 1.0, 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”
Warm-up

Predict the output: work out each printed line on paper before running the code. Notice that row 2 of B is twice row 1.

Starter
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 while det(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 2×22 \times 2 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) == 2
assert np.linalg.matrix_rank(B) == 1
assert np.isclose(np.linalg.det(B), 0.0)
Output
A rank: 2
A trace: 2.0
A det: -8.0
B rank: 1
B det: 0.0

How it works:

  1. A is diagonal with nonzero entries 4 and -2, so its rank is 2, its trace is 4 + (-2) = 2.0, and its determinant is 4 * (-2) = -8.0 (the minus sign reflects the yy-axis).
  2. B has linearly dependent rows (row 2 = 2 * row 1), so its rank drops to 1 and its determinant collapses to 0.0.

M46-W03 · Diagnose rank and null-space dimension

Section titled “M46-W03 · Diagnose rank and null-space dimension”
Warm-up

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.

Expected output
shape: (100, 5) rank: 3 null_dim: 2
Starter
houses = 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 them
Hint 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] - rank
print("shape:", X.shape, "rank:", rank, "null_dim:", null_dim)
assert X.shape == (100, 5)
assert rank == 3 and null_dim == 2
Output
shape: (100, 5) rank: 3 null_dim: 2

How it works:

  1. The first three columns are linearly independent, giving a 3-D column space.
  2. Both total_rooms and sqft_x2 lie inside the span of the first three columns, so rank stays 3 and the null space has dimension 5 - 3 = 2.
Warm-up

Project the vector y=(4.0,2.0,5.0)\mathbf{y} = (4.0, 2.0, 5.0) onto the direction a=(1.0,2.0,2.0)\mathbf{a} = (1.0, 2.0, 2.0). Print the scalar coefficient cc, the projection y^=ca\hat{\mathbf{y}} = c\mathbf{a}, the residual r=y−y^\mathbf{r} = \mathbf{y} - \hat{\mathbf{y}}, and verify that a⊤r≈0\mathbf{a}^\top \mathbf{r} \approx 0.

Expected output
c: 2.0
y_hat: [2. 4. 4.]
resid: [ 2. -2. 1.]
orthogonal: True
Starter
y = 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 them
Hint 1

The projection formula onto a single vector is y^=a⊤ya⊤aa\hat{\mathbf{y}} = \frac{\mathbf{a}^\top \mathbf{y}}{\mathbf{a}^\top \mathbf{a}} \mathbf{a}.

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 * a
resid = y - y_hat
print("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,
)
Output
c: 2.0
y_hat: [2. 4. 4.]
resid: [ 2. -2. 1.]
orthogonal: True

How it works:

  1. a⊤y=4+4+10=18\mathbf{a}^\top \mathbf{y} = 4 + 4 + 10 = 18 and a⊤a=1+4+4=9\mathbf{a}^\top \mathbf{a} = 1 + 4 + 4 = 9, so c=2.0c = 2.0.
  2. The residual y−2a=(2,−2,1)\mathbf{y} - 2\mathbf{a} = (2, -2, 1) has dot product 2−4+2=02 - 4 + 2 = 0 with a\mathbf{a}.

M46-W05 · Verify an orthogonal matrix preserves lengths and angles

Section titled “M46-W05 · Verify an orthogonal matrix preserves lengths and angles”
Warm-up

Construct the 3-D Householder reflection matrix Q=I−2vv⊤v⊤vQ = I - 2\frac{\mathbf{v}\mathbf{v}^\top}{\mathbf{v}^\top \mathbf{v}} using v=(1.0,−2.0,2.0)\mathbf{v} = (1.0, -2.0, 2.0). Check that Q⊤Q=IQ^\top Q = I, and verify on x=(3.0,1.0,−4.0)\mathbf{x} = (3.0, 1.0, -4.0) and y=(−1.0,2.0,5.0)\mathbf{y} = (-1.0, 2.0, 5.0) that ∥Qx∥2=∥x∥2\lVert Q\mathbf{x} \rVert_2 = \lVert \mathbf{x} \rVert_2 and (Qx)⊤(Qy)=x⊤y(Q\mathbf{x})^\top (Q\mathbf{y}) = \mathbf{x}^\top \mathbf{y}.

Expected output
Q.T @ Q == I: True
length preserved: True 5.099
dot preserved: True -21.0
det(Q): -1.0
Starter
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])
# TODO: build Householder matrix Q = I - 2 * outer(v, v) / (v @ v)
# TODO: verify orthogonality, length preservation, and dot-product preservation
Hint 1

Use np.outer(v, v) to form vv⊤\mathbf{v}\mathbf{v}^\top.

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_ok
assert np.isclose(np.linalg.det(Q), -1.0)
Output
Q.T @ Q == I: True
length preserved: True 5.099
dot preserved: True -21.0
det(Q): -1.0

How it works:

  1. Householder reflections are the building blocks of np.linalg.qr inside LAPACK.
  2. Every Householder matrix is symmetric and orthogonal with determinant -1.0 (a reflection across the plane perpendicular to v\mathbf{v}).

M46-W06 · Symmetric eigendecomposition with eigh

Section titled “M46-W06 · Symmetric eigendecomposition with eigh”
Warm-up

Compute the eigenvalues and eigenvectors of the symmetric matrix S=[5222]S = \begin{bmatrix} 5 & 2 \\ 2 & 2 \end{bmatrix} using np.linalg.eigh. Sort them in descending eigenvalue order, print the eigenvalues, and verify S=QΛQ⊤S = Q \Lambda Q^\top.

Expected output
eigenvalues (desc): [6. 1.]
spectral reconstruction ok: True
Starter
S = np.array([[5.0, 2.0], [2.0, 2.0]])
# TODO: call np.linalg.eigh(S), sort descending, verify Q @ diag(vals) @ Q.T == S
Hint 1

Sort indices descending with idx = np.argsort(vals)[::-1], then slice vals = vals[idx] and vecs = vecs[:, idx].

Hint 2

Reconstruct SS 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_ok
Output
eigenvalues (desc): [6. 1.]
spectral reconstruction ok: True

How it works:

  1. The characteristic equation (5−λ)(2−λ)−4=λ2−7λ+6=0(5-\lambda)(2-\lambda) - 4 = \lambda^2 - 7\lambda + 6 = 0 gives exact eigenvalues 6 and 1.
  2. Reordering columns of vecs alongside vals preserves S=QΛQ⊤S = Q \Lambda Q^\top.

M46-W07 · Check positive definiteness of a covariance matrix

Section titled “M46-W07 · Check positive definiteness of a covariance matrix”
Warm-up

Load data/houses.csv, standardize sqft, bedrooms, bathrooms, and condition, and compute the sample covariance matrix Σ\Sigma. Check whether Σ\Sigma is positive definite using np.linalg.eigvalsh, and verify that np.linalg.cholesky(Sigma) succeeds and reproduces Σ=LL⊤\Sigma = L L^\top.

Expected output
min eigenvalue: 0.1036
positive definite: True
Cholesky L @ L.T == Sigma: True
Starter
houses = 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 == Sigma
Hint 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_ok
Output
min eigenvalue: 0.1036
positive definite: True
Cholesky L @ L.T == Sigma: True

How it works:

  1. Every eigenvalue of Sigma is strictly positive (the smallest is positive because no column is an exact linear combination of the others).
  2. Cholesky factorization LL⊤=ΣL L^\top = \Sigma confirms positive definiteness directly.

M46-W08 · Reconstruct a matrix from reduced SVD

Section titled “M46-W08 · Reconstruct a matrix from reduced SVD”
Warm-up

Compute the reduced SVD (full_matrices=False) of the 4×34 \times 3 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.

Expected output
shapes: (4, 3) (3,) (3, 3)
singular values: [25.4624 1.2907 0. ]
exact match: True
Starter
A = np.arange(1.0, 13.0).reshape(4, 3)
# TODO: compute reduced SVD, print shapes and singular values, verify reconstruction
Hint 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) @ Vt
max_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-12
Output
shapes: (4, 3) (3,) (3, 3)
singular values: [25.4624 1.2907 0. ]
exact match: True

How it works:

  1. Because rows of A increase by a constant step [3, 3, 3], A has rank 2, which is why the third singular value is 0.0.
  2. Broadcasting U * s scales each column of U cleanly without allocating np.diag(s).

M46-C01 · Implement modified Gram–Schmidt

Section titled “M46-C01 · Implement modified Gram–Schmidt”
Core

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.

Expected output
orthonormality ok: True
reconstruction ok: True
R upper triangular: True
R diagonal: [3.6099 3.2261 3.6546 2.8494]
Starter
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 triangularity
Hint 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_ok
Output
orthonormality ok: True
reconstruction ok: True
R upper triangular: True
R diagonal: [3.6099 3.2261 3.6546 2.8494]

How it works:

  1. Updating v after each single projection (modified Gram–Schmidt) keeps Q orthonormal to near machine precision.
  2. Each diagonal entry R[j, j] is the length of column j’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”
Core

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.

Expected output
weights: [12.9195 0.3589 0.0377 0.1439 -0.1935]
matches lstsq: True
residuals orthogonal to A: True
Starter
houses = 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 orthogonality
Hint 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)
Output
weights: [12.9195 0.3589 0.0377 0.1439 -0.1935]
matches lstsq: True
residuals orthogonal to A: True

How it works:

  1. Substituting A=QRA = QR into the normal equations cancels Q⊤Q=IQ^\top Q = I and leaves Rw=Q⊤yR\mathbf{w} = Q^\top \mathbf{y}.
  2. Because w_qr minimizes ∥y−Aw∥2\lVert \mathbf{y} - A\mathbf{w} \rVert_2, the residual is perpendicular to every column of A, 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”
Core

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.

Expected output
lam1: 2.0369
pc1: [0.626 0.6495 0.4317]
eigenvector equation ok: True
Starter
R = 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] > 0
Hint 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()
Output
lam1: 2.0369
pc1: [0.626 0.6495 0.4317]
eigenvector equation ok: True

How it works:

  1. eigh guarantees real eigenvalues and orthonormal columns; reversing the sort puts the largest eigenvalue at index 0.
  2. 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”
Core

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.

Expected output
condition number: 5.929
smallest singular value: 16.614
age : +0.0024
tenure_months : -0.6475
monthly_charges : -0.2842
total_charges : +0.7071
Starter
customers = 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 vector
Hint 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 σ\sigma satisfies Zvmin⁡≈0Z\mathbf{v}_{\min} \approx \mathbf{0}, 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 collinearity
assert abs(v_min[-1]) > 0.7 # total_charges dominates the null-like direction
Output
condition number: 5.929
smallest singular value: 16.614
age : +0.0024
tenure_months : -0.6475
monthly_charges : -0.2842
total_charges : +0.7071

How it works:

  1. The last right singular vector gives the approximate linear relation 0.71 * total_charges - 0.65 * tenure_months - 0.28 * monthly_charges ≈ 0.
  2. Notice age has weight nearly 0.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”
Core

Given the tall matrix X below and vector y, compute an orthonormal basis Q for col⁡(X)\operatorname{col}(X) via np.linalg.qr, form the projection matrix P=QQ⊤P = QQ^\top, and verify four properties: symmetry (P⊤=PP^\top = P), idempotence (P2=PP^2 = P), rank equal to tr⁡(P)=2\operatorname{tr}(P) = 2, and the Pythagorean identity ∥y∥22=∥Py∥22+∥(I−P)y∥22\lVert \mathbf{y} \rVert_2^2 = \lVert P\mathbf{y} \rVert_2^2 + \lVert (I - P)\mathbf{y} \rVert_2^2.

Expected output
symmetric: True idempotent: True
trace(P) == rank(X): 2.0 2
Pythagoras holds: True ||r||: 1.2247
Starter
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])
# TODO: build Q via qr, form P = Q @ Q.T, verify symmetry, idempotence, trace, Pythagoras
Hint 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 rank⁡(X)\operatorname{rank}(X) 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 @ y
r = y - y_hat
sym_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)
Output
symmetric: True idempotent: True
trace(P) == rank(X): 2.0 2
Pythagoras holds: True ||r||: 1.2247

How it works:

  1. P2=QQ⊤QQ⊤=QIQ⊤=PP^2 = Q Q^\top Q Q^\top = Q I Q^\top = P: projecting twice does nothing after the first projection.
  2. In real ML code you rarely form the n×nn \times n matrix PP explicitly; instead you compute Q @ (Q.T @ y) in O(np)O(np) instead of O(n2)O(n^2).

M46-C06 · Determinant as area scaling and stable slogdet

Section titled “M46-C06 · Determinant as area scaling and stable slogdet”
Core

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 300ln⁡(0.05)300 \ln(0.05).

Expected output
parallelogram area vs |det(A)|: 5.5 5.5
det(0.05 * I_300) underflows: 0.0
slogdet vs 300*ln(0.05): -898.7197 -898.7197
Starter
A = 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.0
assert sign == 1.0 and np.isclose(logdet_c, exact_logdet)
Output
parallelogram area vs |det(A)|: 5.5 5.5
det(0.05 * I_300) underflows: 0.0
slogdet vs 300*ln(0.05): -898.7197 -898.7197

How it works:

  1. 0.05300≈10−3910.05^{300} \approx 10^{-391} is smaller than the smallest float64 number (≈10−308\approx 10^{-308}), so det silently returns 0.0 even though C is invertible with condition number 1.0.
  2. slogdet works in log space and matches 300ln⁡(0.05)300 \ln(0.05) cleanly.

M46-C07 · Compress category monthly sales and check Eckart–Young

Section titled “M46-C07 · Compress category monthly sales and check Eckart–Young”
Core

Load data/sales.csv and build the 6×246 \times 24 matrix of monthly revenue by category (rows = category, columns = YYYY-MM). Compute its reduced SVD. For ranks k=1,2,3k = 1, 2, 3, print the actual Frobenius reconstruction error ∥M−Mk∥F\lVert M - M_k \rVert_F, the Eckart–Young tail ∑i>kσi2\sqrt{\sum_{i>k} \sigma_i^2}, and the percentage of total Frobenius energy retained.

Expected output
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%
Starter
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, 3
Hint 1

Create month = sales["order_date"].str.slice(0, 7) and pivot with index="category", columns="month", values="revenue", aggfunc="sum".

Hint 2

Rank-kk 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)
Output
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:

  1. Rank 1 captures over 98% of the category-by-month revenue energy because Electronics dominates every month with a shared November–December spike.
  2. 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”
Core

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 4×34 \times 3 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]).

Expected output
matches np.linalg.pinv: True
w_pinv: [ 1.1212 -0.2424 0.8788]
matches lstsq: True
Starter
def 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.lstsq
Hint 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 @ y
w_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)
Output
matches np.linalg.pinv: True
w_pinv: [ 1.1212 -0.2424 0.8788]
matches lstsq: True

How it works:

  1. Because column 3 equals column 1 plus column 2, A has rank 2 and its third singular value is zero.
  2. Zeroing 1 / s[2] projects the solution onto the row space of A, guaranteeing the unique least-squares vector of smallest L2 norm.

M46-C09 · Predict the output: singular values vs. eigenvalues of X⊤XX^\top X

Section titled “M46-C09 · Predict the output: singular values vs. eigenvalues of X⊤XX^\top XX⊤X”
Core

Predict the output: without running the code first, predict all four lines printed below for the 3×23 \times 2 matrix X.

Starter
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

X⊤X=diag⁡(9,16)X^\top X = \operatorname{diag}(9, 16), whose eigenvalues are 16 and 9.

Hint 2

np.linalg.svd always sorts singular values descending, and the Frobenius norm is 32+42\sqrt{3^2 + 4^2}.

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)
Output
singular values of X: [4. 3.]
eigenvalues of X.T @ X: [16. 9.]
s**2 == eigs: True
Frobenius norm of X: 5.0

How it works:

  1. Singular values of XX are the square roots of the eigenvalues of X⊤XX^\top X, always returned in descending order ([4., 3.]).
  2. The Frobenius norm equals σ12+σ22=16+9=5.0\sqrt{\sigma_1^2 + \sigma_2^2} = \sqrt{16 + 9} = 5.0.

M46-C10 · Implement PCA from scratch via SVD

Section titled “M46-C10 · Implement PCA from scratch via SVD”
Core

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).

Expected output
explained ratios: [0.5591 0.2831 0.1036]
ratios match sklearn: True
scores match up to sign: True
Starter
from 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 PCA
Hint 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)
Output
explained ratios: [0.5591 0.2831 0.1036]
ratios match sklearn: True
scores match up to sign: True

How it works:

  1. U[:, :k] * s[:k] equals Xc @ Vt[:k].T directly from Xc=UΣV⊤X_c = U\Sigma V^\top and V⊤V=IV^\top V = I.
  2. Notice sklearn.decomposition.PCA uses 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”
Core

Write ridge_svd(X, y, lam) that centers X and y (so the intercept is unpenalized) and computes Ridge weights via w=Vdiag⁡ ⁣(σiσi2+λ)U⊤yc\mathbf{w} = V \operatorname{diag}\!\left(\frac{\sigma_i}{\sigma_i^2 + \lambda}\right) U^\top \mathbf{y}_c and intercept b=yˉ−xˉ⊤wb = \bar{y} - \bar{\mathbf{x}}^\top \mathbf{w}. 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).

Expected output
w_svd: [ 0.3257 -0.0048 0.0548 0.106 ] b: 12.9195
matches normal eq: True
matches sklearn: True
Starter
from 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 Ridge
Hint 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.0
w_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)
Output
w_svd: [ 0.3257 -0.0048 0.0548 0.106 ] b: 12.9195
matches normal eq: True
matches sklearn: True

How it works:

  1. Substituting Xc=UΣV⊤X_c = U\Sigma V^\top into (Xc⊤Xc+λI)−1Xc⊤yc(X_c^\top X_c + \lambda I)^{-1} X_c^\top \mathbf{y}_c turns the inverse into a diagonal scaling σiσi2+λ\frac{\sigma_i}{\sigma_i^2 + \lambda}.
  2. Small singular values (σi≪λ\sigma_i \ll \sqrt{\lambda}) 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”
Core

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.

Expected output
cond(V): 1.17e+08
cond(V.T @ V): 1.17e+08^2 -> 1.35e+16
normal eq max error: 1.13e-01
QR max error: 6.58e-09
QR >1000x more accurate: True
Starter
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
# TODO: print cond(V), cond(V.T @ V), and max weight error for normal eqs vs QR
Hint 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 10810^8, so cond(V.T @ V) reaches ≈1016\approx 10^{16}, 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_qr
Output
cond(V): 1.17e+08
cond(V.T @ V): 1.17e+08^2 -> 1.35e+16
normal eq max error: 1.13e-01
QR max error: 6.58e-09
QR >1000x more accurate: True

How it works:

  1. Powers 1,t,t2,…,t111, t, t^2, \dots, t^{11} on [0,1][0, 1] look nearly identical in shape, pushing κ(V)\kappa(V) above 10710^7 and κ(V⊤V)\kappa(V^\top V) past 101510^{15}.
  2. 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.

M46-X01 · Power iteration with deflation for top two eigenvectors

Section titled “M46-X01 · Power iteration with deflation for top two eigenvectors”
Challenge

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 v←Sv/∥Sv∥2\mathbf{v} \leftarrow S\mathbf{v} / \lVert S\mathbf{v} \rVert_2 and evaluating the Rayleigh quotient λ=v⊤Sv\lambda = \mathbf{v}^\top S \mathbf{v}. Then apply Hotelling deflation (S2=S−λ1v1v1⊤S_2 = S - \lambda_1 \mathbf{v}_1 \mathbf{v}_1^\top) and run power iteration a second time to recover (λ2,v2)(\lambda_2, \mathbf{v}_2). 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.

Expected output
lam1: 2.824493 (eigh: 2.824493), |cos|=1.000000
lam2: 1.646573 (eigh: 1.646573), |cos|=1.000000
v1 orthogonal to v2: True
Starter
def 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 eigh
Hint 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 λ1\lambda_1 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-6
Output
lam1: 2.824493 (eigh: 2.824493), |cos|=1.000000
lam2: 1.646573 (eigh: 1.646573), |cos|=1.000000
v1 orthogonal to v2: True

How it works:

  1. Repeated multiplication by SS amplifies the component along v1\mathbf{v}_1 by (λ1/λ2)k(\lambda_1 / \lambda_2)^k relative to v2\mathbf{v}_2, converging rapidly whenever λ1>λ2\lambda_1 > \lambda_2.
  2. Subtracting λ1v1v1⊤\lambda_1 \mathbf{v}_1 \mathbf{v}_1^\top turns the largest eigenvalue into 0, making λ2\lambda_2 the new dominant eigenvalue.

M46-X02 · Compute Variance Inflation Factors using QR factorization

Section titled “M46-X02 · Compute Variance Inflation Factors using QR factorization”
Challenge

Write vif_qr(Z) for a standardized (zero-mean, unit-std) matrix Z that computes each column’s Variance Inflation Factor VIFj=1/(1−Rj2)\text{VIF}_j = 1 / (1 - R_j^2) 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.

Expected output
age VIF = 1.00
tenure_months VIF = 8.08
monthly_charges VIF = 2.37
total_charges VIF = 682.47
est_total VIF = 693.01
matches inv(R) diagonal: True
Starter
def 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 inverse
Hint 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)
Output
age VIF = 1.00
tenure_months VIF = 8.08
monthly_charges VIF = 2.37
total_charges VIF = 682.47
est_total VIF = 693.01
matches inv(R) diagonal: True

How it works:

  1. Regressing standardized column jj on the remaining columns via QR gives Rj2R_j^2 directly as the squared projection ratio without ever squaring the condition number in Z⊤ZZ^\top Z.
  2. Even when two columns are nearly duplicates (total_charges and est_total), QR stays stable.

M46-X03 · Implement PCA and ZCA whitening transforms

Section titled “M46-X03 · Implement PCA and ZCA whitening transforms”
Challenge

Whitening transforms correlated zero-mean features ZZ into uncorrelated features with unit covariance (cov⁡(Zw)=I\operatorname{cov}(Z_w) = I). Using reduced SVD Z=UΣV⊤Z = U\Sigma V^\top on sqft, bedrooms, bathrooms, and condition from data/houses.csv:

  • PCA whitening: ZPCA=n−1 UZ_{\text{PCA}} = \sqrt{n - 1}\, U
  • ZCA whitening: ZZCA=n−1 UV⊤Z_{\text{ZCA}} = \sqrt{n - 1}\, U V^\top (rotates back to the original feature axes!)

Verify both produce sample covariance equal to I4I_4, and compute the mean diagonal correlation corr⁡(Z[:,j],Zw[:,j])\operatorname{corr}(Z[:, j], Z_w[:, j]) to show that ZCA stays much closer to the original feature meanings than PCA whitening.

Expected output
cov(Z_pca) == I: True cov(Z_zca) == I: True
mean |diag corr| with original (PCA): 0.2887
mean diag corr with original (ZCA): 0.8454
Starter
houses = 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 Z
Hint 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) * U
Z_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_ok
assert np.mean(diag_zca) > np.mean(diag_pca)
Output
cov(Z_pca) == I: True cov(Z_zca) == I: True
mean |diag corr| with original (PCA): 0.2887
mean diag corr with original (ZCA): 0.8454

How it works:

  1. Since U⊤U=IU^\top U = I, multiplying UU by n−1\sqrt{n - 1} yields exact sample covariance 1n−1(n−1U)⊤(n−1U)=I\frac{1}{n-1}(\sqrt{n-1}U)^\top(\sqrt{n-1}U) = I.
  2. Multiplying by the orthogonal matrix V⊤V^\top preserves covariance VIV⊤=IV I V^\top = I 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”
Challenge

Build a minimal Latent Semantic Indexing (LSI) search engine on data/reviews.csv:

  1. Vectorize reviews["text"] with TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5).
  2. Compute top k = 10 sparse SVD components with scipy.sparse.linalg.svds(T, k=10, random_state=42) (remember to reverse to descending order!).
  3. Represent each document in the 10-D latent space by D = U * s and project the query "battery life dies quickly" into the same latent space via qlat=V⊤q\mathbf{q}_{\text{lat}} = V^\top \mathbf{q} (equivalently vec.transform([query]) @ Vt.T).
  4. Rank reviews by cosine similarity to qlat\mathbf{q}_{\text{lat}} in latent space, and print the top 3 review_id, cosine score, and first 52 characters of text.
Expected output
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.
Starter
from scipy.sparse.linalg import svds
from 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 matches
Hint 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 svds
from 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 * s
q_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)
Output
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:

  1. 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.
  2. 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”
Challenge

Ordinary Least Squares minimizes vertical errors (assuming xx is noise-free and only yy is noisy). When both xx and yy 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 n=(nx,ny)\mathbf{n} = (n_x, n_y) to the best orthogonal line is the last right singular vector Vt[-1] of M, giving slope mTLS=−nx/nym_{\text{TLS}} = -n_x / n_y.

Simulate 200 noisy observations from true slope 2.0 where both xx and yy have Gaussian noise σ=0.6\sigma = 0.6 (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!).

Expected output
OLS: slope=1.7058, mean_orth_sq=0.3817
TLS: slope=1.8912, mean_orth_sq=0.3531
Starter
rng = np.random.default_rng(42)
x_true = rng.uniform(-3.0, 3.0, size=200)
y_true = 2.0 * x_true + 1.0
x_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.0
Hint 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.0
x_obs = x_true + rng.normal(0.0, 0.6, size=200)
y_obs = y_true + rng.normal(0.0, 0.6, size=200)
# OLS
A = 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_ols
assert abs(m_tls - 2.0) < abs(m_ols - 2.0)
Output
OLS: slope=1.7058, mean_orth_sq=0.3817
TLS: slope=1.8912, mean_orth_sq=0.3531

How it works:

  1. Because xx is measured with noise, OLS suffers from attenuation bias—pulling the estimated slope down toward 0.
  2. The last right singular vector minimizes ∥Mn∥22\lVert M \mathbf{n} \rVert_2^2 subject to ∥n∥2=1\lVert \mathbf{n} \rVert_2 = 1, which is literally the sum of squared perpendicular distances from every data point to the line!