Skip to content

32. Math for ML — Exercises

These exercises practice every idea of the Math for ML lesson. They use the course datasets data/houses.csv, data/customers.csv, data/reviews.csv and data/ab_test.csv (see the data dictionary).

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script, for example exercise.py. Replace each to-do comment with your code.
  3. Run the script with python exercise.py from your project folder (the one that holds data/). Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Many of them compare floats with np.isclose or np.allclose and a stated tolerance, the habit this module teaches.

Every exercise starts with these lines. The verifier runs them before each exercise.

import numpy as np
import pandas as pd
np.set_printoptions(precision=3, suppress=True)
Warm-up

Load data/houses.csv. Build the feature vector of house H0005 with the features sqft, bedrooms, bathrooms and year_built, as a float array. Print the house id with the vector, then the shape of the vector.

Expected output
H0005 [3170. 4. 3.5 1972. ]
(4,)
Starter
houses = pd.read_csv("data/houses.csv")
features = ["sqft", "bedrooms", "bathrooms", "year_built"]
# TODO: select the row of H0005 and the four features as a float array
# TODO: print the id with the vector, then the shape
Hint 1

H0005 is the fifth row, so its row label is 4. You can also find it with houses["house_id"] == "H0005".

Hint 2

houses.loc[4, features].to_numpy(dtype=float) returns a 1-D array.

Solution
houses = pd.read_csv("data/houses.csv")
features = ["sqft", "bedrooms", "bathrooms", "year_built"]
row = houses.index[houses["house_id"] == "H0005"][0]
x = houses.loc[row, features].to_numpy(dtype=float)
print(houses.loc[row, "house_id"], x)
print(x.shape)
assert x.shape == (4,)
assert x[0] == 3170 and x[3] == 1972
Output
H0005 [3170. 4. 3.5 1972. ]
(4,)

How it works:

  1. The boolean mask finds the row label of H0005 (4), so the code does not depend on the row order.
  2. .loc[row, features] picks the four features in the order of the list, and .to_numpy(dtype=float) makes a float vector.
  3. The shape (4,) means a 1-D array with 4 elements: one per feature.

Alternative: set the id as the index first: houses.set_index("house_id").loc["H0005", features].to_numpy(dtype=float).

M32-W02 · Predict the output: vector arithmetic

Section titled “M32-W02 · Predict the output: vector arithmetic”
Warm-up

Predict the output: write down what each line prints, then run the code. The vectors are small on purpose, so you can compute each line in your head.

Starter
a = np.array([2.0, 4.0, 6.0])
b = np.array([1.0, 0.5, 2.0])
print(a + b)
print(a * b)
print(2 * a - b)
print(a / b)
print(a @ b)

Acceptance criteria:

  • Write your five predictions line by line before you run the code.
  • Your prediction matches the Output in the solution, and you can explain the one line that does not print a vector.
Hint 1

+, *, - and / work element by element: position 0 with position 0, and so on.

Hint 2

@ between two 1-D arrays is the dot product: multiply element by element, then add up. The result is one number.

Solution
a = np.array([2.0, 4.0, 6.0])
b = np.array([1.0, 0.5, 2.0])
print(a + b)
print(a * b)
print(2 * a - b)
print(a / b)
print(a @ b)
assert a @ b == np.sum(a * b) == 16.0
Output
[3. 4.5 8. ]
[ 2. 2. 12.]
[ 3. 7.5 10. ]
[2. 8. 3.]
16.0

How it works:

  1. a + b adds position by position: 2 + 1, 4 + 0.5, 6 + 2.
  2. a * b multiplies position by position. It is not a dot product.
  3. 2 * a - b scales a by 2 first (precedence), then subtracts b.
  4. a / b divides position by position: 4 / 0.5 is 8.
  5. a @ b is the dot product 2 + 2 + 12 = 16, a single number.

M32-W03 · Price a shopping basket with a dot product

Section titled “M32-W03 · Price a shopping basket with a dot product”
Warm-up

A customer buys 2 Wireless Earbuds (79.99 USD), 1 pair of Noise-Cancelling Headphones (249.00 USD) and 3 Smartwatch Series 5 (199.99 USD), with the prices from data/products.csv. Compute the basket total twice: with a loop and with a dot product. Print both, rounded to 2 decimals.

Expected output
loop: 1008.95
dot: 1008.95
Starter
quantities = np.array([2, 1, 3])
prices = np.array([79.99, 249.00, 199.99])
# TODO: total with a for loop over zip(quantities, prices)
# TODO: total with the @ operator
# TODO: print both
Hint 1

A basket total is “quantity times price, added up”. That is the definition of a dot product.

Hint 2

quantities @ prices gives the total in one step.

Solution
quantities = np.array([2, 1, 3])
prices = np.array([79.99, 249.00, 199.99])
loop_total = 0.0
for q, price in zip(quantities, prices, strict=True):
loop_total += q * price
dot_total = quantities @ prices
print(f"loop: {loop_total:.2f}")
print(f"dot: {dot_total:.2f}")
assert np.isclose(loop_total, dot_total)
assert np.isclose(dot_total, 1008.95)
Output
loop: 1008.95
dot: 1008.95

How it works:

  1. The loop multiplies each quantity by its price and adds the result to a running total.
  2. quantities @ prices does the same in one vectorized operation.
  3. The asserts compare floats with np.isclose, because the two ways can differ in the last digit.

Alternative: np.dot(quantities, prices) and np.sum(quantities * prices) give the same total.

Warm-up

Two customers have the usage vectors [17, 0, 10.8] and [12, 3, 15.3] (logins in 30 days, support tickets, average session minutes). Compute the Euclidean (L2) and the Manhattan (L1) distance between them, once by hand with NumPy operations and once with np.linalg.norm. Print the two distances with 3 decimals.

Expected output
L2: 7.365
L1: 12.500
Starter
c1 = np.array([17, 0, 10.8])
c2 = np.array([12, 3, 15.3])
# TODO: the difference vector
# TODO: L2 by hand and with np.linalg.norm; L1 by hand and with ord=1
Hint 1

A distance is the norm of the difference vector c2 - c1.

Hint 2

L2: np.sqrt(np.sum(d**2)). L1: np.sum(np.abs(d)). np.linalg.norm(d, ord=1) gives L1.

Solution
c1 = np.array([17, 0, 10.8])
c2 = np.array([12, 3, 15.3])
d = c2 - c1
l2 = np.sqrt(np.sum(d**2))
l1 = np.sum(np.abs(d))
print(f"L2: {l2:.3f}")
print(f"L1: {l1:.3f}")
assert np.isclose(l2, np.linalg.norm(d))
assert np.isclose(l1, np.linalg.norm(d, ord=1))
Output
L2: 7.365
L1: 12.500

How it works:

  1. d is [-5, 3, 4.5]: how customer 2 differs from customer 1 in each feature.
  2. L2 squares each difference, adds them (25 + 9 + 20.25) and takes the square root.
  3. L1 adds the absolute differences: 5 + 3 + 4.5 = 12.5.
  4. L2 is never larger than L1. They are equal only when one feature holds the whole difference.

M32-W05 · Fix the bug: the shapes do not match

Section titled “M32-W05 · Fix the bug: the shapes do not match”
Warm-up

Fix the bug: this code should score every house with four weights, one per feature, but it crashes with a ValueError. Find the cause and fix it so that the code prints the shapes and the first three scores.

houses = pd.read_csv("data/houses.csv")
X = houses[["sqft", "bedrooms", "bathrooms"]].to_numpy(dtype=float)
weights = np.array([0.2, 5.0, 15.0, 25.0]) # sqft, bedrooms, bathrooms, condition
scores = X @ weights
print(scores[:3])
Output
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 4 is different from 3)
Expected output
(3000, 4) (4,)
[656.5 462. 392. ]
Starter
houses = pd.read_csv("data/houses.csv")
X = houses[["sqft", "bedrooms", "bathrooms"]].to_numpy(dtype=float)
weights = np.array([0.2, 5.0, 15.0, 25.0]) # sqft, bedrooms, bathrooms, condition
# TODO: make the shapes match, print X.shape and weights.shape, then the scores
Hint 1

Print X.shape and weights.shape. For (n, p) @ (p,), the two p must be equal.

Hint 2

The comment on the weights lists four features. Which one is missing from X?

Solution
houses = pd.read_csv("data/houses.csv")
X = houses[["sqft", "bedrooms", "bathrooms", "condition"]].to_numpy(dtype=float)
weights = np.array([0.2, 5.0, 15.0, 25.0]) # sqft, bedrooms, bathrooms, condition
print(X.shape, weights.shape)
scores = X @ weights
print(scores[:3])
assert scores.shape == (len(houses),)
assert np.isclose(scores[0], 0.2 * 2420 + 5 * 4 + 15 * 3.5 + 25 * 4)
Output
(3000, 4) (4,)
[656.5 462. 392. ]

How it works:

  1. X had 3 columns but weights had 4 elements. The inner sizes of (3000, 3) @ (4,) differ, so NumPy raised the error.
  2. The weights describe four features, so the fix adds the missing condition column to X.
  3. Now (3000, 4) @ (4,) gives (3000,): one score per house.

Alternative: if the fourth weight is the mistake, drop it instead: weights[:3]. The comment tells you which side is right. Always fix the side that disagrees with the meaning, not the side that is easier to change.

Warm-up

The loss of a one-weight model is f(w)=(3w−6)2f(w) = (3w - 6)^2. Compute its derivative at w=1w = 1 in two ways: the central difference with h = 1e-5, and the analytic derivative f′(w)=6(3w−6)f'(w) = 6(3w - 6) from the chain rule. Print both with 4 decimals. Then print the derivative at w=2w = 2.

