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:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script, for example
exercise.py. Replace each to-do comment with your code. - Run the script with
python exercise.pyfrom your project folder (the one that holdsdata/). Compare your output with the expected output. - 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 npimport pandas as pd
np.set_printoptions(precision=3, suppress=True)Warm-up
Section titled “Warm-up”M32-W01 · Build a feature vector
Section titled “M32-W01 · Build a feature vector”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.
H0005 [3170. 4. 3.5 1972. ](4,)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 shapeHint 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] == 1972H0005 [3170. 4. 3.5 1972. ](4,)How it works:
- The boolean mask finds the row label of H0005 (4), so the code does not depend on the row order.
.loc[row, features]picks the four features in the order of the list, and.to_numpy(dtype=float)makes a float vector.- 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”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.
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[3. 4.5 8. ][ 2. 2. 12.][ 3. 7.5 10. ][2. 8. 3.]16.0How it works:
a + badds position by position: 2 + 1, 4 + 0.5, 6 + 2.a * bmultiplies position by position. It is not a dot product.2 * a - bscalesaby 2 first (precedence), then subtractsb.a / bdivides position by position: 4 / 0.5 is 8.a @ bis 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”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.
loop: 1008.95dot: 1008.95quantities = 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 bothHint 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.0for q, price in zip(quantities, prices, strict=True): loop_total += q * pricedot_total = quantities @ pricesprint(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)loop: 1008.95dot: 1008.95How it works:
- The loop multiplies each quantity by its price and adds the result to a running total.
quantities @ pricesdoes the same in one vectorized operation.- 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.
M32-W04 · Distance between two customers
Section titled “M32-W04 · Distance between two customers”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.
L2: 7.365L1: 12.500c1 = 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=1Hint 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 - c1l2 = 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))L2: 7.365L1: 12.500How it works:
dis[-5, 3, 4.5]: how customer 2 differs from customer 1 in each feature.- L2 squares each difference, adds them (25 + 9 + 20.25) and takes the square root.
- L1 adds the absolute differences: 5 + 3 + 4.5 = 12.5.
- 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”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, conditionscores = X @ weightsprint(scores[:3])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)(3000, 4) (4,)[656.5 462. 392. ]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 scoresHint 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, conditionprint(X.shape, weights.shape)scores = X @ weightsprint(scores[:3])assert scores.shape == (len(houses),)assert np.isclose(scores[0], 0.2 * 2420 + 5 * 4 + 15 * 3.5 + 25 * 4)(3000, 4) (4,)[656.5 462. 392. ]How it works:
Xhad 3 columns butweightshad 4 elements. The inner sizes of(3000, 3) @ (4,)differ, so NumPy raised the error.- The weights describe four features, so the fix adds the missing
conditioncolumn toX. - 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.
M32-W06 · A numerical derivative
Section titled “M32-W06 · A numerical derivative”The loss of a one-weight model is . Compute its derivative at in two ways: the central difference with h = 1e-5, and the analytic derivative from the chain rule. Print both with 4 decimals. Then print the derivative at .
numerical at 1: -18.0000analytic at 1: -18.0000analytic at 2: 0.0000def 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 = 2Hint 1
The central difference is (f(w + h) - f(w - h)) / (2 * h).
Hint 2
Chain rule: the outer function is with slope , the inner function is with slope 3. So .
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-5numerical = (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) == 0numerical at 1: -18.0000analytic at 1: -18.0000analytic at 2: 0.0000How it works:
- At , , so the analytic derivative is . The negative slope says “increase ”.
- The central difference nudges by a tiny amount in both directions and measures the rise over the run. It matches.
- At , : 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”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.
values: [0 1 2 3]probs: [0.155 0.361 0.376 0.108]E = 1.4373, Var = 0.7721houses = 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
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 @ probsvariance = ((values - expected) ** 2) @ probsprint("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())values: [0 1 2 3]probs: [0.155 0.361 0.376 0.108]E = 1.4373, Var = 0.7721How it works:
np.unique(..., return_counts=True)returns the distinct values and how often each occurs.- The probabilities are the shares. Their sum is 1.
- 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 .
- The variance is the expected squared distance from the mean. NumPy’s
.var()uses the same population formula (divide by ).
M32-W08 · From scores to probabilities and odds
Section titled “M32-W08 · From scores to probabilities and odds”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 . Print the probabilities and the odds with 3 decimals. Check that the log of the odds gives the scores back.
probabilities: [0.119 0.5 0.953]odds: [ 0.135 1. 20.086]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
. NumPy’s np.exp works on whole arrays.
Hint 2
The odds of 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))probabilities: [0.119 0.5 0.953]odds: [ 0.135 1. 20.086]How it works:
- The sigmoid maps −2 to 0.119, 0 to 0.5 and 3 to 0.953. Higher scores mean higher churn probability.
- The odds compare “churn” to “stay”: 0.119 / 0.881 ≈ 0.135, so about 1 to 7.4.
- The odds equal , so the log of the odds is the score. That is why the score is called the log-odds.
M32-C01 · Standardize a data matrix
Section titled “M32-C01 · Standardize a data matrix”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).
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]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 stdsHint 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) / sigmaprint("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)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:
muandsigmahave shape(4,), one value per column.(X - mu) / sigmabroadcasts the two vectors over all 3,000 rows: every row is standardized at once.- H0001 was built in 2016, about 1.1 standard deviations newer than the average house.
- 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”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.
R00010 [1 1 0 0 0 1]R00070 [1 1 0 0 0 1] 1.000R00151 [1 1 0 0 0 1] 1.000R00284 [1 1 0 0 0 0] 0.816R00074 [0 1 0 0 0 0] 0.577R00095 [1 0 0 0 0 0] 0.577R00143 [1 0 0 0 0 0] 0.577R00175 [1 0 0 1 0 0] 0.408R00156 [0 0 1 0 1 0] 0.000reviews = 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 lowHint 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))R00010 [1 1 0 0 0 1]R00070 [1 1 0 0 0 1] 1.000R00151 [1 1 0 0 0 1] 1.000R00284 [1 1 0 0 0 0] 0.816R00074 [0 1 0 0 0 0] 0.577R00095 [1 0 0 0 0 0] 0.577R00143 [1 0 0 0 0 0] 0.577R00175 [1 0 0 1 0 0] 0.408R00156 [0 0 1 0 1 0] 0.000How it works:
- Each review becomes a vector of 6 word counts. R00010 mentions the battery, the quality and “recommend”.
M @ qcomputes the 8 dot products at once. Dividing by the row norms and the query norm turns them into cosines.- Counts are never negative, so every cosine lies between 0 and 1.
- 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.
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”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.
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])[ 156 1104 1905 2763 1890]H0157 0.059H1105 0.119H1906 0.233H2764 0.240H1891 0.241houses = 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 distancesHint 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] == 0H0157 0.059H1105 0.119H1906 0.233H2764 0.240H1891 0.241How it works:
- Broadcasting subtracts the query from all 3,000 rows in one step.
axis=1takes the norm along each row, sodisthas one entry per house.argsortsorts positions by distance. Position 0 is H0001 itself (distance 0), so the slice starts at 1.- 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”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.
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(4, 2)(4,)(3, 3)(2, 4)()(4, 3)errorHow it works:
(4, 3) @ (3, 2)→(4, 2).(4, 3) @ (3,)→(4,): one value per row, the “predict for every row” shape.(3, 4) @ (4, 3)→(3, 3): the shape.(2, 3) @ (3, 4)→(2, 4), which is . The assert checks the rule .v @ vis a dot product: a NumPy scalar with the empty shape().A * vbroadcasts: the shape stays(4, 3).(3, 2) @ (4, 3): the inner sizes 2 and 4 differ, so NumPy raisesValueError.
M32-C05 · Predict every house price with one product
Section titled “M32-C05 · Predict every house price with one product”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.
MAE: 134.6 thousand USDwithin 20%: 43.3%neighborhoodLakeview -323.2Oak Hill -236.2Riverside 14.1Maple Grove 29.3Downtown 63.9Old Town 91.8Cedar Park 97.1Westfield 110.6houses = 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 neighborhoodHint 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 = 50X = houses[cols].to_numpy(dtype=float)y = houses["price"].to_numpy() / 1000y_hat = X @ weights + baseerror = y_hat - ymae = 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"MAE: 134.6 thousand USDwithin 20%: 43.3%neighborhoodLakeview -323.2Oak Hill -236.2Riverside 14.1Maple Grove 29.3Downtown 63.9Old Town 91.8Cedar Park 97.1Westfield 110.6How it works:
X @ weights + basemakes 3,000 predictions with one product.- The MAE averages the absolute errors, so over- and underpricing do not cancel.
- The boolean array
np.abs(error) / y <= 0.2isTruefor good predictions; its mean is their share. - 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”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:
- 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. - Fit price (thousand USD) = sqft for all houses in
data/houses.csv. - 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.
1. unit prices: [ 79.99 249. 1299. ]2. intercept and per-sqft weight: [-130.345 0.327]3. same weights: Trueunits = 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 formulaHint 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() / 1000A = 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 @ yprint("3. same weights:", np.allclose(w, w_inv))assert np.allclose(units @ prices, revenue)assert np.allclose(prices, [79.99, 249.00, 1299.00])1. unit prices: [ 79.99 249. 1299. ]2. intercept and per-sqft weight: [-130.345 0.327]3. same weights: TrueHow it works:
- solve for problem 1: the system is square with a unique answer, and
solvefinds it without forming an inverse. The prices are the list prices of P001, P002 and P003. - lstsq for problem 2: the system is tall (3,000 rows, 2 unknowns).
lstsqminimizes the squared error directly fromA. The slope is about 0.33k USD (327 USD) per sqft. - 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”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.
307 houses, weights: [-414.192 0.563 54.391]RMSE 212.5, R² 0.7882,000 sqft without / with pool: [712.4 766.8]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 predictionsHint 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() / 1000w, *_ = np.linalg.lstsq(A, y)y_hat = A @ wrmse = 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] > 0assert np.isclose((new @ w)[1] - (new @ w)[0], w[2])307 houses, weights: [-414.192 0.563 54.391]RMSE 212.5, R² 0.7882,000 sqft without / with pool: [712.4 766.8]How it works:
- 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.
- 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.
- Two new houses are two rows of a small design matrix.
new @ wpredicts 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”The model is price (thousand USD) size (thousand sqft) distance (km). Its loss is the MSE plus a Ridge penalty on the two feature weights (not on the intercept), with :
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.
analytic: [ -281.562 2294.229 -2192.332]numerical: [ -281.562 2294.229 -2192.332]relative error below 1e-7: Truehouses = pd.read_csv("data/houses.csv")X = np.column_stack([houses["sqft"] / 1000, houses["distance_to_center_km"]])y = houses["price"].to_numpy() / 1000lam = 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 with a column of ones in A.
Hint 2
By the power and constant-factor rules, . The intercept 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() / 1000lam = 10.0A = np.column_stack([np.ones(len(y)), X]) # columns: 1, size, distancemask = 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-4analytic = 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-7assert np.isclose(analytic[0], 2 * np.mean(A @ params - y)) # b has no penalty termanalytic: [ -281.562 2294.229 -2192.332]numerical: [ -281.562 2294.229 -2192.332]relative error below 1e-7: TrueHow it works:
- The derivation, one rule at a time. With the error , the chain rule gives the slope of as times the slope of , which is 1 for , for and for . The sum rule and the factor average these. The power rule adds for the two penalized weights:
maskis 0 for the intercept and 1 for the weights, so one vectorized line adds the penalty slope to the right entries only.- The numerical gradient nudges one parameter at a time, which is what “partial” means. The relative error is tiny, so the derivation is right.
- The second assert checks that the intercept’s slope has no penalty part.
Alternative: write the penalty with the matrix 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.
M32-C09 · The chain rule inside log loss
Section titled “M32-C09 · The chain rule inside log loss”For one customer, logistic regression computes , and the log loss . The chain rule gives and . Check both numerically for two customers: and , with and .
x=1.5, y=1: p=0.7109 dL/dz -0.2891 vs -0.2891 dL/dw -0.4336 vs -0.4336x=-0.5, y=0: p=0.3318 dL/dz 0.3318 vs 0.3318 dL/dw -0.1659 vs -0.1659w, 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 differencesHint 1
The chain is . Write one function that takes and one that takes , then nudge the input.
Hint 2
The derivative of the sigmoid is . Multiplied with , most terms cancel and leave .
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-6for 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)x=1.5, y=1: p=0.7109 dL/dz -0.2891 vs -0.2891 dL/dw -0.4336 vs -0.4336x=-0.5, y=0: p=0.3318 dL/dz 0.3318 vs 0.3318 dL/dw -0.1659 vs -0.1659How it works:
- The chain rule multiplies three slopes: . The first two multiply to , a remarkably simple result.
- For the churner (), is negative: raising the score lowers the loss.
- For the customer who stays (), is positive: lowering the score lowers the loss.
- Averaged over all customers, becomes the gradient of the lesson.
M32-C10 · Fix the bug: the loss goes up
Section titled “M32-C10 · Fix the bug: the loss goes up”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() / 1000w, b, lr = 0.0, 0.0, 0.1for 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)0 32858710 1082588250 232838933161880 32858710 5068350 47442w = 232.65, b = 476.46houses = pd.read_csv("data/houses.csv")sqft = houses["sqft"].to_numpy(dtype=float)z = (sqft - sqft.mean()) / sqft.std()y = houses["price"].to_numpy() / 1000w, b, lr = 0.0, 0.0, 0.1# TODO: fix the update, print the loss at steps 0, 10, 50 and the final w, bHint 1
The gradient points uphill. Which way should the step go?
Hint 2
The update rule is . 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() / 1000w, b, lr = 0.0, 0.0, 0.1losses = []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)0 32858710 5068350 47442w = 232.65, b = 476.46How it works:
- The buggy code added the gradient, so every step went uphill and the loss grew.
- With
-, each step goes against the gradient and the loss falls. - With a standardized feature, the intercept converges to the mean price (476.47) and 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”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.
lr = 0.003: too slow, within 0.1% at iteration Nonelr = 0.03: too slow, within 0.1% at iteration Nonelr = 0.3: converged, within 0.1% at iteration 25lr = 0.38: diverged, within 0.1% at iteration Nonefastest converged rate: 0.3houses = 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() / 1000w_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 rateHint 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() / 1000w_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] = firstfastest = min(speed, key=speed.get)print("fastest converged rate:", fastest)assert diagnose(histories[0.38]) == "diverged"assert fastest == 0.3lr = 0.003: too slow, within 0.1% at iteration Nonelr = 0.03: too slow, within 0.1% at iteration Nonelr = 0.3: converged, within 0.1% at iteration 25lr = 0.38: diverged, within 0.1% at iteration Nonefastest converged rate: 0.3How it works:
diagnoseturns a whole curve into a word with two comparisons: last versus first (divergence), last versus the optimum (speed).- 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.
- 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”From data/customers.csv, compute for each payment method with boolean masks, and . Then show with the formula that you get the same value for electronic checks. Print the values with 3 decimals, sorted from the highest churn rate.
P(churn | electronic_check) = 0.248P(churn | paypal ) = 0.174P(churn | bank_transfer ) = 0.174P(churn | credit_card ) = 0.158P(electronic_check | churn) = 0.402formula check: 0.248customers = pd.read_csv("data/customers.csv")churned = customers["churned"].to_numpy() == 1method = customers["payment_method"].to_numpy()# TODO: for each method m: churned[method == m].mean()# TODO: P(electronic_check | churn) and the check with the formulaHint 1
np.unique(method) lists the methods. A mask such as method == "paypal" keeps the rows where the condition holds.
Hint 2
is (churned & echeck).mean(), and is echeck.mean().
Solution
customers = pd.read_csv("data/customers.csv")churned = customers["churned"].to_numpy() == 1method = 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"]P(churn | electronic_check) = 0.248P(churn | paypal ) = 0.174P(churn | bank_transfer ) = 0.174P(churn | credit_card ) = 0.158P(electronic_check | churn) = 0.402formula check: 0.248How it works:
- Each mask keeps one group; the mean of the churn flags in that group is the conditional probability.
- Electronic-check customers churn at 24.8%, credit-card customers at 15.8%. The overall rate, 19.3%, lies between.
- answers a different question: of all churners, 40% pay by electronic check.
- 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 .
M32-C13 · Bayes’ rule in a spam filter
Section titled “M32-C13 · Bayes’ rule in a spam filter”A mail server sees 10% spam. The word “free” appears in 40% of spam emails and in 2% of normal emails. Compute 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.
Bayes' rule: P(spam | free) = 0.690simulation: P(spam | free) = 0.692 (11456 emails)p_spam, p_free_spam, p_free_ham = 0.10, 0.40, 0.02# TODO: posterior with Bayes' rulerng = 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 .
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.02evidence = p_free_spam * p_spam + p_free_ham * (1 - p_spam)posterior = p_free_spam * p_spam / evidenceprint(f"Bayes' rule: P(spam | free) = {posterior:.3f}")
rng = np.random.default_rng(42)n = 200_000is_spam = rng.random(n) < p_spamhas_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.01Bayes' rule: P(spam | free) = 0.690simulation: P(spam | free) = 0.692 (11456 emails)How it works:
- The evidence is 0.04 + 0.018 = 0.058: 5.8% of all emails contain “free”.
- The posterior is 0.04 / 0.058 ≈ 0.690. One word raises the spam probability from 10% to 69%.
- 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.
- 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”data/ab_test.csv holds an A/B test of a checkout page. Model each user’s conversion as a coin flip with probability . For each group, compute the log-likelihood on a grid of from 0.001 to 0.999 (step 0.001) and print the with the highest log-likelihood next to the group’s conversion rate.
control : MLE on grid 0.101, conversion rate 0.1012treatment: MLE on grid 0.117, conversion rate 0.1166ab = 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 pHint 1
With conversions out of users, the log-likelihood is . This works on the whole grid at once.
Hint 2
grid[np.argmax(log_lik)] is the best 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-12control : MLE on grid 0.101, conversion rate 0.1012treatment: MLE on grid 0.117, conversion rate 0.1166How it works:
- The likelihood of independent coin flips multiplies for every conversion and for every other user. Its log is the sum .
- NumPy evaluates the formula for all 999 grid values at once.
- 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.
- 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.
Challenge
Section titled “Challenge”M32-X01 · Gradient descent with a stopping rule
Section titled “M32-X01 · Gradient descent with a stopping rule”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.
lstsq: [476.466 218.629 -18.964 26.104 68.02 -83.098 55.163]lr = 0.1: 873 iterations, largest difference 3.5e-07lr = 0.3: 285 iterations, largest difference 3.4e-07houses = 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.3Hint 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)lstsq: [476.466 218.629 -18.964 26.104 68.02 -83.098 55.163]lr = 0.1: 873 iterations, largest difference 3.5e-07lr = 0.3: 285 iterations, largest difference 3.4e-07How it works:
- 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.
- 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.
- Both runs land within
1e-6of 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”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.
test RMSE lstsq 197.98test RMSE batch 197.98test RMSE mini 198.08batch coef_: [232.33 -21.21 26.75 71.47 -84.2 ] intercept_: 478.95class 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() / 1000order = 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)) < 5test RMSE lstsq 197.98test RMSE batch 197.98test RMSE mini 198.08batch coef_: [232.33 -21.21 26.75 71.47 -84.2 ] intercept_: 478.95How it works:
fitlearns the scaling from the training rows only and stores it, sopredictscales new rows the same way. This is the leakage rule of module 33 in code.- 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. - The batch model matches
lstsqwithin1e-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. - 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”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.
weights: [-1.989 -0.773 -0.382 0.525 0.448 -0.218 0.643]test log loss, model: 0.3884test log loss, base rate: 0.4891test accuracy at 0.5: 0.828accuracy of 'never churn': 0.808largest difference from sklearn: 4.5e-09customers = 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)weights: [-1.989 -0.773 -0.382 0.525 0.448 -0.218 0.643]test log loss, model: 0.3884test log loss, base rate: 0.4891test accuracy at 0.5: 0.828accuracy of 'never churn': 0.808largest difference from sklearn: 4.5e-09How it works:
designstandardizes any rows with the training statistics and adds the ones column, so the test set never influences the scaling.- The loop is the update rule with the log-loss gradient.
np.clipinlog_lossguards againstlog(0). - The model beats the base rate clearly on the test set, and month-to-month contracts get the largest positive weight.
- 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”Ridge regression minimizes , where are the weights without the intercept. Its closed form is , with the identity matrix whose first diagonal entry is 0. On the five standardized lesson features:
- Solve the closed form with
np.linalg.solvefor = 0, 0.1, 1 and 10, and print the L2 norm of the feature weights for each. - For , run gradient descent with the penalized gradient and show that it matches the closed form within
atol=1e-6.
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-14houses = 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 = 1Hint 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 .
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() / 1000n = 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 * gradprint(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)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-14How it works:
- The penalty adds to : setting the gradient to zero gives this linear system.
solvehandles it like any other. - As grows, the norm of the feature weights shrinks: the penalty pulls every weight toward 0. The intercept stays at the mean price because leaves it out.
- 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 .
- 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”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).
raw L2: MAE 124.9raw L1: MAE 117.6standardized L2: MAE 88.1standardized L1: MAE 88.1houses = 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/L1Hint 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() / 1000order = 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() == 0raw L2: MAE 124.9raw L1: MAE 117.6standardized L2: MAE 88.1standardized L1: MAE 88.1How it works:
- 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.
norm(..., axis=2)collapses the feature axis into one distance per pair.argsortalongaxis=1ranks the training houses for each test house.- 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.
- 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.