Skip to content

32. Math for ML — Mini-project

A small real estate agency wants a price model it can explain to its clients. The data team must not use a black box, and the lead engineer wants proof that the training code is correct before anyone trusts its numbers.

Build the model from scratch with NumPy: linear regression on the log of the price, trained with gradient descent. Prove it right in three ways: a gradient check, a loss curve, and agreement with the closed-form least-squares solution to a stated tolerance. Then evaluate it on houses the model has never seen, and explain the three most important features in plain words.

The project uses every part of module 32: feature vectors, the data matrix, standardization, matrix–vector products, the transpose, lstsq, the MSE gradient, gradient checking, gradient descent, mini-batches and learning-rate choice.

data/houses.csv: 3,000 house sales from 2022 to 2024, described in the data dictionary. Use these columns:

Feature Notes
sqft, bedrooms, bathrooms size; strongly correlated with each other
age sale year minus year_built; build it from sold_date and year_built
condition 1 (poor) to 5 (excellent)
distance_to_center_km 0.2 to 20.2
has_pool, garage_spaces 0/1 and 0 to 3
school_rating 1 to 10, with 90 blanks: fill them with the training median
target: log_price the natural log of price

Why the log of the price? House prices are right-skewed, and a common modeling assumption is that effects are multiplicative: a pool would add a percentage, not a fixed amount. On the log scale, such effects become additive, which suits a linear model. A weight ww then means “the price changes by a factor ewe^w”, or about 100⋅w100 \cdot w percent for small ww.

Your script must:

  1. Build the feature matrix and the log_price target. Fill the missing school ratings with the median of the training rows.
  2. Split the rows 80/20 into training and test sets with np.random.default_rng(42).permutation.
  3. Standardize the features with the training mean and standard deviation only, and add a column of ones.
  4. Write mse_loss(w, A, y) and mse_grad(w, A, y), and pass a gradient check: relative error below 1e-7 at a random weight vector.
  5. Train batch gradient descent with at least three learning rates, plot their loss curves in one figure, and choose one with a one-sentence reason.
  6. Train with the chosen rate until the gradient norm is below 1e-8, and show with np.allclose(..., rtol=0, atol=1e-6) that the weights match np.linalg.lstsq on the training set.
  7. Train a mini-batch version (batch size 32) for 20 epochs and compare its test RMSE with the batch model.
  8. Report on the test set: RMSE on the log scale, R² on the log scale, and the median absolute percentage error of the price in USD.
  9. Print the three features with the largest absolute weights and their effect in percent per standard deviation, 100(ew−1)100(e^w - 1).
  1. Load and build the features. Read the CSV with pandas. Compute age from the year of sold_date and year_built. Build X as a float array and y = np.log(price).

  2. Split. Permute the row positions with a seeded generator, take the first 80% for training. Fill the missing school_rating values with the training median, in both sets.

  3. Standardize and add the intercept column. Compute mu and sigma on the training rows. Apply them to both sets. Write a small helper design(X) so that both sets go through the same code.

  4. Check the gradient. Write the loss and the gradient as in the lesson’s Example 4. Compare with central differences at a random w.

  5. Pick the learning rate. Train for 100 iterations with three or four rates, draw the loss curves on a log scale and pick the fastest stable one.

  6. Converge and compare. Train until the gradient norm is tiny. Compare with lstsq. Print the largest weight difference.

  7. Try mini-batches. Reuse the gradient on random batches of 32 rows. Shuffle every epoch.

  8. Evaluate on the test set. Predict, compute the metrics, and turn log predictions back into prices with np.exp.

  9. Explain. Sort the weights by absolute size and translate the top three into percentages.

A skeleton to start from:

price_model.py (starter)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
FEATURES = ["sqft", "bedrooms", "bathrooms", "age", "condition",
"distance_to_center_km", "has_pool", "garage_spaces", "school_rating"]
# --- Load and split ---
# TODO: houses, age, X, y = log(price), train/test positions, fill school_rating
# --- Design matrices ---
# TODO: mu, sigma from the training rows; design(X) -> ones + standardized columns
# --- Loss, gradient, gradient check ---
# TODO: mse_loss, mse_grad, numerical_grad, relative error < 1e-7
# --- Learning rates and loss curves ---
# TODO: train for 100 iterations with several rates, plot, choose
# --- Converge and compare with lstsq ---
# TODO: stop when the gradient norm < 1e-8; np.allclose with atol=1e-6
# --- Mini-batch, evaluation, explanation ---
# TODO: mini-batch training, test metrics, top three features
Criterion Points Full points when
Data preparation 2 age and log_price are correct; missing ratings use the training median
No leakage 2 The split comes first; median, mean and standard deviation come from the training rows only
Vectorized math 2 Loss, gradient and predictions use @ and .T, with no Python loop over rows
Gradient check 2 A numerical gradient with central differences; relative error below 1e-7
Learning-rate choice 2 A loss-curve figure with at least three rates and a stated reason for the choice
Agreement with lstsq 3 A stopping rule on the gradient norm and an np.allclose check with atol=1e-6
Mini-batch 2 Shuffled each epoch; test RMSE compared with the batch model
Evaluation 2 Test RMSE, R² and median absolute percentage error, computed on the test set only
Explanation 2 Top three features in percent per standard deviation, in plain words
Code quality 1 Clear names, small functions, type hints, comments that say why
Total 20 16 or more: you are ready for module 33
  1. Add the neighborhood as 0/1 columns (pd.get_dummies(houses["neighborhood"], drop_first=True, dtype=float)) and measure how much the test RMSE improves. Module 33 explains one-hot encoding.
  2. Add a Ridge penalty to the gradient (exercise M32-X04) and plot the test RMSE against λ\lambda on a log grid.
  3. Replace the fixed learning rate of the mini-batch version with a schedule, for example ηt=η0/(1+t/100)\eta_t = \eta_0 / (1 + t/100), and compare the final distance to the lstsq weights.
  4. Hold out 20% of the training rows as a validation set and stop the mini-batch training when the validation loss has not improved for 3 epochs (early stopping).
  5. Wrap the model in a class with fit, predict and learned attributes ending in _, as in exercise M32-X02.