Expected output
numerical at 1: -18.0000
analytic at 1: -18.0000
analytic at 2: 0.0000
Starter
def f(w):
return (3 * w - 6) ** 2
# TODO: central difference at w = 1 with h = 1e-5
# TODO: analytic derivative at w = 1 and at w = 2
Hint 1

The central difference is (f(w + h) - f(w - h)) / (2 * h).

Hint 2

Chain rule: the outer function is u2u^2 with slope 2u2u, the inner function is 3w−63w - 6 with slope 3. So f′(w)=2(3w−6)⋅3f'(w) = 2(3w - 6) \cdot 3.

Solution
def f(w: float) -> float:
return (3 * w - 6) ** 2
def f_prime(w: float) -> float:
return 6 * (3 * w - 6)
w, h = 1.0, 1e-5
numerical = (f(w + h) - f(w - h)) / (2 * h)
print(f"numerical at 1: {numerical:.4f}")
print(f"analytic at 1: {f_prime(w):.4f}")
print(f"analytic at 2: {f_prime(2.0):.4f}")
assert np.isclose(numerical, f_prime(w))
assert f_prime(2.0) == 0
Output
numerical at 1: -18.0000
analytic at 1: -18.0000
analytic at 2: 0.0000

How it works:

  1. At w=1w = 1, 3w−6=−33w - 6 = -3, so the analytic derivative is 6⋅(−3)=−186 \cdot (-3) = -18. The negative slope says “increase ww”.
  2. The central difference nudges ww by a tiny amount in both directions and measures the rise over the run. It matches.
  3. At w=2w = 2, 3w−6=03w - 6 = 0: the loss is at its minimum and the slope is 0.

M32-W07 · Expected number of garage spaces

Section titled “M32-W07 · Expected number of garage spaces”
Warm-up

From data/houses.csv, build the probability table of garage_spaces: each value and the share of houses with that value. Compute the expected value and the variance from the table with dot products. Check them against .mean() and .var() of the column.

Expected output
values: [0 1 2 3]
probs: [0.155 0.361 0.376 0.108]
E = 1.4373, Var = 0.7721
Starter
houses = pd.read_csv("data/houses.csv")
garage = houses["garage_spaces"].to_numpy()
# TODO: values and counts with np.unique(..., return_counts=True)
# TODO: probabilities, expected value and variance with @
Hint 1

The probabilities are the counts divided by the number of houses. They add up to 1.

Hint 2

E[G]=∑kk P(G=k)\mathbb{E}[G] = \sum_k k\,P(G = k) is values @ probs. The variance is ((values - expected) ** 2) @ probs.

Solution
houses = pd.read_csv("data/houses.csv")
garage = houses["garage_spaces"].to_numpy()
values, counts = np.unique(garage, return_counts=True)
probs = counts / counts.sum()
expected = values @ probs
variance = ((values - expected) ** 2) @ probs
print("values:", values)
print("probs: ", probs.round(4))
print(f"E = {expected:.4f}, Var = {variance:.4f}")
assert np.isclose(probs.sum(), 1)
assert np.isclose(expected, garage.mean())
assert np.isclose(variance, garage.var())
Output
values: [0 1 2 3]
probs: [0.155 0.361 0.376 0.108]
E = 1.4373, Var = 0.7721

How it works:

  1. np.unique(..., return_counts=True) returns the distinct values and how often each occurs.
  2. The probabilities are the shares. Their sum is 1.
  3. The expected value weights each value by its probability: a dot product. It equals the column mean, because the mean also gives each house the weight 1/n1/n.
  4. The variance is the expected squared distance from the mean. NumPy’s .var() uses the same population formula (divide by nn).

M32-W08 · From scores to probabilities and odds

Section titled “M32-W08 · From scores to probabilities and odds”
Warm-up

A churn model gives three customers the scores (log-odds) −2, 0 and 3. Write a sigmoid function, turn the scores into churn probabilities and compute the odds p/(1−p)p / (1 - p). Print the probabilities and the odds with 3 decimals. Check that the log of the odds gives the scores back.

Expected output
probabilities: [0.119 0.5 0.953]
odds: [ 0.135 1. 20.086]
Starter
scores = np.array([-2.0, 0.0, 3.0])
# TODO: def sigmoid(z)
# TODO: probabilities, odds, and a check with np.log(odds)
Hint 1

σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}). NumPy’s np.exp works on whole arrays.

Hint 2

The odds of p=0.5p = 0.5 are 1 (“one to one”). The log-odds of 1 is 0.

Solution
def sigmoid(z: np.ndarray) -> np.ndarray:
return 1 / (1 + np.exp(-z))
scores = np.array([-2.0, 0.0, 3.0])
probs = sigmoid(scores)
odds = probs / (1 - probs)
print("probabilities:", probs.round(3))
print("odds: ", odds.round(3))
assert np.allclose(np.log(odds), scores)
assert np.allclose(odds, np.exp(scores))
Output
probabilities: [0.119 0.5 0.953]
odds: [ 0.135 1. 20.086]

How it works:

  1. The sigmoid maps −2 to 0.119, 0 to 0.5 and 3 to 0.953. Higher scores mean higher churn probability.
  2. The odds compare “churn” to “stay”: 0.119 / 0.881 ≈ 0.135, so about 1 to 7.4.
  3. The odds equal eze^z, so the log of the odds is the score. That is why the score is called the log-odds.
Core

Load sqft, year_built, condition and distance_to_center_km from data/houses.csv as a data matrix. Standardize every column with broadcasting. Print the column means and standard deviations before, then the standardized row of H0001. Check that every standardized column has mean 0 and standard deviation 1 (tolerance 1e-12).

Expected output
means: [1856.637 1989.293 3.012 8.562]
stds: [711.831 24.987 0.953 5.197]
H0001: [ 0.791 1.069 1.037 -0.127]
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "year_built", "condition", "distance_to_center_km"]
# TODO: X as a float array
# TODO: column means and standard deviations (axis=0)
# TODO: Z = (X - mu) / sigma, print Z[0], check means and stds
Hint 1

X.mean(axis=0) gives one mean per column, shape (4,). Subtracting it from X broadcasts over the rows.

Hint 2

Check with np.allclose(Z.mean(axis=0), 0, atol=1e-12). A relative tolerance is useless near 0, so pass an absolute one.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "year_built", "condition", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
mu = X.mean(axis=0)
sigma = X.std(axis=0)
Z = (X - mu) / sigma
print("means:", mu)
print("stds: ", sigma)
print("H0001:", Z[0])
assert np.allclose(Z.mean(axis=0), 0, atol=1e-12)
assert np.allclose(Z.std(axis=0), 1, atol=1e-12)
Output
means: [1856.637 1989.293 3.012 8.562]
stds: [711.831 24.987 0.953 5.197]
H0001: [ 0.791 1.069 1.037 -0.127]

How it works:

  1. mu and sigma have shape (4,), one value per column.
  2. (X - mu) / sigma broadcasts the two vectors over all 3,000 rows: every row is standardized at once.
  3. H0001 was built in 2016, about 1.1 standard deviations newer than the average house.
  4. The asserts use an absolute tolerance, because the means are tiny numbers like 1e-16, not exactly 0.

Alternative: scikit-learn’s StandardScaler().fit_transform(X) gives the same matrix and remembers mean_ and scale_ for new data (module 34).

M32-C02 · Rank reviews by cosine similarity

Section titled “M32-C02 · Rank reviews by cosine similarity”
Core

A support agent reads review R00010 about Wireless Earbuds and wants the most similar reviews. Use the vocabulary ["battery", "quality", "price", "delivery", "service", "recommend"] and count each word in the lowercased text of these reviews: R00070, R00074, R00095, R00143, R00151, R00156, R00175, R00284. Compute the cosine similarity of R00010 with each of them using one matrix–vector product, and print the reviews from most to least similar.

Expected output
R00010 [1 1 0 0 0 1]
R00070 [1 1 0 0 0 1] 1.000
R00151 [1 1 0 0 0 1] 1.000
R00284 [1 1 0 0 0 0] 0.816
R00074 [0 1 0 0 0 0] 0.577
R00095 [1 0 0 0 0 0] 0.577
R00143 [1 0 0 0 0 0] 0.577
R00175 [1 0 0 1 0 0] 0.408
R00156 [0 0 1 0 1 0] 0.000
Starter
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False).set_index("review_id")
vocab = ["battery", "quality", "price", "delivery", "service", "recommend"]
query_id = "R00010"
ids = ["R00070", "R00074", "R00095", "R00143", "R00151", "R00156", "R00175", "R00284"]
# TODO: a count vector for the query and a count matrix for the candidates
# TODO: cosine similarity with one matrix-vector product and the norms
# TODO: print id and similarity, sorted from high to low
Hint 1

Build the counts with a nested list comprehension: one row per review, one column per word, text.count(word).

Hint 2

M @ q gives the dot product of every row of M with q. Divide by np.linalg.norm(M, axis=1) * np.linalg.norm(q).

Hint 3

np.argsort(-sims) sorts the positions from the highest similarity to the lowest.

Solution
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False).set_index("review_id")
vocab = ["battery", "quality", "price", "delivery", "service", "recommend"]
query_id = "R00010"
ids = ["R00070", "R00074", "R00095", "R00143", "R00151", "R00156", "R00175", "R00284"]
def word_counts(text: str) -> list[int]:
lowered = text.lower()
return [lowered.count(word) for word in vocab]
q = np.array(word_counts(reviews.loc[query_id, "text"]))
M = np.array([word_counts(reviews.loc[i, "text"]) for i in ids])
sims = (M @ q) / (np.linalg.norm(M, axis=1) * np.linalg.norm(q))
print(query_id, q)
for pos in np.argsort(-sims, kind="stable"):
print(f"{ids[pos]} {M[pos]} {sims[pos]:.3f}")
assert M.shape == (8, 6)
assert np.all((sims >= 0) & (sims <= 1 + 1e-12))
Output
R00010 [1 1 0 0 0 1]
R00070 [1 1 0 0 0 1] 1.000
R00151 [1 1 0 0 0 1] 1.000
R00284 [1 1 0 0 0 0] 0.816
R00074 [0 1 0 0 0 0] 0.577
R00095 [1 0 0 0 0 0] 0.577
R00143 [1 0 0 0 0 0] 0.577
R00175 [1 0 0 1 0 0] 0.408
R00156 [0 0 1 0 1 0] 0.000

