Skip to content

46. Linear algebra in depth — Mini-project

Your analytics team maintains a house-pricing pipeline built from two merged property feeds. One feed reports floor area in square feet (sqft), while a partner feed appends living_area_sqm (rounded to the nearest square meter). After the merge, ordinary least squares coefficients for house size started swinging wildly between retrains.

Build a pure-NumPy PCA, Ridge & Collinearity Auditor (linalg_auditor.py) with three reusable components:

  1. Collinearity auditor: computes matrix rank, singular values, condition number, and every feature’s Variance Inflation Factor (VIF) using QR factorization—without inverting a correlation matrix.
  2. SVD-based PCA engine: fits principal components via np.linalg.svd, reports explained variance ratios and Eckart–Young Frobenius reconstruction errors, and matches sklearn.decomposition.PCA.
  3. SVD Ridge regression solver: uses one SVD to compute Ridge weights across an entire grid of penalties λ\lambda via singular-value shrinkage σiσi2+λ\frac{\sigma_i}{\sigma_i^2 + \lambda}, verifies exact agreement with sklearn.linear_model.Ridge, and shows how Ridge tames the collinear coefficients.

data/houses.csv: 3,000 house sales from 2022 to 2024 (see the data dictionary). Build these features:

Feature Notes
sqft, bedrooms, bathrooms strongly correlated size features
age sale year minus year_built
lot_sqft, school_rating each has 90 blanks; fill with the training median
garage_spaces, condition, distance_to_center_km complete numeric features
living_area_sqm simulated partner-feed column: np.round(sqft * 0.092903) (near-collinear with sqft)
target: log_price natural log of price

Your script must:

  1. Load data/houses.csv, build age and living_area_sqm, and split rows 80/20 into training and test sets with np.random.default_rng(42).permutation.
  2. Fill missing values in lot_sqft and school_rating using training medians only, then standardize all features with training mean and standard deviation only.
  3. Implement audit_collinearity(Z, names) using NumPy only: return rank, condition number, smallest singular value, and per-feature VIF computed by regressing each column on the remaining columns via np.linalg.qr (VIFj=1/(1−Rj2)\text{VIF}_j = 1 / (1 - R_j^2)). Run it on both the 9-feature clean set and the 10-feature merged set.
  4. Implement fit_pca_svd(Z) returning components, singular values, and explained variance ratios. Verify that explained variance ratios match sklearn.decomposition.PCA to 1e-10 and that rank-kk reconstruction Frobenius error matches ∑i>kσi2\sqrt{\sum_{i>k}\sigma_i^2} for k=1,3,5k = 1, 3, 5.
  5. Implement ridge_path_svd(Z_train, y_train, lambdas) that computes a single reduced SVD of Z_train and evaluates Ridge weights and intercept across a log-spaced grid of λ\lambda values (np.logspace(-2, 4, 25)), centering y_train so the intercept is never penalized.
  6. Verify your SVD Ridge weights match sklearn.linear_model.Ridge(alpha=lam) on the 10-feature collinear matrix to 1e-6 for at least three λ\lambda values.
  7. Compare OLS (λ=0\lambda = 0) vs. best-λ\lambda Ridge on the 10-feature set: print the fitted weights for sqft and living_area_sqm and both test RMSEs.
  8. Generate a 2-panel figure showing (left) the PCA scree and cumulative variance curve on the 9 clean features and (right) the Ridge coefficient shrinkage path across λ\lambda on the 10 merged features.
  1. Load, engineer, and split. Read data/houses.csv, create age and living_area_sqm, permute indices with seed 42, and take an 80/20 split before computing any medians or scaling statistics.

  2. Impute and standardize cleanly. Fill lot_sqft and school_rating NaNs with training medians. Standardize both the 9 clean features and the 10 merged features with training mean and std.

  3. Write the QR-based collinearity auditor. For each feature jj, take the remaining p−1p - 1 columns Z−jZ_{-j}, factor Z−j=QRZ_{-j} = QR, project z^j=Q(Q⊤zj)\hat{\mathbf{z}}_j = Q(Q^\top \mathbf{z}_j), compute Rj2=1−∥zj−z^j∥22/∥zj∥22R_j^2 = 1 - \lVert \mathbf{z}_j - \hat{\mathbf{z}}_j \rVert_2^2 / \lVert \mathbf{z}_j \rVert_2^2 (since zj\mathbf{z}_j is already zero-mean), and compute VIFj=1/(1−Rj2)\text{VIF}_j = 1 / (1 - R_j^2).

  4. Build and check SVD PCA. Run np.linalg.svd(Z_clean, full_matrices=False). Compute explained variance ratios s**2 / np.sum(s**2) and verify rank-kk Frobenius errors against the Eckart–Young tail.

  5. Implement single-SVD Ridge. Compute U, s, Vt = np.linalg.svd(Z_train, full_matrices=False) and uty = U.T @ (y_train - y_mean) once. For each λ\lambda, compute w = Vt.T @ ((s / (s**2 + lam)) * uty) and intercept b = y_mean.

  6. Validate against scikit-learn. Assert np.allclose against both PCA and Ridge at multiple λ\lambda values.

  7. Compare OLS vs. Ridge and plot. Inspect how OLS splits huge opposing weights between sqft and living_area_sqm, how Ridge stabilizes them, and draw the 2-panel diagnostic figure.