Try the project yourself first. Then compare your script with this one. Your names and the exact choices can differ; your numbers should be close.

Reference solution
price_model.py (part 1: data)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.set_printoptions(precision=4, suppress=True)
FEATURES = ["sqft", "bedrooms", "bathrooms", "age", "condition",
"distance_to_center_km", "has_pool", "garage_spaces", "school_rating"]
houses = pd.read_csv("data/houses.csv")
sale_year = pd.to_datetime(houses["sold_date"]).dt.year
houses["age"] = sale_year - houses["year_built"]
X = houses[FEATURES].to_numpy(dtype=float)
y = np.log(houses["price"].to_numpy(dtype=float))
order = np.random.default_rng(42).permutation(len(y))
n_train = int(0.8 * len(y))
train, test = order[:n_train], order[n_train:]
rating = FEATURES.index("school_rating")
median_rating = np.nanmedian(X[train, rating])
X[:, rating] = np.where(np.isnan(X[:, rating]), median_rating, X[:, rating])
print(f"train {len(train)}, test {len(test)}, median school rating {median_rating}")
print(f"missing values left: {np.isnan(X).sum()}")
Output
train 2400, test 600, median school rating 6.0
missing values left: 0
price_model.py (part 2: design matrices and gradient check)
mu, sigma = X[train].mean(axis=0), X[train].std(axis=0)
def design(rows: np.ndarray) -> np.ndarray:
"""Ones column + features standardized with the training statistics."""
return np.column_stack([np.ones(len(rows)), (X[rows] - mu) / sigma])
A_train, A_test = design(train), design(test)
y_train, y_test = y[train], y[test]
def mse_loss(w: np.ndarray, A: np.ndarray, y: np.ndarray) -> float:
return float(np.mean((A @ w - y) ** 2))
def mse_grad(w: np.ndarray, A: np.ndarray, y: np.ndarray) -> np.ndarray:
return 2 / len(y) * A.T @ (A @ w - y)
def numerical_grad(w: np.ndarray, A: np.ndarray, y: np.ndarray,
h: float = 1e-5) -> np.ndarray:
grad = np.zeros_like(w)
for j in range(len(w)):
step = np.zeros_like(w)
step[j] = h
grad[j] = (mse_loss(w + step, A, y) - mse_loss(w - step, A, y)) / (2 * h)
return grad
w_random = np.random.default_rng(7).normal(size=A_train.shape[1])
g_a = mse_grad(w_random, A_train, y_train)
g_n = numerical_grad(w_random, A_train, y_train)
rel_error = np.linalg.norm(g_a - g_n) / np.linalg.norm(g_a + g_n)
print(A_train.shape, A_test.shape)
print("gradient check passed:", rel_error < 1e-7)
assert rel_error < 1e-7
Output
(2400, 10) (600, 10)
gradient check passed: True
price_model.py (part 3: learning rates)
def train_gd(A: np.ndarray, y: np.ndarray, lr: float, n_iter: int):
w = np.zeros(A.shape[1])
history = []
for _ in range(n_iter):
history.append(mse_loss(w, A, y))
w = w - lr * mse_grad(w, A, y)
return w, np.array(history)
fig, ax = plt.subplots(figsize=(6.5, 4))
for lr in [0.01, 0.1, 0.3, 0.35]:
_, hist = train_gd(A_train, y_train, lr, 100)
ax.plot(hist, label=f"lr = {lr}")
print(f"lr = {lr}: loss after 100 iterations {hist[-1]:.4f}")
ax.set_yscale("log")
ax.set_ylim(0.03, 300)
ax.set_xlabel("iteration")
ax.set_ylabel("training MSE (log price)")
ax.legend()
plt.show()
Output
lr = 0.01: loss after 100 iterations 3.1082
lr = 0.1: loss after 100 iterations 0.0432
lr = 0.3: loss after 100 iterations 0.0432
lr = 0.35: loss after 100 iterations 2733905509.5457
Training loss curves on a log scale for four learning rates over 100 iterations. 0.01 falls slowly and stays above 1, 0.1 and 0.3 fall quickly to about 0.04, and 0.35 dips at first, then rises out of the top of the chart.
Loss curves of the reference solution. 0.3 is the fastest stable rate.
price_model.py (part 4: converge and compare)
def fit_until_flat(A: np.ndarray, y: np.ndarray, lr: float,
tol: float = 1e-8, max_iter: int = 20_000) -> tuple[np.ndarray, int]:
w = np.zeros(A.shape[1])
for iteration in range(max_iter):
grad = mse_grad(w, A, y)
if np.linalg.norm(grad) < tol:
return w, iteration
w = w - lr * grad
return w, max_iter
w_gd, iterations = fit_until_flat(A_train, y_train, lr=0.3)
w_ls, *_ = np.linalg.lstsq(A_train, y_train)
print(f"converged after {iterations} iterations")
print(f"largest difference from lstsq: {np.max(np.abs(w_gd - w_ls)):.1e}")
assert np.allclose(w_gd, w_ls, rtol=0, atol=1e-6)
Output
converged after 218 iterations
largest difference from lstsq: 3.5e-08
price_model.py (part 5: mini-batch)
rng = np.random.default_rng(42)
w_mb = np.zeros(A_train.shape[1])
for _ in range(20):
for batch in np.array_split(rng.permutation(len(y_train)), len(y_train) // 32):
w_mb = w_mb - 0.02 * mse_grad(w_mb, A_train[batch], y_train[batch])
def rmse(w: np.ndarray) -> float:
return float(np.sqrt(mse_loss(w, A_test, y_test)))
print(f"test RMSE (log), batch: {rmse(w_gd):.4f}")
print(f"test RMSE (log), mini-batch: {rmse(w_mb):.4f}")
Output
test RMSE (log), batch: 0.2119
test RMSE (log), mini-batch: 0.2118
price_model.py (part 6: evaluation and explanation)
pred_log = A_test @ w_gd
r2 = 1 - np.sum((y_test - pred_log) ** 2) / np.sum((y_test - y_test.mean()) ** 2)
price_true, price_pred = np.exp(y_test), np.exp(pred_log)
mdape = np.median(np.abs(price_pred - price_true) / price_true)
print(f"test RMSE (log) {rmse(w_gd):.3f}, R² (log) {r2:.3f}")
print(f"median absolute percentage error: {mdape:.1%}")
effects = 100 * (np.exp(w_gd[1:]) - 1)
for j in np.argsort(-np.abs(w_gd[1:]))[:3]:
print(f"{FEATURES[j]:22} weight {w_gd[1 + j]:+.3f} -> {effects[j]:+.1f}% per std "
f"({sigma[j]:.2f} units)")
Output
test RMSE (log) 0.212, R² (log) 0.842
median absolute percentage error: 13.0%
sqft weight +0.278 -> +32.0% per std (709.13 units)
school_rating weight +0.179 -> +19.6% per std (1.92 units)
distance_to_center_km weight -0.169 -> -15.5% per std (5.18 units)

Run it from the project folder:

Terminal
python price_model.py

How it works:

  1. Data. age is computed from the sale year, so a house sold in 2024 is one year older than the same house sold in 2023. The log turns the skewed price into a target with roughly symmetric errors.
  2. No leakage. The split comes first. The median rating, the means and the standard deviations come from the training rows and are applied to both sets through one design helper.
  3. Gradient check. The relative error is far below 1e-7, so the vectorized gradient is right before any training starts.
  4. Learning rate. 0.35 diverges, 0.01 is slow, and 0.1 and 0.3 both reach the minimum. 0.3 is the fastest stable choice, just below the stability limit of about 0.33. Correlated features (the size trio) make the loss surface narrower in one direction, which lowers that limit. If a rate this close to the limit makes you nervous, 0.2 is a safe choice that costs a few more iterations.
  5. Agreement. The stopping rule on the gradient norm ends training at a flat spot. The weights agree with lstsq within 1e-6, which proves that the loop minimizes the right loss.
  6. Mini-batch. After 20 epochs, the mini-batch weights give the same test RMSE as the exact solution to 3 decimals. The tiny difference in the 4th decimal is noise, not a better model.
  7. Explanation. On the log scale, 100(ew−1)100(e^w - 1) is the percentage change of the price for one standard deviation more of a feature, with the others fixed. Size moves the price most (+32% per 709 sqft), then the school rating (+20% per 1.9 points) and the distance to the center (−15% per 5.2 km). The median error of 13% leaves room for the neighborhood (stretch goal 1).

Alternative: make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LinearRegression()) fitted on the training rows gives the same weights in a few lines (module 34). Writing it by hand once makes every part of that pipeline concrete.