How it works:

  1. Each review becomes a vector of 6 word counts. R00010 mentions the battery, the quality and “recommend”.
  2. M @ q computes the 8 dot products at once. Dividing by the row norms and the query norm turns them into cosines.
  3. Counts are never negative, so every cosine lies between 0 and 1.
  4. Look at the top two: R00010 ends with “Would not recommend” (rating 2) and R00070 with “Highly recommend!” (rating 5). Their count vectors are identical, so the cosine is 1.000. Single-word counts cannot see “not”. Module 41 adds word pairs (n-grams) and better weights (TF-IDF) to fix this.
  5. kind="stable" keeps the original order for ties, so the printed order is reproducible.

Alternative: normalize first, then multiply: M_unit = M / np.linalg.norm(M, axis=1, keepdims=True) and M_unit @ (q / np.linalg.norm(q)). With unit vectors, the dot product is the cosine. Search engines store normalized vectors for this reason.

M32-C03 · Refactor: loop → vectorized distances

Section titled “M32-C03 · Refactor: loop → vectorized distances”
Core

Refactor: the code below finds the 5 houses nearest to H0001 on standardized features with a Python loop. Rewrite the distance computation as one vectorized line with broadcasting and np.linalg.norm(..., axis=1). Check that both versions give the same distances and print the 5 nearest house ids with their distances.

Loop version
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
loop_dist = []
for row in Z:
total = 0.0
for a, b in zip(row, Z[0], strict=True):
total += (a - b) ** 2
loop_dist.append(total**0.5)
loop_dist = np.array(loop_dist)
print(np.argsort(loop_dist)[1:6])
Output
[ 156 1104 1905 2763 1890]
Expected output
H0157 0.059
H1105 0.119
H1906 0.233
H2764 0.240
H1891 0.241
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
# TODO: dist = one vectorized line
# TODO: the 5 nearest positions (skip H0001 itself), print ids and distances
Hint 1

Z - Z[0] subtracts H0001’s vector from every row: shape (3000, 5).

Hint 2

np.linalg.norm(Z - Z[0], axis=1) returns one L2 norm per row.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
dist = np.linalg.norm(Z - Z[0], axis=1)
nearest = np.argsort(dist)[1:6]
for pos in nearest:
print(houses.loc[pos, "house_id"], f"{dist[pos]:.3f}")
loop_dist = np.array([sum((a - b) ** 2 for a, b in zip(row, Z[0], strict=True)) ** 0.5
for row in Z])
assert np.allclose(dist, loop_dist)
assert dist[0] == 0
Output
H0157 0.059
H1105 0.119
H1906 0.233
H2764 0.240
H1891 0.241

How it works:

  1. Broadcasting subtracts the query from all 3,000 rows in one step.
  2. axis=1 takes the norm along each row, so dist has one entry per house.
  3. argsort sorts positions by distance. Position 0 is H0001 itself (distance 0), so the slice starts at 1.
  4. The assert proves that the refactor did not change any distance.

Alternative: square distances are enough for ranking, because the square root keeps the order: np.sum((Z - Z[0]) ** 2, axis=1). scikit-learn’s NearestNeighbors does the search for you and is faster on big data.

M32-C04 · Predict the output: matrix shapes

Section titled “M32-C04 · Predict the output: matrix shapes”
Core

Predict the output: A has shape (4, 3), B has shape (3, 2) and v has shape (3,). For each line, write the printed shape, or “error” if NumPy refuses. Then run the code.

Starter
A = np.ones((4, 3))
B = np.ones((3, 2))
v = np.ones(3)
print((A @ B).shape)
print((A @ v).shape)
print((A.T @ A).shape)
print((B.T @ A.T).shape)
print((v @ v).shape)
print((A * v).shape)
try:
print((B @ A).shape)
except ValueError:
print("error")

Acceptance criteria:

  • Write your seven predictions before you run the code.
  • Your predictions match the Output in the solution. For each line, you can say which sizes had to match.
Hint 1

For @, the inner sizes must match: (m, k) @ (k, n) gives (m, n). A 1-D array on the right acts as a column.

Hint 2

* is element-wise with broadcasting, not a matrix product: (4, 3) * (3,) stretches v over the rows. A dot product of two 1-D arrays is a single number with shape ().

Solution
A = np.ones((4, 3))
B = np.ones((3, 2))
v = np.ones(3)
print((A @ B).shape)
print((A @ v).shape)
print((A.T @ A).shape)
print((B.T @ A.T).shape)
print((v @ v).shape)
print((A * v).shape)
try:
print((B @ A).shape)
except ValueError:
print("error")
assert (B.T @ A.T).shape == (A @ B).T.shape
Output
(4, 2)
(4,)
(3, 3)
(2, 4)
()
(4, 3)
error