A starter skeleton:

linalg_auditor.py (starter)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.linear_model import Ridge
CLEAN_FEATURES = [
"sqft",
"bedrooms",
"bathrooms",
"age",
"lot_sqft",
"garage_spaces",
"condition",
"distance_to_center_km",
"school_rating",
]
MERGED_FEATURES = CLEAN_FEATURES + ["living_area_sqm"]
# --- 1. Load, engineer age & living_area_sqm, split 80/20 ---
# TODO: read data/houses.csv, compute age and living_area_sqm, seeded permutation split
# --- 2. Impute missing values & standardize using training stats only ---
# TODO: fill lot_sqft and school_rating with training medians; compute Z_train, Z_test
# --- 3. QR-based collinearity auditor ---
def audit_collinearity(Z: np.ndarray, names: list[str]) -> dict:
# TODO: rank, condition number, smallest singular value, and VIF via np.linalg.qr
raise NotImplementedError
# --- 4. SVD PCA + Eckart-Young verification ---
def fit_pca_svd(Z: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
# TODO: return (components, singular_values, explained_variance_ratio)
raise NotImplementedError
# --- 5. Single-SVD Ridge path ---
def ridge_path_svd(
Z_train: np.ndarray, y_train: np.ndarray, lambdas: np.ndarray
) -> tuple[np.ndarray, float]:
# TODO: one SVD, return weights array (len(lambdas), p) and intercept y_mean
raise NotImplementedError
# --- 6. Verify against scikit-learn and draw the 2-panel diagnostic plot ---
# TODO: assertions + scree plot + Ridge shrinkage path
Criterion Points Full points when
Data prep and no leakage 3 age and living_area_sqm built correctly; split precedes imputation and standardization
QR collinearity auditor 4 Reports rank, condition number, smallest singular value, and exact VIF via QR (no inv)
SVD PCA & Eckart–Young 4 Matches sklearn.decomposition.PCA to 1e-10 and verifies Frobenius error at k=1,3,5k=1, 3, 5
Single-SVD Ridge path 4 Computes one SVD outside the λ\lambda loop; intercept left unpenalized; matches sklearn Ridge to 1e-6
Collinearity stabilization analysis 3 Contrasts OLS vs. Ridge weights on sqft and living_area_sqm and reports test RMSE
Visualization & code quality 2 Clear 2-panel scree + Ridge path figure; clean functions, type hints, and assertions
Total 20 16 or more: you are ready for module 47
  1. Add a helper whiten_zca(Z) that transforms standardized features via ZZCA=ZVΣ−1V⊤n−1Z_{\text{ZCA}} = Z V \Sigma^{-1} V^\top \sqrt{n - 1} and verifies the whitened covariance matrix equals the identity matrix II.
  2. Implement 5-fold cross-validation inside ridge_path_svd (computing 5 SVDs total, one per fold) to pick λ∗\lambda^* without touching the test set.
  3. Implement Principal Component Regression (PCR): keep the top kk singular components of Z_train and compare test RMSE of PCR vs. Ridge across k=1…10k = 1 \dots 10.
  4. Run audit_collinearity on data/customers.csv numeric columns and identify which billing feature should be dropped or regularized.

Try building linalg_auditor.py yourself first, then compare your results and structure with the verified reference solution below.

Reference solution
linalg_auditor.py (part 1: data and leakage-free preprocessing)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.linear_model import Ridge
np.set_printoptions(precision=4, suppress=True)
CLEAN_FEATURES = [
"sqft",
"bedrooms",
"bathrooms",
"age",
"lot_sqft",
"garage_spaces",
"condition",
"distance_to_center_km",
"school_rating",
]
MERGED_FEATURES = CLEAN_FEATURES + ["living_area_sqm"]
houses = pd.read_csv("data/houses.csv")
houses["age"] = pd.to_datetime(houses["sold_date"]).dt.year - houses["year_built"]
houses["living_area_sqm"] = np.round(houses["sqft"] * 0.092903)
X_all = houses[MERGED_FEATURES].to_numpy(dtype=float)
y_all = np.log(houses["price"].to_numpy(dtype=float))
order = np.random.default_rng(42).permutation(len(y_all))
n_train = int(0.8 * len(y_all))
train_idx, test_idx = order[:n_train], order[n_train:]
X_train = X_all[train_idx].copy()
X_test = X_all[test_idx].copy()
y_train, y_test = y_all[train_idx], y_all[test_idx]
for col_name in ("lot_sqft", "school_rating"):
j = MERGED_FEATURES.index(col_name)
med = float(np.nanmedian(X_train[:, j]))
X_train[:, j] = np.where(np.isnan(X_train[:, j]), med, X_train[:, j])
X_test[:, j] = np.where(np.isnan(X_test[:, j]), med, X_test[:, j])
mu = X_train.mean(axis=0)
sigma = X_train.std(axis=0)
Z_train_merged = (X_train - mu) / sigma
Z_test_merged = (X_test - mu) / sigma
Z_train_clean = Z_train_merged[:, : len(CLEAN_FEATURES)]
Z_test_clean = Z_test_merged[:, : len(CLEAN_FEATURES)]
print(f"train: {Z_train_merged.shape}, test: {Z_test_merged.shape}")
missing_total = int(np.isnan(Z_train_merged).sum() + np.isnan(Z_test_merged).sum())
print("missing left:", missing_total)
Output
train: (2400, 10), test: (600, 10)
missing left: 0
linalg_auditor.py (part 2: QR collinearity auditor)
def audit_collinearity(Z: np.ndarray, names: list[str]) -> dict:
"""Compute rank, condition number, smallest singular value, and QR-based VIF."""
s = np.linalg.svd(Z, compute_uv=False)
rank = int(np.linalg.matrix_rank(Z))
vifs: dict[str, float] = {}
p = Z.shape[1]
for j, name in enumerate(names):
others = np.delete(Z, j, axis=1)
Q, _ = np.linalg.qr(others)
z_j = Z[:, j]
z_hat = Q @ (Q.T @ z_j)
ss_res = float(np.sum((z_j - z_hat) ** 2))
ss_tot = float(np.sum(z_j**2))
r2 = 1.0 - ss_res / ss_tot
vifs[name] = float("inf") if r2 >= 1.0 else 1.0 / (1.0 - r2)
return {
"rank": rank,
"p": p,
"cond": float(s[0] / s[-1]),
"s_min": float(s[-1]),
"vifs": vifs,
}
rep_clean = audit_collinearity(Z_train_clean, CLEAN_FEATURES)
rep_merged = audit_collinearity(Z_train_merged, MERGED_FEATURES)
print(
f"clean ({rep_clean['p']} cols): rank={rep_clean['rank']}, "
f"cond={rep_clean['cond']:.2f}, s_min={rep_clean['s_min']:.3f}"
)
print(
f"merged ({rep_merged['p']} cols): rank={rep_merged['rank']}, "
f"cond={rep_merged['cond']:.2f}, s_min={rep_merged['s_min']:.4f}"
)
top_clean = sorted(rep_clean["vifs"].items(), key=lambda kv: -kv[1])[:3]
top_merged = sorted(rep_merged["vifs"].items(), key=lambda kv: -kv[1])[:3]
print("top 3 VIFs (clean): ", {k: round(v, 2) for k, v in top_clean})
print("top 3 VIFs (merged):", {k: round(v, 1) for k, v in top_merged})
assert rep_merged["vifs"]["sqft"] > 10_000
assert rep_merged["vifs"]["living_area_sqm"] > 10_000
Output
clean (9 cols): rank=9, cond=5.38, s_min=15.791
merged (10 cols): rank=10, cond=639.01, s_min=0.1508
top 3 VIFs (clean): {'bedrooms': 6.05, 'bathrooms': 5.74, 'sqft': 4.33}
top 3 VIFs (merged): {'living_area_sqm': 52769.9, 'sqft': 52754.6, 'bedrooms': 6.1}
linalg_auditor.py (part 3: SVD PCA and Eckart-Young check)
def fit_pca_svd(Z: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Fit PCA on zero-mean matrix Z using reduced SVD."""
_, s, Vt = np.linalg.svd(Z, full_matrices=False)
explained_ratio = (s**2) / np.sum(s**2)
return Vt, s, explained_ratio
comps, s_clean, var_ratio = fit_pca_svd(Z_train_clean)
sk_pca = PCA().fit(Z_train_clean)
assert np.allclose(var_ratio, sk_pca.explained_variance_ratio_, atol=1e-10)
U_c, s_c, Vt_c = np.linalg.svd(Z_train_clean, full_matrices=False)
print("explained variance ratios:", np.round(var_ratio, 4))
print("cumulative (top 5): ", np.round(np.cumsum(var_ratio)[:5], 4))
for k in (1, 3, 5):
Z_k = (U_c[:, :k] * s_c[:k]) @ Vt_c[:k, :]
err_actual = float(np.linalg.norm(Z_train_clean - Z_k, ord="fro"))
err_ey = float(np.sqrt(np.sum(s_c[k:] ** 2)))
assert np.isclose(err_actual, err_ey, atol=1e-10)
print(f"k={k}: frob_err={err_actual:.4f} == Eckart-Young {err_ey:.4f}")
Output
explained variance ratios: [0.3337 0.243 0.1284 0.1061 0.079 0.0528 0.0272 0.0181 0.0115]
cumulative (top 5): [0.3337 0.5768 0.7052 0.8113 0.8902]
k=1: frob_err=119.9650 == Eckart-Young 119.9650
k=3: frob_err=79.8038 == Eckart-Young 79.8038
k=5: frob_err=48.6889 == Eckart-Young 48.6889
linalg_auditor.py (part 4: single-SVD Ridge path and verification)
def ridge_path_svd(
Z_train: np.ndarray, y_train: np.ndarray, lambdas: np.ndarray
) -> tuple[np.ndarray, float]:
"""Solve Ridge for every lambda using a single reduced SVD."""
y_mean = float(y_train.mean())
y_c = y_train - y_mean
U, s, Vt = np.linalg.svd(Z_train, full_matrices=False)
uty = U.T @ y_c
weights = np.empty((len(lambdas), Z_train.shape[1]), dtype=float)
for idx, lam in enumerate(lambdas):
shrink = s / (s**2 + lam)
weights[idx] = Vt.T @ (shrink * uty)
return weights, y_mean
lambdas = np.logspace(-2, 4, 25)
W_path, intercept = ridge_path_svd(Z_train_merged, y_train, lambdas)
for check_lam in (0.1, 10.0, 1000.0):
i = int(np.argmin(np.abs(lambdas - check_lam)))
sk_ridge = Ridge(alpha=float(lambdas[i])).fit(Z_train_merged, y_train)
assert np.allclose(W_path[i], sk_ridge.coef_, atol=1e-6)
assert np.isclose(intercept, sk_ridge.intercept_, atol=1e-6)
print("verified SVD Ridge matches sklearn.linear_model.Ridge to 1e-6")
# Compare OLS (lambda=0) vs Ridge at best test RMSE on the collinear matrix
w_ols, b_ols = ridge_path_svd(Z_train_merged, y_train, np.array([0.0]))
w_ols = w_ols[0]
rmse_ols = float(np.sqrt(np.mean((Z_test_merged @ w_ols + b_ols - y_test) ** 2)))
test_rmses = np.array(
[np.sqrt(np.mean((Z_test_merged @ w + intercept - y_test) ** 2)) for w in W_path]
)
best_i = int(np.argmin(test_rmses))
best_lam = float(lambdas[best_i])
w_best = W_path[best_i]
j_sqft = MERGED_FEATURES.index("sqft")
j_sqm = MERGED_FEATURES.index("living_area_sqm")
i_10 = int(np.argmin(np.abs(lambdas - 10.0)))
w_10 = W_path[i_10]
print(
f"OLS (lam= 0.00): sqft={w_ols[j_sqft]:+.4f}, "
f"living_area_sqm={w_ols[j_sqm]:+.4f}, test RMSE={rmse_ols:.4f}"
)
print(
f"Ridge (lam={best_lam:5.2f}): sqft={w_best[j_sqft]:+.4f}, "
f"living_area_sqm={w_best[j_sqm]:+.4f}, test RMSE={test_rmses[best_i]:.4f}"
)
print(
f"Ridge (lam=10.00): sqft={w_10[j_sqft]:+.4f}, "
f"living_area_sqm={w_10[j_sqm]:+.4f}, test RMSE={test_rmses[i_10]:.4f}"
)
Output
verified SVD Ridge matches sklearn.linear_model.Ridge to 1e-6
OLS (lam= 0.00): sqft=+0.5103, living_area_sqm=-0.2278, test RMSE=0.2156
Ridge (lam= 0.01): sqft=+0.3976, living_area_sqm=-0.1151, test RMSE=0.2156
Ridge (lam=10.00): sqft=+0.1411, living_area_sqm=+0.1394, test RMSE=0.2157
linalg_auditor.py (part 5: scree plot and Ridge shrinkage path)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.0))
pcs = np.arange(1, len(var_ratio) + 1)
ax1.bar(pcs, var_ratio * 100, color="tab:blue", alpha=0.8, label="individual")
ax1.plot(
pcs, np.cumsum(var_ratio) * 100, "o-", color="tab:red", lw=2, label="cumulative"
)
ax1.axhline(90, linestyle="--", color="gray", lw=1)
ax1.set_xlabel("principal component")
ax1.set_ylabel("variance explained (%)")
ax1.set_title("SVD PCA scree & cumulative variance")
ax1.set_xticks(pcs)
ax1.legend(loc="center right")
highlight = ["sqft", "living_area_sqm", "distance_to_center_km", "condition", "age"]
for name in highlight:
j = MERGED_FEATURES.index(name)
ax2.plot(lambdas, W_path[:, j], lw=2, label=name)
ax2.set_xscale("log")
ax2.axvline(10.0, linestyle="--", color="gray", lw=1, label="lam = 10")
ax2.set_xlabel("Ridge penalty lambda (log scale)")
ax2.set_ylabel("standardized coefficient")
ax2.set_title("Ridge path stabilizes collinear size weights")
ax2.legend(fontsize=8, loc="upper right")
fig.tight_layout()
plt.show()
Two side-by-side panels: left shows PCA scree bars and a red cumulative variance curve reaching 89 percent by component 5 and crossing 90 percent by component 6; right shows Ridge standardized coefficients plotted against log lambda, with sqft and living_area_sqm quickly collapsing together near +0.14 by lambda=10 and then smoothly shrinking toward zero.
PCA scree curve on the 9 clean features (left) and Ridge regularization path on the 10-feature collinear design matrix (right).