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:
- 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.
- SVD-based PCA engine: fits principal components via
np.linalg.svd, reports explained variance ratios and Eckart–Young Frobenius reconstruction errors, and matchessklearn.decomposition.PCA. - SVD Ridge regression solver: uses one SVD to compute Ridge weights across an entire grid of penalties via singular-value shrinkage , verifies exact agreement with
sklearn.linear_model.Ridge, and shows how Ridge tames the collinear coefficients.
Dataset
Section titled “Dataset”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 |
Requirements
Section titled “Requirements”Your script must:
- Load
data/houses.csv, buildageandliving_area_sqm, and split rows 80/20 into training and test sets withnp.random.default_rng(42).permutation. - Fill missing values in
lot_sqftandschool_ratingusing training medians only, then standardize all features with training mean and standard deviation only. - 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 vianp.linalg.qr(). Run it on both the 9-feature clean set and the 10-feature merged set. - Implement
fit_pca_svd(Z)returning components, singular values, and explained variance ratios. Verify that explained variance ratios matchsklearn.decomposition.PCAto1e-10and that rank- reconstruction Frobenius error matches for . - Implement
ridge_path_svd(Z_train, y_train, lambdas)that computes a single reduced SVD ofZ_trainand evaluates Ridge weights and intercept across a log-spaced grid of values (np.logspace(-2, 4, 25)), centeringy_trainso the intercept is never penalized. - Verify your SVD Ridge weights match
sklearn.linear_model.Ridge(alpha=lam)on the 10-feature collinear matrix to1e-6for at least three values. - Compare OLS () vs. best- Ridge on the 10-feature set: print the fitted weights for
sqftandliving_area_sqmand both test RMSEs. - 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 on the 10 merged features.
Step plan
Section titled “Step plan”-
Load, engineer, and split. Read
data/houses.csv, createageandliving_area_sqm, permute indices with seed 42, and take an 80/20 split before computing any medians or scaling statistics. -
Impute and standardize cleanly. Fill
lot_sqftandschool_ratingNaNs with training medians. Standardize both the 9 clean features and the 10 merged features with training mean and std. -
Write the QR-based collinearity auditor. For each feature , take the remaining columns , factor , project , compute (since is already zero-mean), and compute .
-
Build and check SVD PCA. Run
np.linalg.svd(Z_clean, full_matrices=False). Compute explained variance ratioss**2 / np.sum(s**2)and verify rank- Frobenius errors against the Eckart–Young tail. -
Implement single-SVD Ridge. Compute
U, s, Vt = np.linalg.svd(Z_train, full_matrices=False)anduty = U.T @ (y_train - y_mean)once. For each , computew = Vt.T @ ((s / (s**2 + lam)) * uty)and interceptb = y_mean. -
Validate against scikit-learn. Assert
np.allcloseagainst bothPCAandRidgeat multiple values. -
Compare OLS vs. Ridge and plot. Inspect how OLS splits huge opposing weights between
sqftandliving_area_sqm, how Ridge stabilizes them, and draw the 2-panel diagnostic figure.
A starter skeleton:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.decomposition import PCAfrom 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 pathRubric
Section titled “Rubric”| 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 |
| Single-SVD Ridge path | 4 | Computes one SVD outside the 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 |
Stretch goals
Section titled “Stretch goals”- Add a helper
whiten_zca(Z)that transforms standardized features via and verifies the whitened covariance matrix equals the identity matrix . - Implement 5-fold cross-validation inside
ridge_path_svd(computing 5 SVDs total, one per fold) to pick without touching the test set. - Implement Principal Component Regression (PCR): keep the top singular components of
Z_trainand compare test RMSE of PCR vs. Ridge across . - Run
audit_collinearityondata/customers.csvnumeric columns and identify which billing feature should be dropped or regularized.
Reference solution
Section titled “Reference solution”Try building linalg_auditor.py yourself first, then compare your results and structure with the verified reference solution below.
Reference solution
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.decomposition import PCAfrom 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) / sigmaZ_test_merged = (X_test - mu) / sigmaZ_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)train: (2400, 10), test: (600, 10)missing left: 0def 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_000assert rep_merged["vifs"]["living_area_sqm"] > 10_000clean (9 cols): rank=9, cond=5.38, s_min=15.791merged (10 cols): rank=10, cond=639.01, s_min=0.1508top 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}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}")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.9650k=3: frob_err=79.8038 == Eckart-Young 79.8038k=5: frob_err=48.6889 == Eckart-Young 48.6889def 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 matrixw_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}")verified SVD Ridge matches sklearn.linear_model.Ridge to 1e-6OLS (lam= 0.00): sqft=+0.5103, living_area_sqm=-0.2278, test RMSE=0.2156Ridge (lam= 0.01): sqft=+0.3976, living_area_sqm=-0.1151, test RMSE=0.2156Ridge (lam=10.00): sqft=+0.1411, living_area_sqm=+0.1394, test RMSE=0.2157fig, (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()