How it works:

  1. (4, 3) @ (3, 2) → (4, 2).
  2. (4, 3) @ (3,) → (4,): one value per row, the “predict for every row” shape.
  3. (3, 4) @ (4, 3) → (3, 3): the X⊤XX^\top X shape.
  4. (2, 3) @ (3, 4) → (2, 4), which is (AB)⊤(AB)^\top. The assert checks the rule (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top.
  5. v @ v is a dot product: a NumPy scalar with the empty shape ().
  6. A * v broadcasts: the shape stays (4, 3).
  7. (3, 2) @ (4, 3): the inner sizes 2 and 4 differ, so NumPy raises ValueError.

M32-C05 · Predict every house price with one product

Section titled “M32-C05 · Predict every house price with one product”
Core

Use the agent’s rule of thumb from the lesson: price in thousand USD = 50 + 0.2 × sqft + 5 × bedrooms + 15 × bathrooms + 25 × condition − 10 × distance. Predict all 3,000 prices with one matrix–vector product. Print the mean absolute error (MAE) in thousand USD, the share of houses predicted within 20% of the real price, and the mean error (prediction minus price) per neighborhood, sorted from most underpriced to most overpriced.

Expected output
MAE: 134.6 thousand USD
within 20%: 43.3%
neighborhood
Lakeview -323.2
Oak Hill -236.2
Riverside 14.1
Maple Grove 29.3
Downtown 63.9
Old Town 91.8
Cedar Park 97.1
Westfield 110.6
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
weights = np.array([0.2, 5, 15, 25, -10])
base = 50
# TODO: X, y in thousand USD, y_hat = X @ weights + base
# TODO: MAE, share within 20%, mean error per neighborhood
Hint 1

“Within 20%” means np.abs(y_hat - y) / y <= 0.2. The mean of a boolean array is the share of True.

Hint 2

Put the errors into a pandas Series indexed by neighborhood, or use houses.assign(error=...) and groupby("neighborhood").

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
weights = np.array([0.2, 5, 15, 25, -10])
base = 50
X = houses[cols].to_numpy(dtype=float)
y = houses["price"].to_numpy() / 1000
y_hat = X @ weights + base
error = y_hat - y
mae = np.mean(np.abs(error))
within = np.mean(np.abs(error) / y <= 0.2)
by_hood = houses.assign(error=error).groupby("neighborhood")["error"].mean()
print(f"MAE: {mae:.1f} thousand USD")
print(f"within 20%: {within:.1%}")
print(by_hood.round(1).sort_values().to_string())
assert y_hat.shape == y.shape == (3000,)
assert by_hood.idxmin() == "Lakeview"
Output
MAE: 134.6 thousand USD
within 20%: 43.3%
neighborhood
Lakeview -323.2
Oak Hill -236.2
Riverside 14.1
Maple Grove 29.3
Downtown 63.9
Old Town 91.8
Cedar Park 97.1
Westfield 110.6

How it works:

  1. X @ weights + base makes 3,000 predictions with one product.
  2. The MAE averages the absolute errors, so over- and underpricing do not cancel.
  3. The boolean array np.abs(error) / y <= 0.2 is True for good predictions; its mean is their share.
  4. Grouping the errors by neighborhood shows the pattern: the rule underprices Lakeview and Oak Hill by hundreds of thousands and overprices the cheap neighborhoods. The missing feature is the neighborhood itself.

M32-C06 · Choose a method: inv, solve or lstsq

Section titled “M32-C06 · Choose a method: inv, solve or lstsq”
Core

Choose a method and justify it. For each problem, pick np.linalg.inv, np.linalg.solve or np.linalg.lstsq, solve it, and print the answer:

  1. Three stores sold these units of three products: [[101, 63, 31], [56, 34, 17], [42, 29, 11]], for list-price revenues [64034.99, 35028.44, 24869.58] USD. Find the three unit prices.
  2. Fit price (thousand USD) = w0+w1⋅w_0 + w_1 \cdot sqft for all houses in data/houses.csv.
  3. You need the weights of problem 2 again, but your colleague suggests np.linalg.inv(A.T @ A) @ A.T @ y. Show that it gives the same weights here, and explain in one sentence why you still would not use it.
Expected output
1. unit prices: [ 79.99 249. 1299. ]
2. intercept and per-sqft weight: [-130.345 0.327]
3. same weights: True
Starter
units = np.array([[101, 63, 31], [56, 34, 17], [42, 29, 11]])
revenue = np.array([64034.99, 35028.44, 24869.58])
houses = pd.read_csv("data/houses.csv")
# TODO: problem 1 - a square system
# TODO: problem 2 - a tall least-squares problem with a column of ones
# TODO: problem 3 - compare with the inverse formula
Hint 1

Problem 1 has as many equations as unknowns: a square system. Problem 2 has 3,000 equations and 2 unknowns: no exact solution, so you want the least-squares one.

Hint 2

For problem 2, build A = np.column_stack([np.ones(n), sqft]) and call np.linalg.lstsq(A, y); take the first returned value.

Solution
units = np.array([[101, 63, 31], [56, 34, 17], [42, 29, 11]])
revenue = np.array([64034.99, 35028.44, 24869.58])
prices = np.linalg.solve(units, revenue)
print("1. unit prices:", prices.round(2))
houses = pd.read_csv("data/houses.csv")
sqft = houses["sqft"].to_numpy(dtype=float)
y = houses["price"].to_numpy() / 1000
A = np.column_stack([np.ones(len(sqft)), sqft])
w, *_ = np.linalg.lstsq(A, y)
print("2. intercept and per-sqft weight:", w.round(3))
w_inv = np.linalg.inv(A.T @ A) @ A.T @ y
print("3. same weights:", np.allclose(w, w_inv))
assert np.allclose(units @ prices, revenue)
assert np.allclose(prices, [79.99, 249.00, 1299.00])
Output
1. unit prices: [ 79.99 249. 1299. ]
2. intercept and per-sqft weight: [-130.345 0.327]
3. same weights: True

How it works:

  1. solve for problem 1: the system is square with a unique answer, and solve finds it without forming an inverse. The prices are the list prices of P001, P002 and P003.
  2. lstsq for problem 2: the system is tall (3,000 rows, 2 unknowns). lstsq minimizes the squared error directly from A. The slope is about 0.33k USD (327 USD) per sqft.
  3. Not inv: the inverse gives the same weights on this well-conditioned problem, but it does more work and loses accuracy when columns are nearly dependent (the duplicated-area example of the lesson). Code that only works on easy data is a trap.

M32-C07 · Fit a model for one neighborhood

Section titled “M32-C07 · Fit a model for one neighborhood”
Core

Fit price (thousand USD) on sqft and has_pool, with an intercept, for the Lakeview houses only. Use np.linalg.lstsq on the raw features. Print the three weights, the RMSE and R², and the predicted price of a 2,000 sqft Lakeview house with and without a pool.

Expected output
307 houses, weights: [-414.192 0.563 54.391]
RMSE 212.5, R² 0.788
2,000 sqft without / with pool: [712.4 766.8]
Starter
houses = pd.read_csv("data/houses.csv")
lake = houses[houses["neighborhood"] == "Lakeview"]
# TODO: design matrix with ones, sqft and has_pool; y in thousand USD
# TODO: lstsq, RMSE, R², two predictions
Hint 1

np.column_stack([np.ones(n), lake["sqft"], lake["has_pool"]]) builds the design matrix.

Hint 2

R² is 1 - SS_res / SS_tot, with SS_res = np.sum((y - y_hat) ** 2) and SS_tot = np.sum((y - y.mean()) ** 2). A new house is a row [1, 2000, 0].

Solution
houses = pd.read_csv("data/houses.csv")
lake = houses[houses["neighborhood"] == "Lakeview"]
n = len(lake)
A = np.column_stack([np.ones(n), lake["sqft"], lake["has_pool"]]).astype(float)
y = lake["price"].to_numpy() / 1000
w, *_ = np.linalg.lstsq(A, y)
y_hat = A @ w
rmse = np.sqrt(np.mean((y - y_hat) ** 2))
r2 = 1 - np.sum((y - y_hat) ** 2) / np.sum((y - y.mean()) ** 2)
new = np.array([[1, 2000, 0], [1, 2000, 1]])
print(f"{n} houses, weights: {w.round(3)}")
print(f"RMSE {rmse:.1f}, R² {r2:.3f}")
print("2,000 sqft without / with pool:", (new @ w).round(1))
assert w[1] > 0
assert np.isclose((new @ w)[1] - (new @ w)[0], w[2])
Output
307 houses, weights: [-414.192 0.563 54.391]
RMSE 212.5, R² 0.788
2,000 sqft without / with pool: [712.4 766.8]

How it works:

  1. Inside one neighborhood, size explains most of the price, so R² (0.79) is much higher than the 0.63 of the five-feature model on all houses in the lesson.
  2. The sqft weight is the price per extra sqft in thousand USD. The pool weight is the price difference between two houses that differ only in the pool.
  3. Two new houses are two rows of a small design matrix. new @ w predicts both. Their difference is exactly the pool weight, which the second assert checks.

M32-C08 · Derive and check a penalized gradient

Section titled “M32-C08 · Derive and check a penalized gradient”
Core

The model is price (thousand USD) =b+w1⋅= b + w_1 \cdot size (thousand sqft) +w2⋅+ w_2 \cdot distance (km). Its loss is the MSE plus a Ridge penalty on the two feature weights (not on the intercept), with λ=10\lambda = 10:

L(b,w1,w2)=1n∑i=1n(b+w1xi1+w2xi2−yi)2+λ (w12+w22)L(b, w_1, w_2) = \frac{1}{n}\sum_{i=1}^{n} (b + w_1 x_{i1} + w_2 x_{i2} - y_i)^2 + \lambda\,(w_1^2 + w_2^2)

Derive the three partial derivatives with the sum, power and chain rules. Write loss(params) and grad(params) for params = [b, w1, w2], with no Python loop over rows. Check the gradient at params = [100, 150, -5] against central differences with h = 1e-4. Print both gradients and whether the relative error is below 1e-7.

Expected output
analytic: [ -281.562 2294.229 -2192.332]
numerical: [ -281.562 2294.229 -2192.332]
relative error below 1e-7: True
Starter
houses = pd.read_csv("data/houses.csv")
X = np.column_stack([houses["sqft"] / 1000, houses["distance_to_center_km"]])
y = houses["price"].to_numpy() / 1000
lam = 10.0
# TODO: def loss(params) and def grad(params), params = [b, w1, w2]
# TODO: numerical gradient: nudge one parameter at a time
# TODO: relative error = norm(a - n) / norm(a + n)
Hint 1

By the sum rule, the gradient is the gradient of the MSE part plus the gradient of the penalty part. The MSE part is the lesson’s formula 2nA⊤(Aw−y)\frac{2}{n}A^\top(A\mathbf{w} - \mathbf{y}) with a column of ones in A.

Hint 2

By the power and constant-factor rules, ∂∂w1λ(w12+w22)=2λw1\frac{\partial}{\partial w_1}\lambda(w_1^2 + w_2^2) = 2\lambda w_1. The intercept bb does not appear in the penalty, so its penalty slope is 0.

Hint 3

For the numerical gradient, loop over the 3 parameters, not over the rows: add h to one entry of a copy of params, then subtract it.

Solution
houses = pd.read_csv("data/houses.csv")
X = np.column_stack([houses["sqft"] / 1000, houses["distance_to_center_km"]])
y = houses["price"].to_numpy() / 1000
lam = 10.0
A = np.column_stack([np.ones(len(y)), X]) # columns: 1, size, distance
mask = np.array([0.0, 1.0, 1.0]) # penalize w1 and w2, not b
def loss(params: np.ndarray) -> float:
mse = np.mean((A @ params - y) ** 2)
return float(mse + lam * np.sum((mask * params) ** 2))
def grad(params: np.ndarray) -> np.ndarray:
return 2 / len(y) * A.T @ (A @ params - y) + 2 * lam * mask * params
params, h = np.array([100.0, 150.0, -5.0]), 1e-4
analytic = grad(params)
numerical = np.zeros(3)
for j in range(3):
step = np.zeros(3)
step[j] = h
numerical[j] = (loss(params + step) - loss(params - step)) / (2 * h)
rel_error = np.linalg.norm(analytic - numerical) / np.linalg.norm(analytic + numerical)
print("analytic: ", analytic.round(3))
print("numerical:", numerical.round(3))
print("relative error below 1e-7:", rel_error < 1e-7)
assert rel_error < 1e-7
assert np.isclose(analytic[0], 2 * np.mean(A @ params - y)) # b has no penalty term
Output
analytic: [ -281.562 2294.229 -2192.332]
numerical: [ -281.562 2294.229 -2192.332]
relative error below 1e-7: True

How it works:

  1. The derivation, one rule at a time. With the error ei=b+w1xi1+w2xi2−yie_i = b + w_1 x_{i1} + w_2 x_{i2} - y_i, the chain rule gives the slope of ei2e_i^2 as 2ei2e_i times the slope of eie_i, which is 1 for bb, xi1x_{i1} for w1w_1 and xi2x_{i2} for w2w_2. The sum rule and the factor 1n\frac{1}{n} average these. The power rule adds 2λwj2\lambda w_j for the two penalized weights:
∂L∂b=2n∑iei∂L∂wj=2n∑iei xij+2λwj\frac{\partial L}{\partial b} = \frac{2}{n}\sum_i e_i \qquad \frac{\partial L}{\partial w_j} = \frac{2}{n}\sum_i e_i\,x_{ij} + 2\lambda w_j
  1. mask is 0 for the intercept and 1 for the weights, so one vectorized line adds the penalty slope to the right entries only.
  2. The numerical gradient nudges one parameter at a time, which is what “partial” means. The relative error is tiny, so the derivation is right.
  3. The second assert checks that the intercept’s slope has no penalty part.

Alternative: write the penalty with the matrix DD of exercise M32-X04 (D = np.diag(mask)), so the gradient reads 2 / n * A.T @ (A @ params - y) + 2 * lam * D @ params, the form that scales to any number of features.

Core

For one customer, logistic regression computes z=wx+bz = w x + b, p=σ(z)p = \sigma(z) and the log loss L=−[ylog⁡p+(1−y)log⁡(1−p)]L = -[y \log p + (1 - y)\log(1 - p)]. The chain rule gives dLdz=p−y\frac{dL}{dz} = p - y and dLdw=(p−y) x\frac{dL}{dw} = (p - y)\,x. Check both numerically for two customers: (x=1.5,y=1)(x = 1.5, y = 1) and (x=−0.5,y=0)(x = -0.5, y = 0), with w=0.8w = 0.8 and b=−0.3b = -0.3.

Expected output
x=1.5, y=1: p=0.7109 dL/dz -0.2891 vs -0.2891 dL/dw -0.4336 vs -0.4336
x=-0.5, y=0: p=0.3318 dL/dz 0.3318 vs 0.3318 dL/dw -0.1659 vs -0.1659
Starter
w, b, h = 0.8, -0.3, 1e-6
# TODO: def loss_of_z(z, y) and def loss_of_w(w, x, y)
# TODO: for each customer: chain-rule dL/dz and dL/dw, and central differences
Hint 1

The chain is w→z→p→Lw \to z \to p \to L. Write one function that takes zz and one that takes ww, then nudge the input.

Hint 2

The derivative of the sigmoid is σ(z)(1−σ(z))\sigma(z)(1 - \sigma(z)). Multiplied with dLdp\frac{dL}{dp}, most terms cancel and leave p−yp - y.

Solution
def sigmoid(z: float) -> float:
return 1 / (1 + np.exp(-z))
def loss_of_z(z: float, y: int) -> float:
p = sigmoid(z)
return -(y * np.log(p) + (1 - y) * np.log(1 - p))
def loss_of_w(w: float, x: float, y: int) -> float:
return loss_of_z(w * x + b, y)
w, b, h = 0.8, -0.3, 1e-6
for x, y in [(1.5, 1), (-0.5, 0)]:
z = w * x + b
p = sigmoid(z)
num_dz = (loss_of_z(z + h, y) - loss_of_z(z - h, y)) / (2 * h)
num_dw = (loss_of_w(w + h, x, y) - loss_of_w(w - h, x, y)) / (2 * h)
print(f"x={x}, y={y}: p={p:.4f} dL/dz {p - y:.4f} vs {num_dz:.4f} "
f"dL/dw {(p - y) * x:.4f} vs {num_dw:.4f}")
assert np.isclose(p - y, num_dz) and np.isclose((p - y) * x, num_dw)
Output
x=1.5, y=1: p=0.7109 dL/dz -0.2891 vs -0.2891 dL/dw -0.4336 vs -0.4336
x=-0.5, y=0: p=0.3318 dL/dz 0.3318 vs 0.3318 dL/dw -0.1659 vs -0.1659

How it works:

  1. The chain rule multiplies three slopes: dLdp⋅dpdz⋅dzdw\frac{dL}{dp} \cdot \frac{dp}{dz} \cdot \frac{dz}{dw}. The first two multiply to p−yp - y, a remarkably simple result.
  2. For the churner (y=1y = 1), p−yp - y is negative: raising the score lowers the loss.
  3. For the customer who stays (y=0y = 0), p−y=pp - y = p is positive: lowering the score lowers the loss.
  4. Averaged over all customers, (pi−yi) xi(p_i - y_i)\,x_i becomes the gradient 1nX⊤(σ(Xw)−y)\frac{1}{n}X^\top(\sigma(X\mathbf{w}) - \mathbf{y}) of the lesson.
Core

Fix the bug: this gradient descent should fit price on standardized sqft, but the loss grows at every step. Find the bug, fix it, and print the loss at steps 0, 10 and 50, and the final weights.

houses = pd.read_csv("data/houses.csv")
sqft = houses["sqft"].to_numpy(dtype=float)
z = (sqft - sqft.mean()) / sqft.std()
y = houses["price"].to_numpy() / 1000
w, b, lr = 0.0, 0.0, 0.1
for step in range(51):
error = w * z + b - y
if step in (0, 10, 50):
print(step, round(np.mean(error**2)))
w = w + lr * 2 * np.mean(error * z)
b = b + lr * 2 * np.mean(error)
Output
0 328587
10 10825882
50 23283893316188
Expected output
0 328587
10 50683
50 47442
w = 232.65, b = 476.46
Starter
houses = pd.read_csv("data/houses.csv")
sqft = houses["sqft"].to_numpy(dtype=float)
z = (sqft - sqft.mean()) / sqft.std()
y = houses["price"].to_numpy() / 1000
w, b, lr = 0.0, 0.0, 0.1
# TODO: fix the update, print the loss at steps 0, 10, 50 and the final w, b
Hint 1

The gradient points uphill. Which way should the step go?

Hint 2

The update rule is w←w−η∂L∂ww \leftarrow w - \eta \frac{\partial L}{\partial w}. Check the sign in both update lines.

Solution
houses = pd.read_csv("data/houses.csv")
sqft = houses["sqft"].to_numpy(dtype=float)
z = (sqft - sqft.mean()) / sqft.std()
y = houses["price"].to_numpy() / 1000
w, b, lr = 0.0, 0.0, 0.1
losses = []
for step in range(51):
error = w * z + b - y
losses.append(np.mean(error**2))
if step in (0, 10, 50):
print(step, round(losses[-1]))
w = w - lr * 2 * np.mean(error * z)
b = b - lr * 2 * np.mean(error)
print(f"w = {w:.2f}, b = {b:.2f}")
assert losses[50] < losses[10] < losses[0]
assert np.isclose(b, y.mean(), atol=0.01)
Output
0 328587
10 50683
50 47442
w = 232.65, b = 476.46

How it works:

  1. The buggy code added the gradient, so every step went uphill and the loss grew.
  2. With -, each step goes against the gradient and the loss falls.
  3. With a standardized feature, the intercept converges to the mean price (476.47) and ww to the price change per standard deviation of sqft.

Alternative: write the update once in vector form, params = params - lr * gradient, so that there is only one sign to get right.

M32-C11 · Interpret a learning-rate experiment

Section titled “M32-C11 · Interpret a learning-rate experiment”
Core

Interpret a result. The starter trains the five-feature house model of the lesson with four learning rates and records the loss curve of each. Write a function diagnose(history) that returns "diverged" when the last loss is larger than the first, "too slow" when the last loss is more than 1% above the best possible loss best, and "converged" otherwise. Print the diagnosis of each rate and pick the rate that converged with the fewest iterations to within 0.1% of best.

Expected output
lr = 0.003: too slow, within 0.1% at iteration None
lr = 0.03: too slow, within 0.1% at iteration None
lr = 0.3: converged, within 0.1% at iteration 25
lr = 0.38: diverged, within 0.1% at iteration None
fastest converged rate: 0.3
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "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(Z)), Z])
y = houses["price"].to_numpy() / 1000
w_best, *_ = np.linalg.lstsq(A, y)
best = np.mean((A @ w_best - y) ** 2)
histories = {}
for lr in [0.003, 0.03, 0.3, 0.38]:
w = np.zeros(A.shape[1])
hist = []
for _ in range(80):
hist.append(np.mean((A @ w - y) ** 2))
w = w - lr * 2 / len(y) * A.T @ (A @ w - y)
histories[lr] = np.array(hist)
# TODO: def diagnose(history) and the fastest converged rate
Hint 1

Compare history[-1] with history[0] first, then with best * 1.01.

Hint 2

For the speed, np.argmax(history <= best * 1.001) gives the first iteration within 0.1%. Check that such an iteration exists at all with np.any(...).

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "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(Z)), Z])
y = houses["price"].to_numpy() / 1000
w_best, *_ = np.linalg.lstsq(A, y)
best = np.mean((A @ w_best - y) ** 2)
histories = {}
for lr in [0.003, 0.03, 0.3, 0.38]:
w = np.zeros(A.shape[1])
hist = []
for _ in range(80):
hist.append(np.mean((A @ w - y) ** 2))
w = w - lr * 2 / len(y) * A.T @ (A @ w - y)
histories[lr] = np.array(hist)
def diagnose(history: np.ndarray) -> str:
if history[-1] > history[0]:
return "diverged"
if history[-1] > best * 1.01:
return "too slow"
return "converged"
speed = {}
for lr, hist in histories.items():
label = diagnose(hist)
close = hist <= best * 1.001
first = int(np.argmax(close)) if close.any() else None
print(f"lr = {lr}: {label}, within 0.1% at iteration {first}")
if label == "converged" and first is not None:
speed[lr] = first
fastest = min(speed, key=speed.get)
print("fastest converged rate:", fastest)
assert diagnose(histories[0.38]) == "diverged"
assert fastest == 0.3
Output
lr = 0.003: too slow, within 0.1% at iteration None
lr = 0.03: too slow, within 0.1% at iteration None
lr = 0.3: converged, within 0.1% at iteration 25
lr = 0.38: diverged, within 0.1% at iteration None
fastest converged rate: 0.3

How it works:

  1. diagnose turns a whole curve into a word with two comparisons: last versus first (divergence), last versus the optimum (speed).
  2. 0.003 and 0.03 are too slow for 80 iterations. 0.3 reaches the optimum quickly. 0.38 is above the stability limit of about 0.36 from the lesson, so it diverges.
  3. The interpretation: the best rate sits just below the stability limit. In practice you try rates on a log grid (0.003, 0.03, 0.3) and keep the largest one whose loss curve falls smoothly.

M32-C12 · Conditional churn probabilities by payment method

Section titled “M32-C12 · Conditional churn probabilities by payment method”
Core

From data/customers.csv, compute P(churn∣payment method)P(\text{churn} \mid \text{payment method}) for each payment method with boolean masks, and P(electronic check∣churn)P(\text{electronic check} \mid \text{churn}). Then show with the formula P(A∣B)=P(A and B)/P(B)P(A \mid B) = P(A \text{ and } B) / P(B) that you get the same value for electronic checks. Print the values with 3 decimals, sorted from the highest churn rate.

Expected output
P(churn | electronic_check) = 0.248
P(churn | paypal ) = 0.174
P(churn | bank_transfer ) = 0.174
P(churn | credit_card ) = 0.158
P(electronic_check | churn) = 0.402
formula check: 0.248
Starter
customers = pd.read_csv("data/customers.csv")
churned = customers["churned"].to_numpy() == 1
method = customers["payment_method"].to_numpy()
# TODO: for each method m: churned[method == m].mean()
# TODO: P(electronic_check | churn) and the check with the formula
Hint 1

np.unique(method) lists the methods. A mask such as method == "paypal" keeps the rows where the condition holds.

Hint 2

P(churn and e-check)P(\text{churn and e-check}) is (churned & echeck).mean(), and P(e-check)P(\text{e-check}) is echeck.mean().

Solution
customers = pd.read_csv("data/customers.csv")
churned = customers["churned"].to_numpy() == 1
method = customers["payment_method"].to_numpy()
rates = {m: churned[method == m].mean() for m in np.unique(method)}
for m, rate in sorted(rates.items(), key=lambda item: -item[1]):
print(f"P(churn | {m:16}) = {rate:.3f}")
echeck = method == "electronic_check"
print(f"P(electronic_check | churn) = {echeck[churned].mean():.3f}")
by_formula = (churned & echeck).mean() / echeck.mean()
print(f"formula check: {by_formula:.3f}")
assert np.isclose(by_formula, rates["electronic_check"])
assert rates["electronic_check"] > churned.mean() > rates["credit_card"]
Output
P(churn | electronic_check) = 0.248
P(churn | paypal ) = 0.174
P(churn | bank_transfer ) = 0.174
P(churn | credit_card ) = 0.158
P(electronic_check | churn) = 0.402
formula check: 0.248

How it works:

  1. Each mask keeps one group; the mean of the churn flags in that group is the conditional probability.
  2. Electronic-check customers churn at 24.8%, credit-card customers at 15.8%. The overall rate, 19.3%, lies between.
  3. P(e-check∣churn)P(\text{e-check} \mid \text{churn}) answers a different question: of all churners, 40% pay by electronic check.
  4. The formula divides the share of “both” by the share of the condition, which is the same as counting inside the group.

Alternative: customers.groupby("payment_method")["churned"].mean() gives the conditional churn rates in one line, and pd.crosstab(..., normalize="columns") gives P(method∣churn)P(\text{method} \mid \text{churn}).

Core

A mail server sees 10% spam. The word “free” appears in 40% of spam emails and in 2% of normal emails. Compute P(spam∣"free")P(\text{spam} \mid \text{"free"}) with Bayes’ rule. Then check it with a simulation: draw 200,000 emails with np.random.default_rng(42), decide for each one whether it is spam and whether it contains “free”, and count. Print both values with 3 decimals.

Expected output
Bayes' rule: P(spam | free) = 0.690
simulation: P(spam | free) = 0.692 (11456 emails)
Starter
p_spam, p_free_spam, p_free_ham = 0.10, 0.40, 0.02
# TODO: posterior with Bayes' rule
rng = np.random.default_rng(42)
n = 200_000
# TODO: is_spam = rng.random(n) < p_spam
# TODO: has_free depends on is_spam; count P(spam | free)
Hint 1

The evidence is P(free)=P(free∣spam)P(spam)+P(free∣ham)P(ham)P(\text{free}) = P(\text{free} \mid \text{spam})P(\text{spam}) + P(\text{free} \mid \text{ham})P(\text{ham}).

Hint 2

np.where(is_spam, p_free_spam, p_free_ham) gives each email its own probability of containing “free”. Compare it with a second rng.random(n).

Solution
p_spam, p_free_spam, p_free_ham = 0.10, 0.40, 0.02
evidence = p_free_spam * p_spam + p_free_ham * (1 - p_spam)
posterior = p_free_spam * p_spam / evidence
print(f"Bayes' rule: P(spam | free) = {posterior:.3f}")
rng = np.random.default_rng(42)
n = 200_000
is_spam = rng.random(n) < p_spam
has_free = rng.random(n) < np.where(is_spam, p_free_spam, p_free_ham)
simulated = is_spam[has_free].mean()
print(f"simulation: P(spam | free) = {simulated:.3f} ({has_free.sum()} emails)")
assert np.isclose(posterior, 0.04 / 0.058)
assert abs(simulated - posterior) < 0.01
Output
Bayes' rule: P(spam | free) = 0.690
simulation: P(spam | free) = 0.692 (11456 emails)

How it works:

  1. The evidence is 0.04 + 0.018 = 0.058: 5.8% of all emails contain “free”.
  2. The posterior is 0.04 / 0.058 ≈ 0.690. One word raises the spam probability from 10% to 69%.
  3. The simulation draws spam flags, then a “free” flag with the right probability for each email, and counts inside the “free” group. With 200,000 emails it agrees with the formula to about 2 decimals; the assert allows a difference of 0.01.
  4. A real naive Bayes filter (module 36 and module 41) multiplies such likelihoods for every word, assuming the words are independent given the class.

M32-C14 · Maximum likelihood for a conversion rate

Section titled “M32-C14 · Maximum likelihood for a conversion rate”
Core

data/ab_test.csv holds an A/B test of a checkout page. Model each user’s conversion as a coin flip with probability pp. For each group, compute the log-likelihood on a grid of pp from 0.001 to 0.999 (step 0.001) and print the pp with the highest log-likelihood next to the group’s conversion rate.

Expected output
control : MLE on grid 0.101, conversion rate 0.1012
treatment: MLE on grid 0.117, conversion rate 0.1166
Starter
ab = pd.read_csv("data/ab_test.csv")
grid = np.linspace(0.001, 0.999, 999)
# TODO: for each group: y = converted as float
# TODO: log-likelihood for every p on the grid, without a Python loop over p
Hint 1

With kk conversions out of nn users, the log-likelihood is klog⁡p+(n−k)log⁡(1−p)k \log p + (n - k)\log(1 - p). This works on the whole grid at once.

Hint 2

grid[np.argmax(log_lik)] is the best pp on the grid.

Solution
ab = pd.read_csv("data/ab_test.csv")
grid = np.linspace(0.001, 0.999, 999)
for group, rows in ab.groupby("group"):
y = rows["converted"].to_numpy(dtype=float)
k, n = y.sum(), len(y)
log_lik = k * np.log(grid) + (n - k) * np.log(1 - grid)
best = grid[np.argmax(log_lik)]
print(f"{group:9}: MLE on grid {best:.3f}, conversion rate {y.mean():.4f}")
assert abs(best - y.mean()) <= 0.0005 + 1e-12
Output
control : MLE on grid 0.101, conversion rate 0.1012
treatment: MLE on grid 0.117, conversion rate 0.1166

How it works:

  1. The likelihood of independent coin flips multiplies pp for every conversion and 1−p1 - p for every other user. Its log is the sum klog⁡p+(n−k)log⁡(1−p)k \log p + (n - k)\log(1 - p).
  2. NumPy evaluates the formula for all 999 grid values at once.
  3. The maximum lies at the conversion rate of each group (to the grid step). For a coin-flip model, the maximum likelihood estimate is the sample proportion.
  4. Module 29 tested whether the two rates differ. Maximum likelihood gives the estimates; a test or a confidence interval tells you how sure you can be.

M32-X01 · Gradient descent with a stopping rule

Section titled “M32-X01 · Gradient descent with a stopping rule”
Challenge

Write fit_gd(A, y, lr, tol, max_iter) that runs batch gradient descent on the MSE until the L2 norm of the gradient falls below tol (or max_iter is reached) and returns the weights and the number of iterations. Use the five lesson features plus has_pool, standardized, with a column of ones, and price in thousand USD. Run it with tol=1e-7 for lr = 0.1 and 0.3. Show that both results match np.linalg.lstsq within atol=1e-6.

Expected output
lstsq: [476.466 218.629 -18.964 26.104 68.02 -83.098 55.163]
lr = 0.1: 873 iterations, largest difference 3.5e-07
lr = 0.3: 285 iterations, largest difference 3.4e-07
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km",
"has_pool"]
# TODO: standardized design matrix A and y
# TODO: def fit_gd(A, y, lr, tol=1e-7, max_iter=10_000) -> (w, iterations)
# TODO: compare with lstsq for lr = 0.1 and 0.3
Hint 1

