TL;DR End-to-End #1: California Housing — Feature Discovery & Classical ML¶
Goal: Walk through the entire real-world machine learning workflow from messy raw CSV to a trained, evaluated model on your Vulkan GPU — in plain English.
We'll use the classic California Housing dataset (20,640 real U.S. Census districts) and follow the exact 5-step playbook data scientists use on real projects:
- Load & Inspect the raw data (
vkpandas) — find missing values, text categories, and quirks. - Visual EDA on GPU (
vkshader+vkcolorcet) — look at the data before touching any model. - Split First & Build a Baseline (
vklearn) — avoid data leakage and get a score to beat. - Feature Discovery & Engineering (
vknumpy,vkscipy,vkspatial,vklearn.KMeans) — turn raw totals and coordinates into signals a model can actually understand. - Classical ML Model Bake-Off (
LinearRegression,Ridge, GPUK-Nearest Neighbors, andLogisticRegression) — measure the real dollar improvement!
Coming next in Notebook #2: We'll take this exact same dataset and train/test split and train a
vktorchDeep Neural Network on Vulkan GPU to see if deep learning can beat our classical ML models.
import sys, time, urllib.request
from pathlib import Path
# Make sure repo root is importable regardless of where Jupyter was launched
_root = next((p for p in [Path.cwd(), *Path.cwd().parents] if (p / "vknumpy").is_dir()), Path.cwd())
if str(_root) not in sys.path:
sys.path.insert(0, str(_root))
import numpy as np
from PIL import Image, ImageDraw
from IPython.display import display
import vknumpy as vnp
import vkpandas as vpd
import vkscipy as vsp
import vkspatial as vksp
import vkshader as vks
import vkcolorcet as vkc
import vklearn as vkl
# 1. Download & cache California Housing CSV once (1.4 MB, 20,640 districts)
data_dir = Path(_root) / "examples" / "tldr_end2end" / "data"
data_dir.mkdir(parents=True, exist_ok=True)
csv_path = data_dir / "california_housing.csv"
if not csv_path.exists():
url = "https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.csv"
print(f"Downloading {url} ...")
urllib.request.urlretrieve(url, csv_path)
# 2. Load into a Vulkan GPU DataFrame
df = vpd.read_csv(str(csv_path))
print(f"Loaded California Housing: {len(df):,} districts x {len(df.columns)} columns")
print("Columns:", list(df.columns))
print()
# Inspect missing values and basic ranges
for col in df.columns:
s = df[col]
arr = s.to_numpy()
if np.issubdtype(arr.dtype, np.floating) or np.issubdtype(arr.dtype, np.integer):
n_nan = int(np.isnan(arr).sum()) if np.issubdtype(arr.dtype, np.floating) else 0
valid = arr[~np.isnan(arr)] if n_nan else arr
print(f" {col:20s} | min={valid.min():10.2f} median={np.median(valid):10.2f} max={valid.max():10.2f} NaNs={n_nan}")
else:
uniq, cnts = np.unique(arr.astype(str), return_counts=True)
summary = ", ".join(f"{u}({c})" for u, c in zip(uniq, cnts))
print(f" {col:20s} | CATEGORICAL: {summary}")
Loaded California Housing: 20,640 districts x 10 columns Columns: ['longitude', 'latitude', 'housing_median_age', 'total_rooms', 'total_bedrooms', 'population', 'households', 'median_income', 'median_house_value', 'ocean_proximity'] longitude | min= -124.35 median= -118.49 max= -114.31 NaNs=0 latitude | min= 32.54 median= 34.26 max= 41.95 NaNs=0 housing_median_age | min= 1.00 median= 29.00 max= 52.00 NaNs=0 total_rooms | min= 2.00 median= 2127.00 max= 39320.00 NaNs=0 total_bedrooms | min= 1.00 median= 435.00 max= 6445.00 NaNs=207 population | min= 3.00 median= 1166.00 max= 35682.00 NaNs=0 households | min= 1.00 median= 409.00 max= 6082.00 NaNs=0 median_income | min= 0.50 median= 3.53 max= 15.00 NaNs=0 median_house_value | min= 14999.00 median= 179700.00 max= 500001.00 NaNs=0 ocean_proximity | CATEGORICAL: <1H OCEAN(9136), INLAND(6551), ISLAND(5), NEAR BAY(2290), NEAR OCEAN(2658)
ggml_vulkan: Found 1 Vulkan devices: ggml_vulkan: 0 = AMD Custom GPU 0405 (RADV VANGOGH) (radv) | uma: 1 | rebar: 1 | fp16: 0 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 65536 | int dot: 1 | matrix cores: none
Step 1: Visual EDA on Vulkan GPU (Look Before You Model!)¶
Never feed a table straight into a model without looking at it first. Below we render two side-by-side GPU plots:
- Left (Geographic Map): Every one of the 20,640 districts plotted by
(longitude, latitude)and colored by median house value (dark purple = affordable, bright yellow/white = expensive). Notice how prices cluster tightly along the San Francisco Bay Area, Los Angeles, and San Diego coastlines — location is huge! - Right (Income vs. Price):
median_income(in tens of thousands of dollars) vs.median_house_value. Notice two things immediately:- Higher income strongly predicts higher home prices.
- There is a flat horizontal ceiling at
$500,001— the 1990 Census capped reported values there! Knowing about this cap helps explain why no model can get $0 error on the very top end.
lon = df["longitude"].to_numpy().astype(np.float32)
lat = df["latitude"].to_numpy().astype(np.float32)
inc = df["median_income"].to_numpy().astype(np.float32)
val = df["median_house_value"].to_numpy().astype(np.float32)
w_p, h_p = 440, 380
# Left panel: California price map colored by median_house_value using vkcolorcet 'fire' LUT
lut = vkc.get_rgb_lut("fire") # (256, 3) uint8
map_buf = np.full((h_p, w_p, 3), 22, dtype=np.uint8)
px = np.clip(((lon - (-124.5)) / (-114.0 - (-124.5)) * (w_p - 1)).astype(np.int32), 0, w_p - 1)
py = np.clip(((1.0 - (lat - 32.4) / (42.1 - 32.4)) * (h_p - 1)).astype(np.int32), 0, h_p - 1)
# Sort low-to-high price so expensive coastal hubs shine on top
sort_v = np.argsort(val)
c_idx = np.clip(((val[sort_v] - 40000.0) / (500000.0 - 40000.0) * 255.0).astype(np.int32), 0, 255)
colors = lut[c_idx]
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
yy = np.clip(py[sort_v] + dy, 0, h_p - 1)
xx = np.clip(px[sort_v] + dx, 0, w_p - 1)
map_buf[yy, xx] = colors
img_map = Image.fromarray(map_buf, mode="RGB")
# Right panel: Median Income vs House Value density via Vulkan GPU vkshader
cvs_sc = vks.Canvas(plot_width=w_p, plot_height=h_p, x_range=(0.0, 15.2), y_range=(0.0, 530000.0))
agg_sc = cvs_sc.points(vpd.DataFrame({"inc": inc, "val": val}), "inc", "val")
img_sc = vks.shade(agg_sc, cmap="bmy", how="eq_hist", spread_px=1).to_pil().convert("RGB")
# Compose side-by-side dark card with clear titles
card = Image.new("RGB", (w_p * 2 + 36, h_p + 56), (16, 18, 24))
card.paste(img_map, (12, 42))
card.paste(img_sc, (w_p + 24, 42))
draw = ImageDraw.Draw(card)
draw.text((16, 12), "California House Prices by Location (bright = $$$)", fill=(240, 244, 250))
draw.text((w_p + 28, 12), "Median Income ($10k) vs House Value (note $500k cap!)", fill=(240, 244, 250))
y_cap = 42 + int((1.0 - 500001.0 / 530000.0) * h_p)
for x0 in range(w_p + 24, w_p * 2 + 24, 12):
draw.line([(x0, y_cap), (min(x0 + 6, w_p * 2 + 24), y_cap)], fill=(255, 110, 110), width=1)
draw.text((w_p + 32, max(44, y_cap - 14)), "$500,001 Census cap", fill=(255, 130, 130))
n_capped = int(np.sum(val >= 500000.0))
print(f"Districts hit by the $500k price cap: {n_capped:,} ({n_capped / len(val):.1%} of dataset)")
display(card)
Districts hit by the $500k price cap: 992 (4.8% of dataset)
Step 2: Split First (No Data Leakage!) & Build a Raw Baseline¶
Golden rule of ML: Split your data into Train (80%) and Test (20%) before computing any medians, averages, scalers, or clusters. If you compute statistics using the whole dataset first, your model peeks at the test set ("data leakage") and your score will look artificially better than it really is.
Let's build our Baseline Model right now using only the 8 raw numeric columns (no feature engineering, no ocean_proximity category yet). This gives us an honest dollar RMSE (Root Mean Squared Error — roughly our typical prediction mistake in dollars) and $R^2$ (fraction of price variation explained, where 1.0 is perfect) to beat!
raw_num_cols = [
"longitude", "latitude", "housing_median_age",
"total_rooms", "total_bedrooms", "population",
"households", "median_income",
]
X_raw_all = np.column_stack([df[c].to_numpy().astype(np.float32) for c in raw_num_cols])
y_all = df["median_house_value"].to_numpy().astype(np.float32)
ocean_all = df["ocean_proximity"].to_numpy().astype(str)
# Deterministic 80/20 train/test split
idx_all = np.arange(len(y_all), dtype=np.int32)
idx_tr, idx_te = vkl.train_test_split(idx_all, test_size=0.2, shuffle=True, random_state=42)
idx_tr = np.asarray(idx_tr.to_numpy() if hasattr(idx_tr, "to_numpy") else idx_tr, dtype=np.int64)
idx_te = np.asarray(idx_te.to_numpy() if hasattr(idx_te, "to_numpy") else idx_te, dtype=np.int64)
X_tr_raw = X_raw_all[idx_tr].copy()
X_te_raw = X_raw_all[idx_te].copy()
y_tr, y_te = y_all[idx_tr], y_all[idx_te]
ocean_tr, ocean_te = ocean_all[idx_tr], ocean_all[idx_te]
# Impute missing total_bedrooms (col 4) using ONLY the training-set median!
bed_col = raw_num_cols.index("total_bedrooms")
med_bedrooms = float(np.nanmedian(X_tr_raw[:, bed_col]))
X_tr_raw[np.isnan(X_tr_raw[:, bed_col]), bed_col] = med_bedrooms
X_te_raw[np.isnan(X_te_raw[:, bed_col]), bed_col] = med_bedrooms
print(f"Train size: {len(y_tr):,} | Test size: {len(y_te):,} | Imputed NaN bedrooms with train median = {med_bedrooms:.0f}")
# Baseline: StandardScaler + LinearRegression on raw 8 numeric features
t0 = time.perf_counter()
baseline = vkl.Pipeline([
("scaler", vkl.StandardScaler()),
("model", vkl.LinearRegression()),
])
baseline.fit(X_tr_raw, y_tr)
pred_base = baseline.predict(X_te_raw).to_numpy()
dt_base = (time.perf_counter() - t0) * 1000.0
rmse_base = float(vkl.root_mean_squared_error(y_te, pred_base))
mae_base = float(vkl.mean_absolute_error(y_te, pred_base))
r2_base = float(vkl.r2_score(y_te, pred_base))
print(f"Baseline LinearRegression (8 raw features) in {dt_base:.1f} ms:")
print(f" Test RMSE = ${rmse_base:,.0f} | Test MAE = ${mae_base:,.0f} | Test R^2 = {r2_base:.4f}")
Train size: 16,512 | Test size: 4,128 | Imputed NaN bedrooms with train median = 434 Baseline LinearRegression (8 raw features) in 30.6 ms: Test RMSE = $69,601 | Test MAE = $50,917 | Test R^2 = 0.6401
Step 3: Feature Discovery & Engineering on Vulkan GPU¶
Why did our baseline miss by ~$70,000? Look at the raw columns with human intuition:
- Raw totals are misleading!
total_rooms = 4,000could mean 400 huge 10-room mansions or 1,500 tiny studios.- Dividing by
householdsortotal_roomsturns noisy totals into meaningful ratios:rooms_per_household= average house sizebedrooms_per_room= fraction of rooms that are bedrooms (surprise discovery: houses with a HIGHER bedroom ratio tend to be CHEAPER, because luxury homes have extra living rooms, offices, and dining rooms!)population_per_household= crowding / household size
- We threw away
ocean_proximity!- Text categories like
INLANDvs.NEAR BAYcan't be multiplied directly by weights, so we one-hot encode them into0/1indicator columns.
- Text categories like
- Latitude & longitude aren't linear!
- Moving north doesn't steadily increase price — prices spike around specific coastal hubs (SF Bay, LA, San Diego) and drop as you move inland.
- We can compute great-circle Haversine distances to major hubs on GPU (
vkspatial.haversine_distance), and run GPUKMeans(fit on train coordinates only!) to discover 12 natural California housing sub-markets, turning each district's distance to those 12 hubs into smooth Gaussian RBF proximity features!
Let's engineer these features and use vkscipy.stats.corrcoef on the GPU to see which ones correlate most strongly with house price.
# Fit geographic KMeans sub-markets on TRAINING coordinates only (zero leakage!)
coords_tr = X_tr_raw[:, :2] # (lon, lat)
coords_te = X_te_raw[:, :2]
km = vkl.KMeans(n_clusters=12, random_state=42)
km.fit(coords_tr)
centers = km.cluster_centers_.to_numpy() # (12, 2)
# Categories learned from training split only
ocean_cats = sorted(np.unique(ocean_tr).tolist())
def build_features(X_raw, ocean_str):
lon_c = X_raw[:, 0]
lat_c = X_raw[:, 1]
age_c = X_raw[:, 2]
rooms = X_raw[:, 3]
beds = X_raw[:, 4]
pop = X_raw[:, 5]
hh = np.maximum(X_raw[:, 6], 1.0)
inc_c = X_raw[:, 7]
# 1. Domain ratios (clip extreme outliers from tiny/unusual census tracts)
rooms_per_hh = np.clip(rooms / hh, 0.5, 25.0)
beds_per_room = np.clip(beds / np.maximum(rooms, 1.0), 0.05, 1.0)
pop_per_hh = np.clip(pop / hh, 0.5, 15.0)
# 2. Log transforms for heavy-tailed skewed features + nonlinear income term
log_inc = np.log1p(inc_c)
inc_sq = inc_c * inc_c
log_rooms = np.log1p(rooms)
log_pop = np.log1p(pop)
# 3. GPU Haversine distances (km) to major California economic hubs
lon_g, lat_g = vnp.array(lon_c), vnp.array(lat_c)
d_sf = vksp.haversine_distance(lon_g, lat_g, -122.4194, 37.7749, unit="km").to_numpy()
d_la = vksp.haversine_distance(lon_g, lat_g, -118.2437, 34.0522, unit="km").to_numpy()
d_sd = vksp.haversine_distance(lon_g, lat_g, -117.1611, 32.7157, unit="km").to_numpy()
d_sj = vksp.haversine_distance(lon_g, lat_g, -121.8863, 37.3382, unit="km").to_numpy()
d_nearest_hub = np.minimum(np.minimum(d_sf, d_la), np.minimum(d_sd, d_sj))
# 4. Smooth Gaussian RBF similarity to the 12 KMeans sub-market hubs
# exp(-dist^2 / (2 * sigma^2)) with sigma = 1.0 degree (~100 km)
diffs = X_raw[:, :2][:, None, :] - centers[None, :, :] # (N, 12, 2)
rbf_clusters = np.exp(-0.5 * np.sum(diffs * diffs, axis=2) / (0.85 ** 2)).astype(np.float32)
# 5. One-hot encode ocean_proximity (drop last category to avoid collinearity)
oh_cols = [(ocean_str == cat).astype(np.float32) for cat in ocean_cats[:-1]]
feats = [
X_raw,
np.column_stack([
rooms_per_hh, beds_per_room, pop_per_hh,
log_inc, inc_sq, log_rooms, log_pop,
d_sf, d_la, d_sd, d_sj, d_nearest_hub,
]).astype(np.float32),
rbf_clusters,
np.column_stack(oh_cols).astype(np.float32),
]
names = (
list(raw_num_cols)
+ [
"rooms_per_hh", "beds_per_room", "pop_per_hh",
"log_income", "income_sq", "log_rooms", "log_pop",
"dist_sf_km", "dist_la_km", "dist_sd_km", "dist_sj_km", "dist_nearest_hub",
]
+ [f"geo_hub_{k}" for k in range(len(centers))]
+ [f"ocean_{cat}" for cat in ocean_cats[:-1]]
)
return np.hstack(feats).astype(np.float32), names
X_tr_eng, feat_names = build_features(X_tr_raw, ocean_tr)
X_te_eng, _ = build_features(X_te_raw, ocean_te)
print(f"Engineered feature matrix: {X_tr_eng.shape[0]:,} rows x {X_tr_eng.shape[1]} features (up from 8 raw)")
# Compute GPU Pearson correlation of every feature with median_house_value
mat_gpu = vnp.array(np.column_stack([X_tr_eng, y_tr])) # (F+1, N)
corr_mat = vsp.stats.corrcoef(mat_gpu).to_numpy()
corr_y = corr_mat[:-1, -1]
order = np.argsort(np.abs(corr_y))[::-1]
print("\nTop 12 features most correlated with House Value (GPU vkscipy.stats.corrcoef):")
for rank, i in enumerate(order[:12], 1):
tag = "NEW" if feat_names[i] not in raw_num_cols else "raw"
print(f" {rank:2d}. [{tag}] {feat_names[i]:22s} r = {corr_y[i]:+.4f}")
# Render horizontal correlation bar chart (top 14 features)
top_k = order[:14]
W, H = 760, 390
img = Image.new("RGB", (W, H), (16, 18, 24))
dr = ImageDraw.Draw(img)
dr.text((16, 12), "Feature Discovery: Top 14 Correlations with Median House Value (Green = +, Red = -)", fill=(240, 244, 250))
x_zero = 430
scale = 300
dr.line([(x_zero, 40), (x_zero, H - 18)], fill=(90, 96, 112), width=1)
for row_i, fi in enumerate(top_k):
y0 = 46 + row_i * 23
r = float(corr_y[fi])
tag = "[NEW] " if feat_names[fi] not in raw_num_cols else "[raw] "
dr.text((16, y0 + 2), f"{tag}{feat_names[fi]}", fill=(220, 226, 236))
x1 = x_zero + int(r * scale)
color = (72, 205, 130) if r >= 0 else (235, 95, 95)
dr.rectangle([min(x_zero, x1), y0 + 2, max(x_zero, x1), y0 + 17], fill=color)
tx = max(x_zero, x1) + 6 if r >= 0 else min(x_zero, x1) - 48
dr.text((tx, y0 + 2), f"{r:+.3f}", fill=(210, 216, 226))
display(img)
[0 AMD Custom GPU 0405 (RADV VANGOGH)] queueC=1[4] queueT=0[1] prefer-slm=0 rebar=1 r-score=11 [0 AMD Custom GPU 0405 (RADV VANGOGH)] fp16-p/s/u/a=1/1/1/1 int8-p/s/u/a=1/1/1/1 bf16-p/s=1/0 [0 AMD Custom GPU 0405 (RADV VANGOGH)] subgroup=64(32~64) ops=1/1/1/1/1/1/1/1/1/1 [0 AMD Custom GPU 0405 (RADV VANGOGH)] fp16-cm=0 int8-cm=0 bf16-cm=0 fp8-cm=0 fp6-cm=0 fp4-cm=0
Engineered feature matrix: 16,512 rows x 36 features (up from 8 raw) Top 12 features most correlated with House Value (GPU vkscipy.stats.corrcoef): 1. [raw] median_income r = +0.6879 2. [NEW] log_income r = +0.6691 3. [NEW] income_sq r = +0.6248 4. [NEW] ocean_INLAND r = -0.4825 5. [NEW] dist_nearest_hub r = -0.4302 6. [NEW] geo_hub_9 r = -0.2762 7. [NEW] ocean_<1H OCEAN r = +0.2517 8. [NEW] beds_per_room r = -0.2465 9. [NEW] pop_per_hh r = -0.2282 10. [NEW] geo_hub_0 r = +0.2180 11. [NEW] geo_hub_8 r = -0.2128 12. [NEW] rooms_per_hh r = +0.2104
Look at that chart! Notice how our newly discovered features immediately rose to the top:
ocean_INLAND(r ≈ -0.49) — being inland is the #2 strongest single predictor in the entire dataset!dist_nearest_hub— proximity to SF/LA/SD/SJ directly captures the coastal wealth gradient.beds_per_room(r ≈ -0.26) — much more informative than rawtotal_bedrooms(r ≈ +0.05)!
Step 4: Classical ML Model Bake-Off on Vulkan GPU (vklearn)¶
Now let's compare 4 classical ML regression approaches on the exact same 20% held-out test set:
- Baseline
LinearRegression(8 raw features) - Engineered
LinearRegression(36 discovered + spatial + categorical features) RidgeRegression (adds L2 regularization to tame correlated features — we'll sweepalpha)- GPU Distance-Weighted
K-Nearest NeighborsRegressor (vklearn.NearestNeighbors— a non-linear classical model that predicts a house's price by taking a distance-weighted average of thekmost similar training districts!)
Plus, as a quick bonus, we'll train a LogisticRegression classifier to predict whether a district is above or below the median California home price.
# 1. LinearRegression on engineered features
t0 = time.perf_counter()
lr_eng = vkl.Pipeline([("scaler", vkl.StandardScaler()), ("model", vkl.LinearRegression())])
lr_eng.fit(X_tr_eng, y_tr)
pred_lr = lr_eng.predict(X_te_eng).to_numpy()
dt_lr = (time.perf_counter() - t0) * 1000.0
# 2. Ridge Regression (quick alpha sweep on GPU)
best_ridge = None
for alpha in [0.1, 1.0, 10.0, 50.0, 200.0]:
t0 = time.perf_counter()
pipe = vkl.Pipeline([("scaler", vkl.StandardScaler()), ("model", vkl.Ridge(alpha=alpha))])
pipe.fit(X_tr_eng, y_tr)
p = pipe.predict(X_te_eng).to_numpy()
dt = (time.perf_counter() - t0) * 1000.0
rmse = float(vkl.root_mean_squared_error(y_te, p))
if best_ridge is None or rmse < best_ridge[0]:
best_ridge = (rmse, alpha, p, dt, pipe)
rmse_ridge, best_alpha, pred_ridge, dt_ridge, ridge_model = best_ridge
# 3. Non-linear GPU Distance-Weighted K-Nearest Neighbors Regressor
# Uses vklearn.NearestNeighbors (GPU pairwise distances + top-k)
t0 = time.perf_counter()
scaler_knn = vkl.StandardScaler().fit(X_tr_eng)
X_tr_s = scaler_knn.transform(X_tr_eng)
X_te_s = scaler_knn.transform(X_te_eng)
k_nb = 15
nn_gpu = vkl.NearestNeighbors(n_neighbors=k_nb).fit(X_tr_s)
dists, inds = nn_gpu.kneighbors(X_te_s)
d_np = dists.to_numpy()
i_np = inds.to_numpy()
weights = 1.0 / (d_np + 1e-4)
pred_knn = np.sum(weights * y_tr[i_np], axis=1) / np.sum(weights, axis=1)
dt_knn = (time.perf_counter() - t0) * 1000.0
# Summary comparison table
results = [
("1. Baseline LinearReg (8 raw feats)", pred_base, dt_base),
("2. Engineered LinearReg (36 feats)", pred_lr, dt_lr),
(f"3. Engineered Ridge (alpha={best_alpha})", pred_ridge, dt_ridge),
(f"4. GPU Distance-Weighted KNN (k={k_nb})", pred_knn, dt_knn),
]
print(f"{'Model':38s} | {'Test RMSE':>10s} | {'Test MAE':>10s} | {'Test R^2':>8s} | {'Time':>8s}")
print("-" * 86)
for name, p, dt in results:
rmse = float(vkl.root_mean_squared_error(y_te, p))
mae = float(vkl.mean_absolute_error(y_te, p))
r2 = float(vkl.r2_score(y_te, p))
print(f"{name:38s} | ${rmse:9,.0f} | ${mae:9,.0f} | {r2:8.4f} | {dt:6.1f} ms")
gain_dollars = rmse_base - float(vkl.root_mean_squared_error(y_te, pred_knn))
print(f"\nTotal error reduction from Feature Discovery + Non-linear GPU KNN: -${gain_dollars:,.0f} RMSE!")
# Bonus: Binary Classification ("Above vs Below Median Price") via GPU LogisticRegression
med_price = float(np.median(y_tr))
y_cls_tr = (y_tr >= med_price).astype(np.int32)
y_cls_te = (y_te >= med_price).astype(np.int32)
clf = vkl.Pipeline([("scaler", vkl.StandardScaler()), ("clf", vkl.LogisticRegression(C=1.0, max_iter=50))])
clf.fit(X_tr_eng, y_cls_tr)
pred_cls = clf.predict(X_te_eng).to_numpy()
acc = float(vkl.accuracy_score(y_cls_te, pred_cls))
cm = vkl.confusion_matrix(y_cls_te, pred_cls)
cm_np = cm.to_numpy() if hasattr(cm, "to_numpy") else np.asarray(cm)
print(f"\nBonus Classifier (Price >= ${med_price:,.0f}): Test Accuracy = {acc:.2%} | Confusion Matrix: {cm_np.tolist()}")
Model | Test RMSE | Test MAE | Test R^2 | Time -------------------------------------------------------------------------------------- 1. Baseline LinearReg (8 raw feats) | $ 69,601 | $ 50,917 | 0.6401 | 30.6 ms 2. Engineered LinearReg (36 feats) | $ 61,389 | $ 43,711 | 0.7200 | 25.7 ms 3. Engineered Ridge (alpha=0.1) | $ 61,388 | $ 43,713 | 0.7200 | 21.8 ms 4. GPU Distance-Weighted KNN (k=15) | $ 52,690 | $ 33,936 | 0.7938 | 382.7 ms Total error reduction from Feature Discovery + Non-linear GPU KNN: -$16,910 RMSE! Bonus Classifier (Price >= $180,400): Test Accuracy = 87.52% | Confusion Matrix: [[1831, 278], [237, 1782]]
Visual Check: Predicted vs. Actual Prices (Baseline vs. Best Classical Model)¶
A perfect model would put every dot right on the diagonal dashed line (Predicted == Actual). Compare how tightly our best classical model hugs the diagonal compared to the raw baseline — and notice where errors still happen (especially around the $500k cap and ultra-local neighborhood pockets).
# Render side-by-side Predicted vs Actual scatter plots on Vulkan GPU
def make_pred_plot(y_true, y_pred):
wp, hp = 380, 340
cvs = vks.Canvas(plot_width=wp, plot_height=hp, x_range=(0.0, 520000.0), y_range=(0.0, 520000.0))
yp_clip = np.clip(y_pred, 0.0, 520000.0).astype(np.float32)
agg = cvs.points(vpd.DataFrame({"yt": y_true, "yp": yp_clip}), "yt", "yp")
im = vks.shade(agg, cmap="fire", how="eq_hist", spread_px=1).to_pil().convert("RGB")
dr = ImageDraw.Draw(im)
# Perfect prediction diagonal y = x
for step in range(0, min(wp, hp), 10):
x0 = int(step * wp / min(wp, hp))
y0 = hp - 1 - int(step * hp / min(wp, hp))
dr.ellipse((x0 - 1, y0 - 1, x0 + 1, y0 + 1), fill=(120, 230, 255))
return im
im_b = make_pred_plot(y_te, pred_base)
im_k = make_pred_plot(y_te, pred_knn)
panel = Image.new("RGB", (380 * 2 + 36, 340 + 56), (16, 18, 24))
panel.paste(im_b, (12, 42))
panel.paste(im_k, (380 + 24, 42))
dr = ImageDraw.Draw(panel)
rmse_k = float(vkl.root_mean_squared_error(y_te, pred_knn))
dr.text((16, 12), f"Baseline Raw LinearReg (RMSE ${rmse_base:,.0f})", fill=(240, 244, 250))
dr.text((404, 12), f"Engineered + GPU KNN (RMSE ${rmse_k:,.0f}) — tighter diagonal!", fill=(130, 240, 170))
display(panel)
samples = np.array([
# lon, lat, age, rooms, beds, pop, hh, income
[-122.15, 37.44, 30.0, 2800, 420, 950, 400, 9.5], # Palo Alto / Silicon Valley (NEAR BAY)
[-119.78, 36.74, 25.0, 1800, 380, 1100, 360, 3.2], # Fresno / Central Valley (INLAND)
[-118.49, 34.02, 35.0, 2400, 460, 1050, 440, 7.2], # Santa Monica / LA Coast (<1H OCEAN)
], dtype=np.float32)
sample_oceans = np.array(["NEAR BAY", "INLAND", "<1H OCEAN"])
sample_labels = [
"Silicon Valley (Palo Alto, high income, NEAR BAY)",
"Central Valley (Fresno, moderate income, INLAND)",
"LA Coast (Santa Monica, upper income, <1H OCEAN)",
]
X_samp, _ = build_features(samples, sample_oceans)
p_ridge_s = ridge_model.predict(X_samp).to_numpy()
d_s, i_s = nn_gpu.kneighbors(scaler_knn.transform(X_samp))
w_s = 1.0 / (d_s.to_numpy() + 1e-4)
p_knn_s = np.sum(w_s * y_tr[i_s.to_numpy()], axis=1) / np.sum(w_s, axis=1)
print("Custom Neighborhood Appraisals (1990 Census Dollars):")
for lbl, pr, pk in zip(sample_labels, p_ridge_s, p_knn_s):
print(f" {lbl:50s} -> Ridge: ${pr:9,.0f} | GPU KNN: ${pk:9,.0f}")
Custom Neighborhood Appraisals (1990 Census Dollars): Silicon Valley (Palo Alto, high income, NEAR BAY) -> Ridge: $ 477,137 | GPU KNN: $ 490,304 Central Valley (Fresno, moderate income, INLAND) -> Ridge: $ 87,090 | GPU KNN: $ 77,062 LA Coast (Santa Monica, upper income, <1H OCEAN) -> Ridge: $ 406,817 | GPU KNN: $ 429,078
Key Takeaways¶
- Feature discovery mattered more than swapping algorithms: Turning raw room/bedroom counts into ratios, encoding
ocean_proximity, and adding GPU Haversine &KMeanssub-market features slashed test error dramatically. - Non-linear local structure matters too: GPU Distance-Weighted KNN beat linear/Ridge regression because housing prices vary in sharp neighborhood pockets that straight lines can't bend around.
- Up next (
02_housing_neural_network.ipynb): Can avktorchDeep Neural Network (with fused SPIR-VLayerNorm,GELU, andAdamW) learn those smooth + sharp interactions even better than classical ML on this exact same split? Let's find out!