Compute the gradient at the top of the loop, test np.linalg.norm(grad) < tol, and return early. If the loop ends without returning, return max_iter.

Hint 2

A small gradient norm means a flat spot. For a convex loss like the MSE, the only flat spot is the minimum.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km",
"has_pool"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
A = np.column_stack([np.ones(len(Z)), Z])
y = houses["price"].to_numpy() / 1000
def fit_gd(A: np.ndarray, y: np.ndarray, lr: float, tol: float = 1e-7,
max_iter: int = 10_000) -> tuple[np.ndarray, int]:
w = np.zeros(A.shape[1])
for iteration in range(max_iter):
grad = 2 / len(y) * A.T @ (A @ w - y)
if np.linalg.norm(grad) < tol:
return w, iteration
w = w - lr * grad
return w, max_iter
w_ls, *_ = np.linalg.lstsq(A, y)
print("lstsq:", w_ls.round(3))
for lr in [0.1, 0.3]:
w, iters = fit_gd(A, y, lr)
diff = np.max(np.abs(w - w_ls))
print(f"lr = {lr}: {iters} iterations, largest difference {diff:.1e}")
assert iters < 10_000
assert np.allclose(w, w_ls, rtol=0, atol=1e-6)
Output
lstsq: [476.466 218.629 -18.964 26.104 68.02 -83.098 55.163]
lr = 0.1: 873 iterations, largest difference 3.5e-07
lr = 0.3: 285 iterations, largest difference 3.4e-07

How it works:

  1. The stopping rule uses the gradient itself: at the minimum the gradient is the zero vector, so its norm measures how far from flat you still are.
  2. With a three times larger learning rate, the loop needs about three times fewer iterations, because each step covers more ground in the slow directions.
  3. Both runs land within 1e-6 of the closed-form weights, and the pool adds a positive weight. The gradient tolerance (1e-7) is tighter than the weight tolerance on purpose: near the minimum, the distance to the best weights is roughly the gradient norm divided by the smallest curvature (about 0.2 here).

Alternative: stop when the loss improves by less than a relative amount, for example prev - loss < 1e-12 * prev. scikit-learn’s iterative models use a tol parameter of this kind.

M32-X02 · Refactor into a class: LinearRegressionGD

Section titled “M32-X02 · Refactor into a class: LinearRegressionGD”
Challenge

Refactor procedural code into a class. Write LinearRegressionGD in the style of the minilearn library of Part 3 and of scikit-learn: __init__(lr, n_epochs, batch_size=None, random_state=42), fit(X, y) that standardizes X with the training statistics and runs batch (batch_size=None) or mini-batch gradient descent, and predict(X). Store mean_, scale_, coef_ (per standardized feature), intercept_ and loss_history_. Split the houses 80/20 with a seeded permutation, fit a batch and a mini-batch model on the five lesson features, and print their test RMSE next to the lstsq solution.

Expected output
test RMSE lstsq 197.98
test RMSE batch 197.98
test RMSE mini 198.08
batch coef_: [232.33 -21.21 26.75 71.47 -84.2 ] intercept_: 478.95
Starter
class LinearRegressionGD:
def __init__(self, lr=0.1, n_epochs=100, batch_size=None, random_state=42):
...
def fit(self, X, y):
# TODO: standardize with the training mean and std, add learned attributes
# TODO: loop over epochs; one step (batch) or many steps (mini-batch)
return self
def predict(self, X):
# TODO: standardize with the stored statistics, then a matrix-vector product
...
Hint 1

Keep the intercept separate from coef_: the gradient for the intercept is 2 * mean(error) and the gradient for the weights is 2 / n * Z.T @ error.

Hint 2

predict must use self.mean_ and self.scale_ from fit, never statistics of the test data. Otherwise test rows are scaled differently from training rows.

Hint 3

For mini-batches, create rng = np.random.default_rng(self.random_state) once in fit, and call rng.permutation(n) at the start of each epoch.

Solution
class LinearRegressionGD:
"""Linear regression trained with (mini-)batch gradient descent on the MSE."""
def __init__(self, lr: float = 0.1, n_epochs: int = 100,
batch_size: int | None = None, random_state: int = 42) -> None:
self.lr = lr
self.n_epochs = n_epochs
self.batch_size = batch_size
self.random_state = random_state
def fit(self, X: np.ndarray, y: np.ndarray) -> "LinearRegressionGD":
self.mean_ = X.mean(axis=0)
self.scale_ = X.std(axis=0)
Z = (X - self.mean_) / self.scale_
n, p = Z.shape
self.coef_ = np.zeros(p)
self.intercept_ = 0.0
self.loss_history_ = []
rng = np.random.default_rng(self.random_state)
size = n if self.batch_size is None else self.batch_size
for _ in range(self.n_epochs):
order = rng.permutation(n) if self.batch_size else np.arange(n)
for batch in np.array_split(order, max(n // size, 1)):
error = Z[batch] @ self.coef_ + self.intercept_ - y[batch]
self.coef_ -= self.lr * 2 / len(batch) * Z[batch].T @ error
self.intercept_ -= self.lr * 2 * error.mean()
self.loss_history_.append(np.mean((self._raw(Z) - y) ** 2))
return self
def _raw(self, Z: np.ndarray) -> np.ndarray:
return Z @ self.coef_ + self.intercept_
def predict(self, X: np.ndarray) -> np.ndarray:
return self._raw((X - self.mean_) / self.scale_)
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
y = houses["price"].to_numpy() / 1000
order = np.random.default_rng(42).permutation(len(y))
train, test = order[:2400], order[2400:]
def rmse(model_pred: np.ndarray) -> float:
return float(np.sqrt(np.mean((model_pred - y[test]) ** 2)))
batch = LinearRegressionGD(lr=0.3, n_epochs=300).fit(X[train], y[train])
mini = LinearRegressionGD(lr=0.01, n_epochs=20, batch_size=32).fit(X[train], y[train])
Z_train = (X[train] - batch.mean_) / batch.scale_
A_train = np.column_stack([np.ones(len(train)), Z_train])
w_ls, *_ = np.linalg.lstsq(A_train, y[train])
A_test = np.column_stack([np.ones(len(test)), (X[test] - batch.mean_) / batch.scale_])
print(f"test RMSE lstsq {rmse(A_test @ w_ls):.2f}")
print(f"test RMSE batch {rmse(batch.predict(X[test])):.2f}")
print(f"test RMSE mini {rmse(mini.predict(X[test])):.2f}")
print("batch coef_:", batch.coef_.round(2), "intercept_:", round(batch.intercept_, 2))
assert np.allclose(np.r_[batch.intercept_, batch.coef_], w_ls, rtol=0, atol=1e-6)
assert abs(rmse(mini.predict(X[test])) - rmse(A_test @ w_ls)) < 5
Output
test RMSE lstsq 197.98
test RMSE batch 197.98
test RMSE mini 198.08
batch coef_: [232.33 -21.21 26.75 71.47 -84.2 ] intercept_: 478.95

How it works:

  1. fit learns the scaling from the training rows only and stores it, so predict scales new rows the same way. This is the leakage rule of module 33 in code.
  2. One loop serves both modes. With batch_size=None, there is one “batch” per epoch holding all rows in order. Otherwise, each epoch shuffles and cuts mini-batches.
  3. The batch model matches lstsq within 1e-6, so its test RMSE is identical. The mini-batch model’s test RMSE is within 0.1k USD of it after 20 epochs: close, not exact.
  4. The learned attributes end with an underscore (coef_, mean_), the scikit-learn convention from module 18.

Alternative: scikit-learn’s SGDRegressor inside a Pipeline with StandardScaler does the same job with a learning-rate schedule; module 34 rebuilds minilearn on top of scikit-learn’s base classes.

M32-X03 · Logistic regression from scratch with a test set

Section titled “M32-X03 · Logistic regression from scratch with a test set”
Challenge

Predict churn from tenure_months, logins_last_30d, support_tickets, monthly_charges, has_autopay and a 0/1 column month_to_month (contract is month-to-month). Split the 5,000 customers 75/25 with a seeded permutation. Standardize with the training statistics, train logistic regression with batch gradient descent on the log loss (lr=1.0, 2,000 iterations), and report the test log loss, the test log loss of the base rate, and the test accuracy at a 0.5 threshold. Check your weights against LogisticRegression(C=np.inf) on the same training data.

Expected output
weights: [-1.989 -0.773 -0.382 0.525 0.448 -0.218 0.643]
test log loss, model: 0.3884
test log loss, base rate: 0.4891
test accuracy at 0.5: 0.828
accuracy of 'never churn': 0.808
largest difference from sklearn: 4.5e-09
Starter
customers = pd.read_csv("data/customers.csv")
customers["month_to_month"] = (customers["contract"] == "month-to-month").astype(int)
cols = ["tenure_months", "logins_last_30d", "support_tickets",
"monthly_charges", "has_autopay", "month_to_month"]
# TODO: X, y, a 75/25 split with np.random.default_rng(42).permutation
# TODO: standardize with train mean/std, add a column of ones
# TODO: gradient descent on log loss; test log loss, base-rate log loss, accuracy
# TODO: compare with sklearn LogisticRegression(C=np.inf)
Hint 1

The gradient is A.T @ (sigmoid(A @ w) - y) / len(y). The base-rate model predicts the training churn rate for every test customer.

Hint 2

Fit scikit-learn on the standardized training features without the column of ones; it adds its own intercept. Then compare np.r_[model.intercept_, model.coef_[0]] with your weights.

Solution
from sklearn.linear_model import LogisticRegression
customers = pd.read_csv("data/customers.csv")
customers["month_to_month"] = (customers["contract"] == "month-to-month").astype(int)
cols = ["tenure_months", "logins_last_30d", "support_tickets",
"monthly_charges", "has_autopay", "month_to_month"]
X = customers[cols].to_numpy(dtype=float)
y = customers["churned"].to_numpy(dtype=float)
order = np.random.default_rng(42).permutation(len(y))
train, test = order[:3750], order[3750:]
mu, sd = X[train].mean(axis=0), X[train].std(axis=0)
def design(rows: np.ndarray) -> np.ndarray:
return np.column_stack([np.ones(len(rows)), (X[rows] - mu) / sd])
def sigmoid(z: np.ndarray) -> np.ndarray:
return 1 / (1 + np.exp(-z))
def log_loss(y_true: np.ndarray, p: np.ndarray) -> float:
p = np.clip(p, 1e-15, 1 - 1e-15)
return float(-np.mean(y_true * np.log(p) + (1 - y_true) * np.log(1 - p)))
A_train, A_test = design(train), design(test)
w = np.zeros(A_train.shape[1])
for _ in range(2000):
w -= 1.0 * A_train.T @ (sigmoid(A_train @ w) - y[train]) / len(train)
p_test = sigmoid(A_test @ w)
base = np.full(len(test), y[train].mean())
print("weights:", w.round(3))
print(f"test log loss, model: {log_loss(y[test], p_test):.4f}")
print(f"test log loss, base rate: {log_loss(y[test], base):.4f}")
print(f"test accuracy at 0.5: {np.mean((p_test >= 0.5) == y[test]):.3f}")
print(f"accuracy of 'never churn': {np.mean(y[test] == 0):.3f}")
model = LogisticRegression(C=np.inf, tol=1e-10, max_iter=1000)
model.fit(A_train[:, 1:], y[train])
w_sk = np.r_[model.intercept_, model.coef_[0]]
print(f"largest difference from sklearn: {np.max(np.abs(w_sk - w)):.1e}")
assert np.allclose(w, w_sk, rtol=0, atol=1e-4)
assert log_loss(y[test], p_test) < log_loss(y[test], base)
Output
weights: [-1.989 -0.773 -0.382 0.525 0.448 -0.218 0.643]
test log loss, model: 0.3884
test log loss, base rate: 0.4891
test accuracy at 0.5: 0.828
accuracy of 'never churn': 0.808
largest difference from sklearn: 4.5e-09

How it works:

  1. design standardizes any rows with the training statistics and adds the ones column, so the test set never influences the scaling.
  2. The loop is the update rule with the log-loss gradient. np.clip in log_loss guards against log(0).
  3. The model beats the base rate clearly on the test set, and month-to-month contracts get the largest positive weight.
  4. Accuracy at 0.5 looks high, but predicting “never churn” for everyone already gets almost as much (last line). That is why module 36 prefers log loss, ROC-AUC and precision/recall for imbalanced classes.

M32-X04 · Ridge regression: closed form and gradient descent

Section titled “M32-X04 · Ridge regression: closed form and gradient descent”
Challenge

Ridge regression minimizes 1n∥Aw−y∥22+λ∥w1:∥22\frac{1}{n}\lVert A\mathbf{w} - \mathbf{y}\rVert_2^2 + \lambda \lVert \mathbf{w}_{1:} \rVert_2^2, where w1:\mathbf{w}_{1:} are the weights without the intercept. Its closed form is (A⊤A+nλD) w=A⊤y(A^\top A + n\lambda D)\,\mathbf{w} = A^\top \mathbf{y}, with DD the identity matrix whose first diagonal entry is 0. On the five standardized lesson features:

  1. Solve the closed form with np.linalg.solve for λ\lambda = 0, 0.1, 1 and 10, and print the L2 norm of the feature weights for each.
  2. For λ=1\lambda = 1, run gradient descent with the penalized gradient 2nA⊤(Aw−y)+2λDw\frac{2}{n}A^\top(A\mathbf{w} - \mathbf{y}) + 2\lambda D\mathbf{w} and show that it matches the closed form within atol=1e-6.
Expected output
lambda 0: |w| = 256.24, weights [230.1 -18.3 26.4 68.9 -83.4]
lambda 0.1: |w| = 199.03, weights [169.4 19. 40. 60.6 -72.8]
lambda 1: |w| = 111.82, weights [ 77.3 45.2 48.5 31.1 -34. ]
lambda 10: |w| = 29.86, weights [18.8 15.4 15.7 5.9 -4.7]
GD vs closed form (lambda 1): 2.1e-14
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
# TODO: standardized design matrix A, y in thousand USD, n
# TODO: D = np.eye(6) with D[0, 0] = 0
# TODO: closed form for each lambda; norm of w[1:]
# TODO: gradient descent with the penalty for lambda = 1
Hint 1

np.linalg.solve(A.T @ A + n * lam * D, A.T @ y) is the whole closed form. With lam = 0 it is ordinary least squares.

Hint 2

The penalty adds curvature, so the stable learning rate is a bit smaller than without it. 0.2 is safe for λ=1\lambda = 1.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "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(Z)), Z])
y = houses["price"].to_numpy() / 1000
n = len(y)
D = np.eye(A.shape[1])
D[0, 0] = 0 # do not penalize the intercept
solutions = {}
for lam in [0, 0.1, 1, 10]:
w = np.linalg.solve(A.T @ A + n * lam * D, A.T @ y)
solutions[lam] = w
size = np.linalg.norm(w[1:])
print(f"lambda {lam:>4}: |w| = {size:7.2f}, weights {w[1:].round(1)}")
w = np.zeros(A.shape[1])
for _ in range(2000):
grad = 2 / n * A.T @ (A @ w - y) + 2 * 1.0 * D @ w
w = w - 0.2 * grad
print(f"GD vs closed form (lambda 1): {np.max(np.abs(w - solutions[1])):.1e}")
assert np.allclose(w, solutions[1], rtol=0, atol=1e-6)
norms = [np.linalg.norm(solutions[lam][1:]) for lam in [0, 0.1, 1, 10]]
assert norms == sorted(norms, reverse=True)
Output
lambda 0: |w| = 256.24, weights [230.1 -18.3 26.4 68.9 -83.4]
lambda 0.1: |w| = 199.03, weights [169.4 19. 40. 60.6 -72.8]
lambda 1: |w| = 111.82, weights [ 77.3 45.2 48.5 31.1 -34. ]
lambda 10: |w| = 29.86, weights [18.8 15.4 15.7 5.9 -4.7]
GD vs closed form (lambda 1): 2.1e-14

How it works:

  1. The penalty adds nλDn\lambda D to A⊤AA^\top A: setting the gradient to zero gives this linear system. solve handles it like any other.
  2. As λ\lambda grows, the norm of the feature weights shrinks: the penalty pulls every weight toward 0. The intercept stays at the mean price because DD leaves it out.
  3. The correlated trio sqft/bedrooms/bathrooms changes most. Least squares gives sqft almost all the credit and bedrooms a negative weight. Ridge spreads the credit more evenly among correlated features, so the bedroom weight is already positive at λ=0.1\lambda = 0.1.
  4. Gradient descent with the penalized gradient reaches the same weights within 1e-6.

Alternative: sklearn.linear_model.Ridge(alpha=n * lam) on the standardized features gives the same weights, because scikit-learn’s loss uses the sum of squares instead of the mean. Module 35 covers Ridge, Lasso and ElasticNet.

M32-X05 · Nearest-neighbor prices with L1 and L2 distances

Section titled “M32-X05 · Nearest-neighbor prices with L1 and L2 distances”
Challenge

Estimate house prices with 5 nearest neighbors, written with NumPy only. Split the houses into 2,400 training and 600 test rows with np.random.default_rng(42).permutation. For each test house, predict the mean price of its 5 nearest training houses. Compare four variants: raw or standardized features (standardized with training statistics), and L2 or L1 distance. Print the test MAE in thousand USD of each variant. Use the features sqft, bedrooms, bathrooms, condition, distance_to_center_km and school_rating (fill the 90 missing ratings with the training median).

Expected output
raw L2: MAE 124.9
raw L1: MAE 117.6
standardized L2: MAE 88.1
standardized L1: MAE 88.1
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km",
"school_rating"]
# TODO: X with the missing school ratings filled by the training median, y in k USD
# TODO: def knn_predict(X_train, y_train, X_test, k, ord)
# distances with broadcasting: X_test[:, None, :] - X_train[None, :, :]
# TODO: MAE for raw/standardized x L2/L1
Hint 1

X_test[:, None, :] - X_train[None, :, :] has shape (600, 2400, 6). np.linalg.norm(..., ord=..., axis=2) turns it into a (600, 2400) distance matrix.

Hint 2

np.argsort(dist, axis=1)[:, :k] gives the positions of the k nearest training houses for every test house. y_train[positions].mean(axis=1) averages their prices.

Hint 3

Compute the median and the standardization statistics on the training rows only, then apply them to both sets.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km",
"school_rating"]
X = houses[cols].to_numpy(dtype=float)
y = houses["price"].to_numpy() / 1000
order = np.random.default_rng(42).permutation(len(y))
train, test = order[:2400], order[2400:]
median_rating = np.nanmedian(X[train, 5])
X[:, 5] = np.where(np.isnan(X[:, 5]), median_rating, X[:, 5])
def knn_predict(X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray,
k: int = 5, norm_ord: int = 2) -> np.ndarray:
diff = X_test[:, None, :] - X_train[None, :, :]
dist = np.linalg.norm(diff, ord=norm_ord, axis=2)
nearest = np.argsort(dist, axis=1, kind="stable")[:, :k]
return y_train[nearest].mean(axis=1)
mu, sd = X[train].mean(axis=0), X[train].std(axis=0)
variants = {"raw": X, "standardized": (X - mu) / sd}
maes = {}
for name, data in variants.items():
for norm_ord in (2, 1):
pred = knn_predict(data[train], y[train], data[test], k=5, norm_ord=norm_ord)
maes[(name, norm_ord)] = np.mean(np.abs(pred - y[test]))
print(f"{name:12} L{norm_ord}: MAE {maes[(name, norm_ord)]:.1f}")
assert maes[("standardized", 2)] < maes[("raw", 2)]
assert np.isnan(X).sum() == 0
Output
raw L2: MAE 124.9
raw L1: MAE 117.6
standardized L2: MAE 88.1
standardized L1: MAE 88.1

How it works:

  1. Broadcasting builds all 600 × 2,400 difference vectors at once (8.6 million numbers, about 70 MB, fine for a laptop). For bigger data, process the test rows in chunks or use scikit-learn’s tree-based neighbor search.
  2. norm(..., axis=2) collapses the feature axis into one distance per pair. argsort along axis=1 ranks the training houses for each test house.
  3. On raw features, the distance is essentially a sqft distance, and the error is large. Standardizing lets distance and school rating count, which lowers the MAE from about 125 to 88.
  4. On standardized features, L1 and L2 give the same MAE here. On raw features, L1 does better, because it lets the small features count a little more against the large sqft differences.

Alternative: KNeighborsRegressor(n_neighbors=5, p=1) in a Pipeline with SimpleImputer(strategy="median") and StandardScaler (modules 34 and 35) computes the same predictions.