Skip to content

32. Math for ML

This module starts Part 5. Every model in the rest of the course is built from a few ideas: a row of data is a vector, a prediction is a dot product, an error is a distance, and training is walking downhill on a loss. You do not need a math background. Each idea comes in three steps: the intuition in plain words, then NumPy code on the course data, then the formula. The code and the formula always compute the same number, so you can check one against the other.

  • Treat a house as a feature vector and a dataset as a matrix, and compute sums, dot products, norms, distances and cosine similarity with NumPy.
  • Predict for every row with one matrix–vector product, read and check matrix shapes, and solve a least-squares problem with np.linalg.solve and np.linalg.lstsq instead of an inverse.
  • Explain derivatives, partial derivatives, gradients and the chain rule as slopes, and check an analytic gradient against a numerical one.
  • Write gradient descent from scratch for linear regression, choose a learning rate from a loss curve, and confirm the result against the closed-form solution.
  • Use expectation, variance, conditional probability, Bayes’ rule and likelihood, and read logistic regression as a probability model with the sigmoid and log loss.

You need school arithmetic only: adding, multiplying, squares and square roots. The module explains everything else.

The lesson page runs top to bottom, so start with one setup block. It loads NumPy and pandas, sets NumPy to print 3 decimals without scientific notation, and reads the houses.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.set_printoptions(precision=3, suppress=True)
houses = pd.read_csv("data/houses.csv")

A formula is a short way to write a loop. The sum sign ∑\sum means “add up”, and the small letters around it say what to add. When a formula looks hard, read the code next to it first. The code is the same idea in a language you already know.

Symbol Read it as NumPy
xix_i “x sub i”: element number ii of x\mathbf{x} x[i - 1] (math counts from 1, Python from 0)
x\mathbf{x} (bold, lowercase) a vector a 1-D array, shape (p,)
XX (capital) a matrix a 2-D array, shape (n, p)
∑i=1nxi\sum_{i=1}^{n} x_i add x1,x2,…,xnx_1, x_2, \dots, x_n x.sum()
y^\hat{y} “y hat”: a predicted value y_pred
X⊤X^\top “X transposed” X.T
∥x∥\lVert \mathbf{x} \rVert the length (norm) of x\mathbf{x} np.linalg.norm(x)
dLdw\frac{dL}{dw} the derivative (slope) of LL with respect to ww a number
∇L\nabla L “nabla L”: the gradient of LL an array of slopes
P(A∣B)P(A \mid B) the probability of AA given BB a[b].mean() for boolean arrays
E[T]\mathbb{E}[T] the expected value of TT values @ probs

A vector is an ordered list of numbers (module 23 used the word for a 1-D array). In machine learning, one row of data becomes a feature vector: a vector with one position per feature. The order is fixed, so position 0 always means the same feature.

House H0001 in data/houses.csv has 2,420 sqft, 4 bedrooms, 3.5 bathrooms, condition 4 (on a scale of 1 to 5) and a distance of 7.9 km to the city center. As a feature vector:

features = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
x1 = houses.loc[0, features].to_numpy(dtype=float)
print(houses.loc[0, "house_id"], x1)
print(x1.shape, x1.ndim)
Output
H0001 [2420. 4. 3.5 4. 7.9]
(5,) 1

The vector has 5 numbers, so its shape is (5,). Math writes a vector in bold, x=(x1,x2,…,xp)\mathbf{x} = (x_1, x_2, \dots, x_p), where pp is the number of features. Geometrically, a vector is a point (or an arrow from the origin to that point) in a space with pp axes. You cannot draw 5 axes, but every rule in this module works the same in 2, 5 or 5,000 dimensions.

You add two vectors of the same length element by element. You multiply a vector by a number (a scalar) by multiplying every element. NumPy does both without a loop:

x2 = houses.loc[1, features].to_numpy(dtype=float) # house H0002
print("x2 - x1:", x2 - x1)
print("midpoint:", (x1 + x2) / 2)
print("in m², ...:", x1 * np.array([0.0929, 1, 1, 1, 1]))
Output
x2 - x1: [-810. -2. -1.5 0. 3.6]
midpoint: [2015. 3. 2.75 4. 9.7 ]
in m², ...: [224.818 4. 3.5 4. 7.9 ]

The difference x2 - x1 says how H0002 differs from H0001 in each feature: 810 sqft smaller, 2 bedrooms fewer, 3.6 km farther out. The midpoint is the average house of the two. The last line converts the first element from sqft to m² with an element-wise product.

In math notation, for two vectors with pp elements and a scalar cc:

u+v=(u1+v1,…,up+vp)c u=(c u1,…,c up)\mathbf{u} + \mathbf{v} = (u_1 + v_1, \dots, u_p + v_p) \qquad c\,\mathbf{u} = (c\,u_1, \dots, c\,u_p)

Standardization (module 18) is vector arithmetic too. Subtract the vector of column means μ\boldsymbol{\mu}, then divide by the vector of column standard deviations σ\boldsymbol{\sigma}, element by element:

X = houses[features].to_numpy(dtype=float)
mu = X.mean(axis=0)
sigma = X.std(axis=0)
z1 = (x1 - mu) / sigma
print("mu: ", mu)
print("sigma:", sigma)
print("z1: ", z1)
Output
mu: [1856.637 3.017 2.624 3.012 8.562]
sigma: [711.831 1.275 0.908 0.953 5.197]
z1: [ 0.791 0.772 0.965 1.037 -0.127]

After standardization, every feature is measured in “standard deviations from the average house”. H0001 is about 0.8 standard deviations above average in size and close to average in distance. The numbers are now on one scale, which matters for distances and for gradient descent later in this module. As a formula, where the division is element by element:

z=x−μσ\mathbf{z} = \frac{\mathbf{x} - \boldsymbol{\mu}}{\boldsymbol{\sigma}}

The picture shows the same rules in 2 dimensions: adding two arrows puts them end to end, and multiplying by 2 doubles the length without changing the direction.

u = np.array([2.0, 1.0])
v = np.array([0.5, 2.0])
fig, ax = plt.subplots(figsize=(5, 4))
arrows = [(2 * u, "2u", "tab:purple", 2), (u + v, "u + v", "tab:green", 2),
(v, "v", "tab:orange", 2), (u, "u", "tab:blue", 4)]
for vec, label, color, width in arrows:
ax.annotate("", xy=vec, xytext=(0, 0),
arrowprops={"arrowstyle": "->", "color": color, "lw": width})
ax.text(vec[0] + 0.05, vec[1] - 0.25, label, color=color)
ax.plot([u[0], u[0] + v[0]], [u[1], u[1] + v[1]], "--", color="gray")
ax.set_xlim(0, 4.5)
ax.set_ylim(0, 3.5)
ax.set_aspect("equal")
ax.set_xlabel("feature 1")
ax.set_ylabel("feature 2")
ax.set_title("Vector addition and scalar multiplication")
plt.show()
Four arrows from the origin: u to (2, 1), v to (0.5, 2), u + v to (2.5, 3) reached by placing v at the tip of u, and 2u to (4, 2) pointing the same way as u but twice as long.
Adding vectors puts arrows end to end; a scalar changes the length.

A real estate agent has a rule of thumb for the price of a house, in thousands of USD: start at 50, add 0.2 per sqft, 5 per bedroom, 15 per bathroom and 25 per condition point, and subtract 10 per km from the center. To price a house, you multiply each feature by its weight and add the results. That operation is the dot product. Here is the same score three ways: a loop, an element-wise product with a sum, and the @ operator.

weights = np.array([0.2, 5, 15, 25, -10]) # thousand USD per unit of each feature
base = 50
total = 0.0
for w_i, x_i in zip(weights, x1, strict=True):
total += w_i * x_i
print("loop: ", round(base + total, 2))
print("sum(w*x): ", round(base + np.sum(weights * x1), 2))
print("w @ x: ", round(base + weights @ x1, 2))
print("real price:", houses.loc[0, "price"] / 1000)
Output
loop: 627.5
sum(w*x): 627.5
w @ x: 627.5
real price: 1097.5

All three give the same score. The rule of thumb says about 628k USD, but H0001 sold for 1,097.5k USD: it is in Lakeview, the most expensive neighborhood, and the rule ignores the neighborhood. This formula, a base value plus a dot product, is a linear model. Every linear model in this course (linear regression, logistic regression, the first layer of a neural network) computes a dot product. Training means finding good weights from data instead of guessing them. The base value is called the intercept or bias: the prediction when every feature is 0.

In math notation, the dot product of a weight vector w\mathbf{w} and a feature vector x\mathbf{x} is:

w⋅x=∑i=1pwi xi=w1x1+w2x2+⋯+wpxp\mathbf{w} \cdot \mathbf{x} = \sum_{i=1}^{p} w_i\,x_i = w_1 x_1 + w_2 x_2 + \dots + w_p x_p

A norm measures the length of a vector. Two norms appear everywhere in ML:

  • The L2 norm (Euclidean norm) is the straight-line length, from the theorem of Pythagoras: ∥x∥2=∑ixi2\lVert \mathbf{x} \rVert_2 = \sqrt{\sum_i x_i^2}.
  • The L1 norm (Manhattan norm) adds the absolute values, like walking along the streets of a grid city: ∥x∥1=∑i∣xi∣\lVert \mathbf{x} \rVert_1 = \sum_i \lvert x_i \rvert.

The norm of a difference is a distance. The Euclidean distance between two houses is ∥x2−x1∥2\lVert \mathbf{x}_2 - \mathbf{x}_1 \rVert_2, and the Manhattan distance is ∥x2−x1∥1\lVert \mathbf{x}_2 - \mathbf{x}_1 \rVert_1.

diff = x2 - x1
print("by hand L2:", round(np.sqrt(np.sum(diff**2)), 3))
print("norm L2: ", round(np.linalg.norm(diff), 3))
print("by hand L1:", round(np.sum(np.abs(diff)), 3))
print("norm L1: ", round(np.linalg.norm(diff, ord=1), 3))
Output
by hand L2: 810.012
norm L2: 810.012
by hand L1: 817.1
norm L1: 817.1

Both distances are about 810, which is almost exactly the sqft difference. The other four features hardly count, because sqft is measured in hundreds and bedrooms in ones. A distance on raw features is a distance in sqft. Standardize first, and every feature counts in the same unit:

z2 = (x2 - mu) / sigma
print("standardized diff:", z2 - z1)
print("L2 distance:", round(np.linalg.norm(z2 - z1), 3))
Output
standardized diff: [-1.138 -1.569 -1.652 0. 0.693]
L2 distance: 2.639

Now the bedrooms (−1.6 standard deviations), the bathrooms (−1.7) and the distance (+0.7) count as much as the size (−1.1). Models that compare rows by distance, such as k-nearest neighbors (module 35) and k-means (module 39), need scaled features for this reason.

A unit vector has length 1. Divide a vector by its L2 norm to get the unit vector that points the same way: v / np.linalg.norm(v).

Norms also control model size. Regularization adds a penalty on the size of the weights to the training loss, so that the model prefers small weights and does not chase noise. Ridge regression adds λ∥w∥22\lambda \lVert \mathbf{w} \rVert_2^2 and Lasso adds λ∥w∥1\lambda \lVert \mathbf{w} \rVert_1, where λ\lambda (lambda) sets the strength of the penalty. The two penalties judge weights differently:

w_spread = np.array([1.0, 1.0, 1.0, 1.0])
w_sparse = np.array([2.0, 0.0, 0.0, 0.0])
for name, w in [("spread", w_spread), ("sparse", w_sparse)]:
print(f"{name}: L2 squared = {np.sum(w**2):.1f}, L1 = {np.sum(np.abs(w)):.1f}")
Output
spread: L2 squared = 4.0, L1 = 4.0
sparse: L2 squared = 4.0, L1 = 2.0

The squared L2 penalty is 4 for both. The L1 penalty is smaller for the sparse vector (a vector with many zeros). So the L1 penalty rewards setting weights exactly to 0, which is why Lasso drops features. Module 35 uses both penalties.

Norm Formula NumPy Used for
L2 (Euclidean) ∑ixi2\sqrt{\sum_i x_i^2} np.linalg.norm(x) straight-line distance, KNN, k-means, Ridge, the length of a gradient
squared L2 ∑ixi2\sum_i x_i^2 x @ x MSE, Ridge penalty (no square root, easy to differentiate)
L1 (Manhattan) ∑i∣xi∣\sum_i \lvert x_i \rvert np.linalg.norm(x, ord=1) distances robust to one big difference, MAE, Lasso
max (L-infinity) max⁡i∣xi∣\max_i \lvert x_i \rvert np.linalg.norm(x, ord=np.inf) worst-case difference, tolerance checks

Cosine similarity: the angle between two vectors

Section titled “Cosine similarity: the angle between two vectors”

The dot product has a second meaning. For two vectors u\mathbf{u} and v\mathbf{v} with angle θ\theta between them:

u⋅v=∥u∥2 ∥v∥2cos⁡θ\mathbf{u} \cdot \mathbf{v} = \lVert \mathbf{u} \rVert_2 \, \lVert \mathbf{v} \rVert_2 \cos\theta

Divide the dot product by both lengths and you get the cosine similarity, which depends only on the direction:

cos⁡θ=u⋅v∥u∥2 ∥v∥2\cos\theta = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert_2 \, \lVert \mathbf{v} \rVert_2}

It is 1 when the vectors point the same way, 0 when they are at a right angle (nothing in common) and −1 when they point in opposite directions.

Cosine similarity compares texts. Count how often each word of a small vocabulary appears in a review, and each review becomes a vector. Here are four real reviews from data/reviews.csv:

reviews = pd.read_csv("data/reviews.csv", keep_default_na=False).set_index("review_id")
vocab = ["battery", "quality", "price", "delivery", "recommend"]
ids = ["R00070", "R00284", "R00243", "R00156"]
texts = [reviews.loc[i, "text"].lower() for i in ids]
counts = np.array([[text.count(word) for word in vocab] for text in texts])
for review_id, text, row in zip(ids, texts, counts, strict=True):
print(review_id, row, text[:60])
Output
R00070 [1 1 0 0 1] the battery charges fast and holds the charge. build quality
R00284 [1 1 0 0 0] the material quality feels solid & well made. the batter
R00243 [1 0 0 1 0] bought this for my son. the battery life is quite amazing. t
R00156 [0 0 1 0 0] the price point is way too high. however, customer service s

R00070 and R00284 both talk about the battery and the quality. R00243 talks about the battery and the delivery. R00156 talks about the price only. Compare R00070 with the others, and with a made-up review that is R00070 written twice:

def cosine(u: np.ndarray, v: np.ndarray) -> float:
return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))
query = counts[0]
others = {"R00284": counts[1], "R00243": counts[2], "R00156": counts[3],
"R00070 twice": 2 * query}
for name, vec in others.items():
print(f"{name:13} dot = {query @ vec}, cosine = {cosine(query, vec):.3f}")
Output
R00284 dot = 2, cosine = 0.816
R00243 dot = 1, cosine = 0.408
R00156 dot = 0, cosine = 0.000
R00070 twice dot = 6, cosine = 1.000

The doubled review has the largest dot product, but only because it is longer. Its cosine is exactly 1: same words, same proportions. R00284 shares two topics (cosine 0.816), R00243 shares one (0.408) and R00156 shares none (0). Cosine similarity ignores length and keeps the topic. Search engines, recommender systems and the text embeddings of module 41 rank results this way.

A matrix is a table of numbers with rows and columns (module 23). In ML, the data matrix XX stacks the feature vectors of all rows: row ii is house number ii, and column jj is feature number jj. With nn rows and pp features, XX has shape (n,p)(n, p), and xijx_{ij} is the value of feature jj for house ii.

print(X.shape)
print("row 0 (house H0001):", X[0])
print("column 0 (sqft), first 5:", X[:5, 0])
Output
(3000, 5)
row 0 (house H0001): [2420. 4. 3.5 4. 7.9]
column 0 (sqft), first 5: [2420. 1610. 1260. 1790. 3170.]

A row is one house. A column is one feature across all houses. The target, the price, is a separate vector y\mathbf{y} of length nn. scikit-learn uses the same convention: fit(X, y) with X of shape (n_samples, n_features).

Matrix–vector product: predict for every row

Section titled “Matrix–vector product: predict for every row”

The dot product priced one house. To price all 3,000, take the dot product of every row with the same weights. That is the matrix–vector product, X @ weights in NumPy:

y_rule = X @ weights + base # (3000, 5) @ (5,) -> (3000,)
print(y_rule.shape)
print("predicted:", y_rule[:4].round(1))
print("actual: ", houses["price"].to_numpy()[:4] / 1000)
print("row 0 again:", round(base + X[0] @ weights, 2))
Output
(3000,)
predicted: [627.5 397. 285. 533.5]
actual: [1097.5 486.5 223. 431. ]
row 0 again: 627.5

One line of code makes 3,000 predictions, one per row. Element 0 is the score of H0001 from the dot-product section. “Predict for every row” is the most common operation in ML, and it is always a matrix–vector product, or a matrix product when the model has several outputs. In math notation, with the hat marking predictions:

y^=Xw+bwherey^i=∑j=1pxij wj+b\hat{\mathbf{y}} = X\mathbf{w} + b \qquad \text{where} \qquad \hat{y}_i = \sum_{j=1}^{p} x_{ij}\,w_j + b

Matrix multiplication combines a matrix of shape (n,p)(n, p) with a matrix of shape (p,k)(p, k) and gives shape (n,k)(n, k). Each column of the result is the matrix–vector product with one column of the second matrix. So two pricing rules at once are one product:

rules = np.column_stack([weights, [0.25, 0, 10, 30, -12]]) # (5, 2): two rules
both = X @ rules # (3000, 5) @ (5, 2)
print(rules.shape, both.shape)
print(both[:3].round(1))
Output
(5, 2) (3000, 2)
[[577.5 665.2]
[347. 404.5]
[235. 266.6]]

Column 0 is the first rule (without the base of 50) and column 1 is a second rule. The shape rule: the inner sizes must match, and the outer sizes give the result.

Left Right Result Meaning
(n, p) (p,) (n,) one prediction per row
(n, p) (p, k) (n, k) k predictions per row
(p,) (p,) () a dot product: one number
(p, n) (n,) (p,) one sum per feature (the gradient shape, see below)
(n, p) (4,) with p = 5 error the inner sizes 5 and 4 differ

When the inner sizes differ, NumPy refuses:

print(X @ np.ones(4))
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 5)

Read the message as “the right operand needs 5 rows, it has 4”. Check shapes with print(A.shape, B.shape) before you multiply. Two more rules: matrix multiplication is not commutative (ABAB and BABA differ, and one may not even exist), and * is element-wise, not a matrix product.

The transpose X⊤X^\top turns rows into columns: an (n, p) matrix becomes (p, n). In NumPy it is X.T, a view with no copy. Two products with the transpose come back again and again:

  • X⊤XX^\top X has shape (p,p)(p, p). Entry (j,k)(j, k) adds up feature jj times feature kk over all rows. For standardized features, X⊤X/nX^\top X / n is the correlation matrix.
  • X⊤rX^\top \mathbf{r} has shape (p,)(p,). For each feature, it adds up the feature times a per-row number rir_i, such as the error of each prediction. This is the core of the gradient of linear regression.
Z = (X - mu) / sigma # every row standardized at once
n = len(Z)
print((Z.T @ Z / n).round(2))
print(np.allclose(Z.T @ Z / n, np.corrcoef(X, rowvar=False)))
Output
[[1. 0.85 0.85 0.06 0.1 ]
[0.85 1. 0.9 0.08 0.09]
[0.85 0.9 1. 0.08 0.09]
[0.06 0.08 0.08 1. 0.19]
[0.1 0.09 0.09 0.19 1. ]]
True

The diagonal is 1 (each feature with itself). Sqft, bedrooms and bathrooms correlate at 0.85 to 0.90: big houses have more rooms. The check against np.corrcoef is True. One more rule you will meet in derivations: (AB)⊤=B⊤A⊤(AB)^\top = B^\top A^\top (the order flips).

Identity, inverse, and why you solve instead of invert

Section titled “Identity, inverse, and why you solve instead of invert”

The identity matrix II (np.eye(p)) has 1 on the diagonal and 0 elsewhere. It is the “1” of matrices: AI=AAI = A. The inverse A−1A^{-1} of a square matrix undoes it: A−1A=IA^{-1}A = I (module 23). Check both rules on the correlation matrix of the five features, a well-behaved square matrix:

eye = np.eye(5) # the identity matrix I
R = Z.T @ Z / n # the correlation matrix from above
print("R @ I equals R: ", np.allclose(R @ eye, R))
print("inv(R) @ R equals I: ", np.allclose(np.linalg.inv(R) @ R, eye))
Output
R @ I equals R: True
inv(R) @ R equals I: True

Linear regression has a closed-form solution, a formula that gives the best weights in one step, with no iterations. The best weights satisfy the normal equations (module 23, Example 5):

X⊤X w=X⊤y⇒w=(X⊤X)−1X⊤yX^\top X \, \mathbf{w} = X^\top \mathbf{y} \qquad \Rightarrow \qquad \mathbf{w} = (X^\top X)^{-1} X^\top \mathbf{y}

The formula on the right is how textbooks write the answer. Do not compute it that way in code. Forming an inverse costs more work and loses accuracy, because rounding errors grow when the columns of XX are almost dependent. Instead:

  • np.linalg.solve(A, b) solves the square system Aw=bA\mathbf{w} = \mathbf{b} directly.
  • np.linalg.lstsq(X, y) solves the least-squares problem from XX itself, without forming X⊤XX^\top X at all. It also copes with columns that depend on each other.

To see the difference, build a data matrix with the area stored twice: in sqft and in m², with a tiny measurement noise. Such duplicates happen in real data after a join. The columns are almost dependent.

rng = np.random.default_rng(42)
y_k = houses["price"].to_numpy() / 1000 # price in thousand USD
sqm = X[:, 0] * 0.0929 + rng.normal(0, 0.01, n) # area again, in m²
A_dup = np.column_stack([np.ones(n), X[:, 0], sqm])
XtX, Xty = A_dup.T @ A_dup, A_dup.T @ y_k
w_inv = np.linalg.inv(XtX) @ Xty
w_solve = np.linalg.solve(XtX, Xty)
w_lstsq, *_ = np.linalg.lstsq(A_dup, y_k)
for name, w in [("inv", w_inv), ("solve", w_solve), ("lstsq", w_lstsq)]:
error = np.linalg.norm(XtX @ w - Xty) # how well w solves the equations
mse_w = np.mean((A_dup @ w - y_k) ** 2)
print(f"{name:5} equation error {error:.0e}, MSE {mse_w:,.1f}")
print(f"condition number of XtX: {np.linalg.cond(XtX):.0e}")
Output
inv equation error 1e+02, MSE 47,413.1
solve equation error 3e-06, MSE 47,413.1
lstsq equation error 2e-04, MSE 47,413.1
condition number of XtX: 4e+10

All three weight vectors predict equally well here: the MSE is the same. But the inverse solves the equations tens of millions of times less accurately than solve. On harder data, that error reaches the predictions. Do not worry that lstsq shows a larger equation error than solve. solve works on these equations directly, so it is judged on its own task. lstsq never forms them: it minimizes ∥Aw−y∥\lVert A\mathbf{w} - \mathbf{y} \rVert itself, and on that task, the MSE, it is as good as solve. On the original columns it is also the more robust method. The condition number (module 23) measures how much a matrix amplifies rounding errors; a condition number of 101010^{10} can cost about 10 of the 16 significant digits of a float. The exact tiny numbers depend on your CPU and NumPy build. The gap of several orders of magnitude does not.

A model learns by reducing its error. To reduce the error, it must know which way to change each weight. The derivative answers that question: it is the slope of a function at one point. A positive slope means “the output grows when the input grows”, a negative slope means “it shrinks”, and a slope of 0 means you are at a flat spot, such as a minimum.

Take the simplest price model: price (in thousand USD) =w×= w \times size (in thousand sqft), with one weight ww. The loss function turns the weight into one number that says how bad the predictions are. Here it is the mean squared error (module 03): the average of the squared prediction errors.

size_k = X[:, 0] / 1000 # thousand sqft
def loss(w: float) -> float:
return float(np.mean((w * size_k - y_k) ** 2))
for w in [100, 200, 250, 300]:
print(f"w = {w}: loss = {loss(w):,.0f}")
Output
w = 100: loss = 158,079
w = 200: loss = 66,647
w = 250: loss = 50,585
w = 300: loss = 54,291

The loss falls from w = 100 to w = 250, then rises again. Somewhere between 200 and 300 lies the best weight. The derivative tells you which way to go from any point. In math notation, with xix_i the size and yiy_i the price of house ii:

L(w)=1n∑i=1n(w xi−yi)2L(w) = \frac{1}{n} \sum_{i=1}^{n} (w\,x_i - y_i)^2

The derivative of LL at ww is the limit of “rise over run” for a smaller and smaller step hh:

L′(w)=dLdw=lim⁡h→0L(w+h)−L(w)hL'(w) = \frac{dL}{dw} = \lim_{h \to 0} \frac{L(w + h) - L(w)}{h}

There are two ways to get it. The numerical derivative uses a small hh in this formula. The central difference L(w+h)−L(w−h)2h\frac{L(w+h) - L(w-h)}{2h} is more accurate than the one-sided version, so use it. The analytic derivative is an exact formula that you work out with a few rules of calculus.

You need only a handful of rules in this course. You do not have to memorize them: each one can be checked with the central difference. The helper slope below estimates any derivative numerically, and each line compares it with the rule.

def slope(f, w: float, h: float = 1e-5) -> float:
"""Central-difference estimate of the derivative of f at w."""
return (f(w + h) - f(w - h)) / (2 * h)
checks = [
("power w**2 at 3", slope(lambda w: w**2, 3.0), 2 * 3.0),
("power w**3 at 2", slope(lambda w: w**3, 2.0), 3 * 2.0**2),
("constant 5 * w**2 at 3", slope(lambda w: 5 * w**2, 3.0), 5 * (2 * 3.0)),
("sum w**2 + 4*w at 3", slope(lambda w: w**2 + 4 * w, 3.0), 2 * 3.0 + 4),
("exp e**w at 1", slope(np.exp, 1.0), np.exp(1.0)),
("log log(w) at 4", slope(np.log, 4.0), 1 / 4.0),
("chain (3*w - 6)**2 at 1", slope(lambda w: (3 * w - 6) ** 2, 1.0),
2 * (3 * 1.0 - 6) * 3),
]
for name, numerical, rule in checks:
print(f"{name:28} numerical {numerical:8.4f} rule {rule:8.4f}")
Output
power w**2 at 3 numerical 6.0000 rule 6.0000
power w**3 at 2 numerical 12.0000 rule 12.0000
constant 5 * w**2 at 3 numerical 30.0000 rule 30.0000
sum w**2 + 4*w at 3 numerical 10.0000 rule 10.0000
exp e**w at 1 numerical 2.7183 rule 2.7183
log log(w) at 4 numerical 0.2500 rule 0.2500
chain (3*w - 6)**2 at 1 numerical -18.0000 rule -18.0000

Every rule agrees with the numerical slope. Here are the rules in words and symbols:

Rule In words Formula
power bring the power down, lower it by one ddwwk=k wk−1\frac{d}{dw} w^k = k\,w^{k-1}
constant factor a constant multiplies the slope ddwc f(w)=c f′(w)\frac{d}{dw} c\,f(w) = c\,f'(w)
sum the slope of a sum is the sum of the slopes (f+g)′=f′+g′(f + g)' = f' + g'
exponential ewe^w is its own slope ddwew=ew\frac{d}{dw} e^w = e^w
log the slope of the natural log is one over the input ddwlog⁡w=1w\frac{d}{dw} \log w = \frac{1}{w}
chain for a function inside a function, multiply the outer slope by the inner slope ddwf(u(w))=f′(u) u′(w)\frac{d}{dw} f(u(w)) = f'(u)\,u'(w)

The last row is the chain rule. The next sections use it often, and The chain rule explains it with a picture. In the example (3w−6)2(3w - 6)^2, the outer function is a square (slope 2u2u) and the inner one is u=3w−6u = 3w - 6 (slope 3), so the slope is 2(3w−6)⋅32(3w - 6) \cdot 3.

Now derive the slope of the loss in two lines. The sum rule and the constant factor 1n\frac{1}{n} let you take the slope of each squared error separately. Each squared error is a square of the inner function ui=w xi−yiu_i = w\,x_i - y_i, whose slope is xix_i, so the chain rule gives 2ui⋅xi2u_i \cdot x_i:

dLdw=1n∑i=1nddw(w xi−yi)2=2n∑i=1nxi (w xi−yi)\frac{dL}{dw} = \frac{1}{n} \sum_{i=1}^{n} \frac{d}{dw}(w\,x_i - y_i)^2 = \frac{2}{n} \sum_{i=1}^{n} x_i\,(w\,x_i - y_i)

Check it against the numerical slope on the houses:

def dloss(w: float) -> float:
return float(2 * np.mean(size_k * (w * size_k - y_k)))
w0, h = 200.0, 1e-3
numerical = (loss(w0 + h) - loss(w0 - h)) / (2 * h)
print(f"numerical: {numerical:.4f}")
print(f"analytic: {dloss(w0):.4f}")
best_w = np.sum(size_k * y_k) / np.sum(size_k**2) # where the slope is 0
print(f"best w: {best_w:.2f}")
print("slope there is 0:", np.isclose(dloss(best_w), 0, atol=1e-6))
Output
numerical: -518.9404
analytic: -518.9404
best w: 265.63
slope there is 0: True

The two derivatives agree to 4 decimals. The slope at w = 200 is negative, so increasing ww lowers the loss. At the best weight (about 266k USD per thousand sqft) the slope is 0. The plot shows the loss curve, the tangent line at w = 200 (a line with the slope of the derivative) and the minimum.

ws = np.linspace(100, 400, 200)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(ws, [loss(w) for w in ws], label="loss L(w)")
ax.plot(ws, loss(w0) + dloss(w0) * (ws - w0), "--", label="tangent at w = 200")
ax.scatter([w0, best_w], [loss(w0), loss(best_w)], color="black", zorder=3)
ax.annotate("minimum: slope 0", (best_w, loss(best_w)), xytext=(280, 120_000),
arrowprops={"arrowstyle": "->"})
ax.set_ylim(0, 300_000)
ax.set_xlabel("weight w (thousand USD per thousand sqft)")
ax.set_ylabel("mean squared error")
ax.legend()
plt.show()
A U-shaped loss curve over weights from 100 to 400 with its lowest point near w = 266. A dashed tangent line touches the curve at w = 200 and slopes downward, showing that a larger weight lowers the loss.
The derivative is the slope of the tangent line. It points away from the minimum.

Real models have many weights. Add an intercept to the size model: y^=w x+b\hat{y} = w\,x + b. The loss now depends on two numbers, L(w,b)L(w, b). A partial derivative is the slope in one direction while you hold the other inputs fixed. ∂L∂w\frac{\partial L}{\partial w} asks “what happens if I nudge only ww?” The curly ∂\partial just marks a partial derivative.

The gradient ∇L\nabla L collects all partial derivatives in one vector. It points in the direction in which the loss grows fastest, so its negative points downhill.

∇L=(∂L/∂w∂L/∂b)=2n∑i=1n(w xi+b−yi)(xi1)\nabla L = \begin{pmatrix} \partial L / \partial w \\ \partial L / \partial b \end{pmatrix} = \frac{2}{n} \sum_{i=1}^{n} (w\,x_i + b - y_i) \begin{pmatrix} x_i \\ 1 \end{pmatrix}
def loss2(w: float, b: float) -> float:
return float(np.mean((w * size_k + b - y_k) ** 2))
def grad2(w: float, b: float) -> np.ndarray:
error = w * size_k + b - y_k
return np.array([2 * np.mean(error * size_k), 2 * np.mean(error)])
w0, b0, h = 200.0, 50.0, 1e-3
numerical = np.array([
(loss2(w0 + h, b0) - loss2(w0 - h, b0)) / (2 * h), # nudge w only
(loss2(w0, b0 + h) - loss2(w0, b0 - h)) / (2 * h), # nudge b only
])
print("numerical:", numerical.round(3))
print("analytic: ", grad2(w0, b0).round(3))
Output
numerical: [-333.277 -110.276]
analytic: [-333.277 -110.276]

Each partial derivative is an ordinary derivative with the other parameter frozen. Both are negative here, so the loss falls when you raise ww or bb.

With pp features, put a column of ones in front of the data matrix, so that the intercept becomes weight number 0. Then the whole gradient is one line of matrix algebra:

∇L(w)=2nX⊤(Xw−y)\nabla L(\mathbf{w}) = \frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y})

Xw−yX\mathbf{w} - \mathbf{y} is the vector of errors, one per row. X⊤X^\top times it adds up “feature times error” for every feature at once: the (p, n) @ (n,) row of the shape table. Example 4 checks this formula numerically on five features.

Most loss functions are a function inside a function. For one house, the squared error is L=u2L = u^2, where u=w x−yu = w\,x - y is the error. The chain rule says: multiply the slopes along the chain.

dLdw=dLdu⋅dudw=2u⋅x\frac{dL}{dw} = \frac{dL}{du} \cdot \frac{du}{dw} = 2u \cdot x
flowchart LR
    W["w"] -->|"du/dw = x"| U["u = w·x − y"]
    U -->|"dL/du = 2u"| L["L = u²"]

Take H0001: x=2.42x = 2.42 (thousand sqft), y=1097.5y = 1097.5 (thousand USD) and w=300w = 300.

x, y, w = 2.42, 1097.5, 300.0
u = w * x - y # inner function: the error
dL_du = 2 * u # outer slope: derivative of u²
du_dw = x # inner slope: derivative of w·x − y
print(f"u = {u:.1f}, dL/du = {dL_du:.1f}, du/dw = {du_dw}")
print(f"chain rule: {dL_du * du_dw:.2f}")
h = 1e-4
print(f"numerical: {(((w + h) * x - y) ** 2 - ((w - h) * x - y) ** 2) / (2 * h):.2f}")
Output
u = -371.5, dL/du = -743.0, du/dw = 2.42
chain rule: -1798.06
numerical: -1798.06

The prediction is 371.5k USD too low, so uu is negative and the slope is negative: raise ww. The chain rule result matches the numerical slope. A neural network is a long chain of such functions. Backpropagation, the training algorithm of neural networks, is the chain rule applied from the loss back to every weight. PyTorch does it for you with autograd (module 42).

Imagine standing on a hillside in thick fog. You cannot see the valley, but you can feel the slope under your feet. Take a small step downhill, feel again, repeat. That is gradient descent (module 03 used it on one weight):

w←w−η ∇L(w)\mathbf{w} \leftarrow \mathbf{w} - \eta \, \nabla L(\mathbf{w})

The arrow means “replace by”. η\eta (eta) is the learning rate: the size of the step.

flowchart TB
    S["Start: w = 0"] --> P["Predict: Xw"]
    P --> G["Gradient: 2/n · Xᵀ(Xw − y)"]
    G --> U["Step: w = w − η · gradient"]
    U --> C{"Loss still falling?"}
    C -->|yes| P
    C -->|no| D["Done"]

Run it on the one-weight size model with three learning rates:

def descend(lr: float, steps: int = 6) -> list[float]:
w, path = 0.0, []
for _ in range(steps):
w = w - lr * dloss(w)
path.append(round(w, 1))
return path
for lr in [0.01, 0.1, 0.26]:
print(f"lr = {lr}: {descend(lr)}")
print(f"target: {best_w:.1f}")
Output
lr = 0.01: [21.0, 40.3, 58.2, 74.6, 89.7, 103.6]
lr = 0.1: [210.0, 254.0, 263.2, 265.1, 265.5, 265.6]
lr = 0.26: [546.1, -30.6, 578.4, -64.7, 614.4, -102.7]
target: 265.6
  • With 0.01 the steps are too small: after 6 steps ww is still far from 265.6.
  • With 0.1 it is within 3 of the target after 3 steps.
  • With 0.26 every step overshoots, and the overshoot grows: the weights jump from side to side and move away from the answer. This is divergence.

The safe learning rate depends on the curvature of the loss, and the curvature depends on the scale of the features. A feature measured in sqft (thousands) and one measured in bedrooms (ones) need very different step sizes, but gradient descent uses one learning rate for all weights. After standardization, all features have the same scale, the loss surface is closer to a round bowl, and one learning rate suits every weight. Always standardize before gradient descent. Example 5 does this on five features and draws the loss curves.

Stochastic and mini-batch gradient descent

Section titled “Stochastic and mini-batch gradient descent”

Batch gradient descent uses all nn rows to compute each gradient. With 3,000 rows that is cheap. With 30 million rows, one step reads the whole dataset. Two variants estimate the gradient from a sample of rows instead:

  • Stochastic gradient descent (SGD) uses one random row per step.
  • Mini-batch gradient descent uses a small random batch of rows per step, often 32 to 256.

Each estimate is noisy, but it costs a fraction of a full gradient, so the model makes many more steps in the same time. One pass over all rows is still one epoch (module 03). The usual recipe shuffles the row positions at the start of each epoch and cuts them into batches:

order = rng.permutation(n)
batches = np.array_split(order, n // 32)
print(len(batches), [len(b) for b in batches[:3]], len(batches[-1]))
Output
93 [33, 33, 33] 32

With batches of about 32 rows, one epoch is 93 steps instead of 1. np.array_split makes batches of nearly equal size, so no row is left out.

Variant Rows per step Steps per epoch (n = 3,000) Gradient Typical use
Batch all n 1 exact small data, convex problems, teaching
Mini-batch 32–256 about 11–93 noisy neural networks (PyTorch DataLoader), large data
Stochastic 1 3,000 very noisy streaming data, SGDRegressor, online learning

Random variables, expectation and variance

Section titled “Random variables, expectation and variance”

Machine learning predicts things that are uncertain: will a customer churn, will a review be positive? Probability is the language for that uncertainty. A random variable (module 29) is a number whose value depends on chance, such as the number of support tickets of a random customer.

The expected value (or expectation) E[T]\mathbb{E}[T] is the long-run average of a random variable: each possible value times its probability, added up. That is a dot product of the values and the probabilities. The variance is the expected squared distance from the mean (module 29).

customers = pd.read_csv("data/customers.csv")
tickets = customers["support_tickets"].to_numpy()
values, counts_t = np.unique(tickets, return_counts=True)
probs = counts_t / counts_t.sum()
print("values:", values)
print("P(T=k):", probs.round(4))
expected = values @ probs
variance = ((values - expected) ** 2) @ probs
print(f"E[T] = {expected:.4f}, mean = {tickets.mean():.4f}")
print(f"Var(T) = {variance:.4f}, var = {tickets.var():.4f}")
Output
values: [0 1 2 3 4 5 6 7 8 9]
P(T=k): [0.307 0.348 0.205 0.091 0.037 0.007 0.003 0. 0. 0. ]
E[T] = 1.2386, mean = 1.2386
Var(T) = 1.3713, var = 1.3713

The expected value from the probability table equals the plain mean of the column, and the variance equals .var(). They are two views of the same number. This is why ML losses are averages. The expected loss is the average error you expect on new data from the same source. The average loss on held-out data, rows the model never saw during training, estimates it. The training average underestimates it once the model is fitted to those rows, which is why modules 34 and 37 always keep a test set. In math notation:

E[T]=∑kk P(T=k)Var⁡(T)=E[(T−E[T])2]=∑k(k−E[T])2 P(T=k)\mathbb{E}[T] = \sum_k k \, P(T = k) \qquad \operatorname{Var}(T) = \mathbb{E}\big[(T - \mathbb{E}[T])^2\big] = \sum_k (k - \mathbb{E}[T])^2 \, P(T = k)

A conditional probability P(A∣B)P(A \mid B) is the probability of AA when you already know that BB happened. You keep only the rows where BB is true and measure AA among them:

churned = customers["churned"].to_numpy() == 1
monthly = (customers["contract"] == "month-to-month").to_numpy()
print(f"P(churn) = {churned.mean():.3f}")
print(f"P(churn | month-to-month) = {churned[monthly].mean():.3f}")
print(f"by the formula = {(churned & monthly).mean() / monthly.mean():.3f}")
print(f"P(month-to-month | churn) = {monthly[churned].mean():.3f}")
print("independent?", np.isclose(churned[monthly].mean(), churned.mean(), atol=0.01))
Output
P(churn) = 0.193
P(churn | month-to-month) = 0.296
by the formula = 0.296
P(month-to-month | churn) = 0.855
independent? False

19.3% of all customers churn, but 29.6% of month-to-month customers do. Knowing the contract changes the probability, so contract and churn are not independent. For independent events, P(A∣B)=P(A)P(A \mid B) = P(A); the last line tests this with a tolerance of 1 percentage point and prints False. The fourth line shows that the order matters: 85.5% of churners are on month-to-month contracts. P(A∣B)P(A \mid B) and P(B∣A)P(B \mid A) are different numbers. The third line used the definition as a formula:

P(A∣B)=P(A and B)P(B)P(A \mid B) = \frac{P(A \text{ and } B)}{P(B)}

Often you know P(B∣A)P(B \mid A) but you need P(A∣B)P(A \mid B). Bayes’ rule turns one into the other:

P(A∣B)=P(B∣A) P(A)P(B)withP(B)=P(B∣A) P(A)+P(B∣not A) P(not A)P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)} \qquad \text{with} \qquad P(B) = P(B \mid A)\,P(A) + P(B \mid \text{not } A)\,P(\text{not } A)

The parts have names. The prior P(A)P(A) is what you believe before the evidence. The likelihood P(B∣A)P(B \mid A) says how probable the evidence is if AA is true. The posterior P(A∣B)P(A \mid B) is the updated belief after the evidence.

A churn example. 19.3% of customers churn (the prior). The evidence is “3 logins or fewer in the last 30 days”. Among churners, 17.4% log in that rarely. Among customers who stay, 5.6% do. What is the churn probability of a customer with few logins?

low = (customers["logins_last_30d"] <= 3).to_numpy()
prior = churned.mean()
p_low_churn = low[churned].mean() # likelihood
p_low_stay = low[~churned].mean()
evidence = p_low_churn * prior + p_low_stay * (1 - prior)
posterior = p_low_churn * prior / evidence
print(f"prior {prior:.3f}, P(low|churn) {p_low_churn:.3f}, "
f"P(low|stay) {p_low_stay:.3f}")
print(f"posterior P(churn | low) = {posterior:.3f}")
print(f"counted directly = {churned[low].mean():.3f}")
Output
prior 0.193, P(low|churn) 0.174, P(low|stay) 0.056
posterior P(churn | low) = 0.425
counted directly = 0.425

The evidence raises the churn probability from 19.3% to 42.5%. Bayes’ rule and the direct count agree. Note the size of the update: few logins are three times as common among churners, yet the posterior is still below 50%, because most customers do not churn. Ignoring the prior is a classic mistake, the base-rate fallacy. The naive Bayes classifier (module 36) applies this rule to many features at once.

The word likelihood also names a way to fit models. Suppose each customer churns with the same unknown probability pp. The likelihood L(p)\mathcal{L}(p) (a curly L, so you do not confuse it with the loss LL) is the probability of the observed data if the parameter were pp: the product of pp for every churner and 1−p1 - p for every other customer. A product of 5,000 numbers below 1 is too small for a float, so you work with the log-likelihood, a sum:

log⁡L(p)=∑i=1n[yilog⁡p+(1−yi)log⁡(1−p)]\log \mathcal{L}(p) = \sum_{i=1}^{n} \big[ y_i \log p + (1 - y_i) \log(1 - p) \big]

Maximum likelihood estimation (MLE) picks the parameter that makes the data most probable.

y_churn = churned.astype(float)
print("product of probabilities:", np.prod(np.where(churned, 0.2, 0.8)))
grid = np.linspace(0.01, 0.99, 981) # candidate values of p, step 0.001
log_lik = np.array([np.sum(y_churn * np.log(p) + (1 - y_churn) * np.log(1 - p))
for p in grid])
print(f"best p on the grid: {grid[np.argmax(log_lik)]:.3f}")
print(f"churn rate: {y_churn.mean():.4f}")
Output
product of probabilities: 0.0
best p on the grid: 0.193
churn rate: 0.1926

The plain product underflows to 0.0: the true value is far smaller than the smallest float. The log-likelihood is a normal number. Its maximum sits at the churn rate, 0.193. For this simple model, the maximum likelihood estimate is the sample mean, which is what common sense says too. For richer models there is no common-sense answer, but the principle stays the same.

The sigmoid and log loss: logistic regression as probability

Section titled “The sigmoid and log loss: logistic regression as probability”

Linear regression predicts any number. To predict a probability, a model needs an output between 0 and 1. Logistic regression computes the same score as a linear model, z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b, then squeezes it through the sigmoid (or logistic function), an S-shaped curve that maps any number to a value between 0 and 1. The score zz is the log-odds: z=log⁡p1−pz = \log \frac{p}{1 - p}, where p1−p\frac{p}{1-p} is the odds (a churn probability of 0.2 has odds of 1 to 4). The sigmoid turns log-odds back into a probability.

def sigmoid(z: np.ndarray) -> np.ndarray:
return 1 / (1 + np.exp(-z))
scores = np.array([-4.0, -1.0, 0.0, 1.0, 4.0])
print("sigmoid:", sigmoid(scores).round(3))
p = sigmoid(scores)
print("log-odds back:", np.log(p / (1 - p)).round(3))
Output
sigmoid: [0.018 0.269 0.5 0.731 0.982]
log-odds back: [-4. -1. 0. 1. 4.]

A score of 0 means a probability of 0.5. Large positive scores approach 1 and large negative scores approach 0, but never reach them. Taking the log-odds of the probabilities gives the scores back. In math notation, the sigmoid is:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}
zs = np.linspace(-6, 6, 200)
fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(zs, sigmoid(zs))
ax.axhline(0.5, color="gray", lw=0.8, ls="--")
ax.axvline(0, color="gray", lw=0.8, ls="--")
ax.set_xlabel("score z = w·x + b (log-odds)")
ax.set_ylabel("probability σ(z)")
ax.set_title("The sigmoid squeezes any score into (0, 1)")
plt.show()
An S-shaped curve that rises from near 0 at z = −6 through 0.5 at z = 0 to near 1 at z = 6, steepest in the middle.
The sigmoid maps a score to a probability. A score of 0 gives 0.5.

How do you train it? Use maximum likelihood: each customer has their own probability pi=σ(zi)p_i = \sigma(z_i), and the log-likelihood is the same sum as before. Machine learning minimizes losses, so flip the sign and average. That is the log loss (also called binary cross-entropy). For one churner, the loss is −log⁡p-\log p, where pp is the predicted churn probability:

def log_loss(y: np.ndarray, p: np.ndarray) -> float:
return float(-np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)))
truth = np.array([1.0])
for prob in [0.9, 0.6, 0.1, 0.01]:
loss_value = log_loss(truth, np.array([prob]))
print(f"churner predicted at {prob:4}: loss {loss_value:.3f}")
Output
churner predicted at 0.9: loss 0.105
churner predicted at 0.6: loss 0.511
churner predicted at 0.1: loss 2.303
churner predicted at 0.01: loss 4.605

A confident correct prediction (0.9) costs little. A confident wrong prediction (0.01) costs a lot, and the cost grows without limit as the predicted probability goes to 0. So log loss punishes overconfidence, which is why it is the standard metric for probabilities (module 36).

For nn customers, the log loss averages the cost over all of them. The term with yiy_i counts for churners and the term with 1−yi1 - y_i for the others:

log loss=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]\text{log loss} = -\frac{1}{n} \sum_{i=1}^{n} \big[ y_i \log p_i + (1 - y_i) \log(1 - p_i) \big]

Where does the gradient come from? From the chain rule, along the chain wj→z→p→Lw_j \to z \to p \to L. You need one more rule, the slope of the sigmoid: σ′(z)=σ(z) (1−σ(z))\sigma'(z) = \sigma(z)\,(1 - \sigma(z)). Check it, and the result of the whole chain for one churner, numerically:

for z in [-2.0, 0.0, 1.5]:
p_z = sigmoid(z)
print(f"z = {z:4}: sigmoid slope {slope(sigmoid, z):.4f}, "
f"p(1 - p) = {p_z * (1 - p_z):.4f}")
y_one = 1.0
dL_dz = slope(lambda z: log_loss(np.array([y_one]), sigmoid(np.array([z]))), 0.5)
print(f"dL/dz at z = 0.5: numerical {dL_dz:.4f}, p - y = {sigmoid(0.5) - y_one:.4f}")
Output
z = -2.0: sigmoid slope 0.1050, p(1 - p) = 0.1050
z = 0.0: sigmoid slope 0.2500, p(1 - p) = 0.2500
z = 1.5: sigmoid slope 0.1491, p(1 - p) = 0.1491
dL/dz at z = 0.5: numerical -0.3775, p - y = -0.3775

For one customer, the three slopes of the chain are:

dLdp=−yp+1−y1−pdpdz=p (1−p)dzdwj=xj\frac{dL}{dp} = -\frac{y}{p} + \frac{1 - y}{1 - p} \qquad \frac{dp}{dz} = p\,(1 - p) \qquad \frac{dz}{dw_j} = x_j

Multiply the first two and most terms cancel: (−yp+1−y1−p) p(1−p)=−y(1−p)+(1−y) p=p−y\big(-\frac{y}{p} + \frac{1-y}{1-p}\big)\,p(1-p) = -y(1-p) + (1-y)\,p = p - y. So dLdwj=(p−y) xj\frac{dL}{dw_j} = (p - y)\,x_j: the error times the feature, as for linear regression. Averaged over all customers and written for all weights at once, the gradient has the same shape as the MSE gradient, with the sigmoid inside:

∇log loss=1nX⊤(σ(Xw)−y)\nabla \text{log loss} = \frac{1}{n} X^\top \big(\sigma(X\mathbf{w}) - \mathbf{y}\big)

Exercise M32-C09 on the exercises page checks the chain for two customers, and Example 7 checks the whole gradient vector numerically before it trains.

Example 7 also trains logistic regression with this gradient and compares it with scikit-learn.

Example 1 — Find comparable houses with distances

Section titled “Example 1 — Find comparable houses with distances”

Goal: A real estate agent prices a house by looking at the most similar houses that sold, the “comparables”. Find the three houses most similar to H0001, first on raw features, then on standardized features, and see why the scale decides the answer.

Step 1 — Measure raw distances from H0001 to every house

Section titled “Step 1 — Measure raw distances from H0001 to every house”
query = X[0]
raw_dist = np.linalg.norm(X - query, axis=1) # broadcasting: (3000, 5) - (5,)
raw_top = np.argsort(raw_dist)[1:4] # position 0 is H0001 itself
print(houses.loc[raw_top, ["house_id"] + features].to_string(index=False))
print(raw_dist[raw_top].round(2))
Output
house_id sqft bedrooms bathrooms condition distance_to_center_km
H2647 2420 4 2.5 3 8.9
H2466 2420 3 3.0 3 8.9
H2068 2420 6 5.0 3 10.5
[1.73 1.8 3.74]

X - query subtracts the query vector from every row. norm(..., axis=1) takes the L2 norm of each row, which gives 3,000 distances in one call. argsort sorts the positions by distance. The three “nearest” houses all have exactly 2,420 sqft. That is almost the only thing the raw distance sees: they have 3 to 6 bedrooms, 2.5 to 5 bathrooms and a worse condition than H0001.

Z_query = Z[0]
std_dist = np.linalg.norm(Z - Z_query, axis=1)
std_top = np.argsort(std_dist)[1:4]
print(houses.loc[std_top, ["house_id"] + features].to_string(index=False))
print(std_dist[std_top].round(3))
Output
house_id sqft bedrooms bathrooms condition distance_to_center_km
H0157 2410 4 3.5 4 8.2
H1105 2470 4 3.5 4 7.4
H1906 2440 4 3.5 4 9.1
[0.059 0.119 0.233]

On standardized features, the neighbors match H0001 on every feature: similar size, the same rooms, the same condition and a similar distance. A difference of one standard deviation now counts the same in every column.

Step 3 — Compare the comparables’ prices

Section titled “Step 3 — Compare the comparables’ prices”
price_k = houses["price"].to_numpy() / 1000
print("H0001 sold for:", price_k[0])
for name, top in [("raw", raw_top), ("standardized", std_top)]:
print(f"{name:12} comparables: {price_k[top]}, mean {price_k[top].mean():.1f}")
Output
H0001 sold for: 1097.5
raw comparables: [946.5 939.5 477.5], mean 787.8
standardized comparables: [ 877. 813. 1271.], mean 987.0

Averaging the neighbors’ prices is a k-nearest neighbors prediction (module 35). Neither estimate knows the neighborhood, so both are rough, but the standardized neighbors are closer in every feature you gave the model. Module 33 adds the neighborhood as a feature.

l1_dist = np.linalg.norm(Z - Z_query, ord=1, axis=1)
l1_top = np.argsort(l1_dist)[1:4]
print("L2 neighbors:", houses.loc[std_top, "house_id"].tolist())
print("L1 neighbors:", houses.loc[l1_top, "house_id"].tolist())
Output
L2 neighbors: ['H0157', 'H1105', 'H1906']
L1 neighbors: ['H0157', 'H1105', 'H1906']

The L1 distance adds absolute differences, so one large difference counts less than in L2, where it is squared. Here both norms pick the same three houses. On data with a few extreme values, the choice matters more. scikit-learn’s KNeighborsRegressor(p=1) uses L1 and p=2 uses L2.

Common mistakes:

  • Measuring distances on raw features. The feature with the largest numbers decides alone. Standardize first.
  • Forgetting axis=1. np.linalg.norm(X - query) returns one number, the norm of the whole matrix.
  • Keeping position 0 of argsort. The closest house to H0001 is H0001 itself, at distance 0.

Example 2 — Match customers to a churn profile with cosine similarity

Section titled “Example 2 — Match customers to a churn profile with cosine similarity”

Goal: The retention team wants a quick risk score: how much does a customer’s usage pattern look like the typical churner? Build an average churner profile and score every customer with cosine similarity.

Step 1 — Build standardized usage vectors

Section titled “Step 1 — Build standardized usage vectors”
usage_cols = ["tenure_months", "logins_last_30d", "avg_session_minutes",
"support_tickets", "monthly_charges"]
U = customers[usage_cols].to_numpy(dtype=float)
U_std = (U - U.mean(axis=0)) / U.std(axis=0)
print(U_std.shape)
print(U_std[:2])
Output
(5000, 5)
[[ 2.477 0.67 -0.449 -1.058 1.04 ]
[ 2.477 0.415 0.11 -1.058 -0.24 ]]

Each customer becomes a vector of 5 standardized numbers. After standardization, 0 means “average” in every feature, so the direction of a vector says how a customer differs from the average customer.

Step 2 — Average the churners into one profile

Section titled “Step 2 — Average the churners into one profile”
churn_profile = U_std[churned].mean(axis=0)
for col, value in zip(usage_cols, churn_profile, strict=True):
print(f"{col:20} {value:+.3f}")
Output
tenure_months -0.575
logins_last_30d -0.196
avg_session_minutes -0.106
support_tickets +0.430
monthly_charges +0.250

The typical churner has a shorter tenure, fewer logins, more tickets and higher charges than the average customer. The profile is a direction in the 5-dimensional usage space.

norms = np.linalg.norm(U_std, axis=1)
similarity = (U_std @ churn_profile) / (norms * np.linalg.norm(churn_profile))
print(similarity.shape, similarity.min().round(3), similarity.max().round(3))
print(similarity[:5].round(3))
Output
(5000,) -0.976 0.991
[-0.717 -0.937 -0.397 -0.687 -0.939]

U_std @ churn_profile computes all 5,000 dot products in one matrix–vector product. Dividing by the two norms turns them into cosine similarities between −1 and 1. The first five customers all have a negative cosine: they point away from the churn profile. They are the oldest customers, with long tenures.

Step 4 — Check that the score ranks risk

Section titled “Step 4 — Check that the score ranks risk”
bands = np.digitize(similarity, [-0.5, 0.0, 0.5])
for band, name in enumerate(["< -0.5", "-0.5 to 0", "0 to 0.5", "> 0.5"]):
in_band = bands == band
print(f"similarity {name:9}: {in_band.sum():5} customers, "
f"churn rate {churned[in_band].mean():.3f}")
Output
similarity < -0.5 : 805 customers, churn rate 0.031
similarity -0.5 to 0: 1537 customers, churn rate 0.092
similarity 0 to 0.5 : 1796 customers, churn rate 0.221
similarity > 0.5 : 862 customers, churn rate 0.464

np.digitize puts each score into a band. The churn rate rises steadily from band to band. Customers with a similarity above 0.5 churn about 15 times as often as those below −0.5. A score made of one dot product already ranks risk. Models in module 36 learn better weights than a plain average.

Common mistakes:

  • Using raw features. Without standardization, every customer vector points in almost the same direction (dominated by charges and tenure), and most similarities are above 0.8.
  • Computing the profile from all customers instead of churners only. The mean of standardized data is (numerically) the zero vector, so the profile has no direction and the cosines are noise.
  • Reading the score as a probability. A cosine is a similarity between −1 and 1, not a churn probability. Example 7 builds a real probability model.

Example 3 — Fit house prices with one matrix product and least squares

Section titled “Example 3 — Fit house prices with one matrix product and least squares”

Goal: Replace the agent’s guessed weights with the best weights for the five features, using the closed-form solution, and confirm that solve and lstsq agree.

A = np.column_stack([np.ones(n), Z]) # column of ones for the intercept
print(A.shape)
print(A[:2])
Output
(3000, 6)
[[ 1. 0.791 0.772 0.965 1.037 -0.127]
[ 1. -0.346 -0.798 -0.687 1.037 0.565]]

The design matrix (module 23) is the data matrix with a column of ones in front. The weight for that column is the intercept, so AwA\mathbf{w} includes the intercept and no separate bb is needed. The features are standardized, which makes the weights comparable later.

w_normal = np.linalg.solve(A.T @ A, A.T @ y_k)
print(w_normal.round(3))
Output
[476.465 230.069 -18.291 26.406 68.886 -83.372]

A.T @ A is a (6, 6) matrix and A.T @ y_k a (6,) vector. solve returns the six weights. The intercept, about 476.47, is the mean price in thousand USD: with standardized features, the average house has all features at 0.

w_ls, residual_ss, rank, _ = np.linalg.lstsq(A, y_k)
print(w_ls.round(3))
print("rank:", rank, " agree:", np.allclose(w_ls, w_normal))
Output
[476.466 230.069 -18.291 26.406 68.886 -83.372]
rank: 6 agree: True

lstsq works on A itself. It also returns the sum of squared residuals and the rank (the number of independent columns). The rank is 6, so no column is a copy of the others, and both methods give the same weights.

Step 4 — Predict every price and measure the fit

Section titled “Step 4 — Predict every price and measure the fit”
y_hat = A @ w_ls
mse = np.mean((y_hat - y_k) ** 2)
r2 = 1 - np.sum((y_k - y_hat) ** 2) / np.sum((y_k - y_k.mean()) ** 2)
print(f"MSE {mse:,.1f} RMSE {np.sqrt(mse):.1f} R² {r2:.3f}")
print(f"rule of thumb RMSE {np.sqrt(np.mean((y_rule - y_k) ** 2)):.1f}")
Output
MSE 37,859.1 RMSE 194.6 R² 0.627
rule of thumb RMSE 215.6

The fitted weights cut the typical error (the RMSE) from about 216k USD for the rule of thumb to 195k USD. R² of 0.63 means the five features explain 63% of the price variance. Much of the rest comes from the neighborhood, which these features do not include, and from non-linear effects that a linear model on the raw price cannot capture.

for name, weight in zip(["intercept"] + features, w_ls, strict=True):
print(f"{name:22} {weight:+9.2f}")
Output
intercept +476.47
sqft +230.07
bedrooms -18.29
bathrooms +26.41
condition +68.89
distance_to_center_km -83.37

Each weight is the price change, in thousand USD, for one standard deviation more of that feature, with the others held fixed. Size dominates. The negative bedroom weight looks odd. It is a partial effect: the change when bedrooms rise and sqft and bathrooms stay fixed, a combination that rarely happens in the data. Bedrooms correlate at 0.85 to 0.90 with sqft and bathrooms (the transpose section), so once sqft is known, bedrooms add little, and the model splits the credit among the three in ways that need not make sense on their own. This is collinearity (module 33 calls it multicollinearity), not a causal effect: adding a bedroom to a house would not lower its price. Module 43 interprets coefficients carefully.

Common mistakes:

  • Forgetting the column of ones. The model is then forced through the origin, and every weight is distorted.
  • Using np.linalg.inv(A.T @ A) @ A.T @ y_k. It gives the same answer on well-behaved data and a wrong one on nearly dependent columns. Use lstsq.
  • Unpacking lstsq into one name. It returns four values; take the first, or unpack all four.

Example 4 — Check a gradient before you trust it

Section titled “Example 4 — Check a gradient before you trust it”

Goal: Gradient descent follows the gradient blindly. A wrong gradient trains a wrong model with no error message. Write the vectorized MSE gradient for the design matrix A, then check it against a numerical gradient, as every ML library does in its tests.

Step 1 — Write the loss and the analytic gradient

Section titled “Step 1 — Write the loss and the analytic gradient”
def mse_loss(w: np.ndarray, A: np.ndarray, y: np.ndarray) -> float:
return float(np.mean((A @ w - y) ** 2))
def mse_grad(w: np.ndarray, A: np.ndarray, y: np.ndarray) -> np.ndarray:
return 2 / len(y) * A.T @ (A @ w - y)
w_test = np.array([400.0, 100, 0, 50, 20, -50])
print(round(mse_loss(w_test, A, y_k), 1))
print(mse_grad(w_test, A, y_k).round(3))
Output
55773.4
[-152.931 -188.495 -144.406 -141.376 -94.956 28.534]

The gradient is the formula 2nA⊤(Aw−y)\frac{2}{n} A^\top (A\mathbf{w} - \mathbf{y}) in one line: errors, then “feature times error” summed per column. It has one entry per weight.

def numerical_grad(f, w: np.ndarray, h: float = 1e-4) -> np.ndarray:
grad = np.zeros_like(w)
for j in range(len(w)):
step = np.zeros_like(w)
step[j] = h # nudge weight j only
grad[j] = (f(w + step) - f(w - step)) / (2 * h)
return grad
num = numerical_grad(lambda w: mse_loss(w, A, y_k), w_test)
print(num.round(3))
Output
[-152.931 -188.495 -144.406 -141.376 -94.956 28.534]

The loop nudges one weight at a time, which is the definition of a partial derivative. It needs two loss evaluations per weight, so it is far too slow for training, but fine for a check.

analytic = mse_grad(w_test, A, y_k)
rel_error = np.linalg.norm(analytic - num) / np.linalg.norm(analytic + num)
print(f"relative error: {rel_error:.1e}")
print("gradient OK:", rel_error < 1e-7)
Output
relative error: 2.1e-10
gradient OK: True

The relative error divides the difference by the size of the gradients, so the test works whatever the scale. Values around 10−710^{-7} or smaller mean the analytic gradient is right.

def buggy_grad(w: np.ndarray, A: np.ndarray, y: np.ndarray) -> np.ndarray:
return 1 / len(y) * A.T @ (A @ w - y) # forgot the 2 from the square
bad = buggy_grad(w_test, A, y_k)
print(f"relative error: {np.linalg.norm(bad - num) / np.linalg.norm(bad + num):.3f}")
Output
relative error: 0.333

The missing factor 2 gives a relative error of 0.333, far above the threshold. Gradient descent would still run with this gradient, just with a halved learning rate, so the bug would hide. A sign error or a missing transpose is worse and also shows up here immediately.

Common mistakes:

  • Using the one-sided difference (f(w + h) - f(w)) / h. Its error shrinks only in proportion to h. The central difference is much more accurate for the same h. (For a quadratic loss like MSE it is even exact, but not for log loss or a neural network.)
  • Using a tiny step such as h = 1e-12. Rounding errors dominate the difference. Use about 1e-4 to 1e-6 for float64 values of moderate size.
  • Checking at w = 0 only. Some bugs vanish at 0 (for example a term multiplied by w). Check at a random or arbitrary point.

Example 5 — Train linear regression with gradient descent

Section titled “Example 5 — Train linear regression with gradient descent”

Goal: Fit the five-feature price model from scratch with gradient descent, choose the learning rate from loss curves, and show that the result matches the closed-form solution of Example 3 to a stated tolerance.

def train_gd(A: np.ndarray, y: np.ndarray, lr: float, n_iter: int):
w = np.zeros(A.shape[1])
history = []
for _ in range(n_iter):
history.append(mse_loss(w, A, y))
w = w - lr * mse_grad(w, A, y)
return w, np.array(history)
w_gd, hist = train_gd(A, y_k, lr=0.1, n_iter=5)
print(hist.round(0))
Output
[328587. 205152. 142709. 105921. 82882.]

The loop is the update rule w←w−η∇L\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla L and nothing else. It starts with all weights at 0 and records the loss before each step. The loss falls quickly from 328,587 (predicting 0 for every house).

Step 2 — Compare learning rates on a loss curve

Section titled “Step 2 — Compare learning rates on a loss curve”
fig, ax = plt.subplots(figsize=(6.5, 4))
for lr in [0.01, 0.1, 0.3, 0.4]:
_, hist = train_gd(A, y_k, lr=lr, n_iter=60)
ax.plot(hist, label=f"lr = {lr}")
print(f"lr = {lr}: loss after 60 steps {hist[-1]:,.0f}")
ax.axhline(mse, color="black", ls=":", label="closed-form minimum")
ax.set_yscale("log")
ax.set_ylim(30_000, 1_000_000) # lr = 0.4 leaves the chart at the top
ax.set_xlabel("iteration")
ax.set_ylabel("MSE (log scale)")
ax.legend()
plt.show()
Output
lr = 0.01: loss after 60 steps 64,264
lr = 0.1: loss after 60 steps 37,979
lr = 0.3: loss after 60 steps 37,859
lr = 0.4: loss after 60 steps 164,298,887,102,898
Loss curves on a log scale over 60 iterations. lr = 0.01 falls slowly and stays far above the minimum; lr = 0.1 and lr = 0.3 drop to the dotted closed-form minimum within about 20 iterations; lr = 0.4 dips once, then rises and leaves the top of the chart.
Too small learns slowly, too large diverges. 0.3 is the fastest stable rate here.

A loss curve plots the training loss against the iteration. It is the first chart to look at when a model trains. With 0.01 the loss is still falling after 60 steps. With 0.1 and 0.3 it reaches the minimum. With 0.4 it explodes to 164 trillion: every step overshoots and lands higher than before. On standardized data the stable limit is close to 0.36, so 0.3 is a good choice.

w_gd, hist = train_gd(A, y_k, lr=0.3, n_iter=500)
print("gradient descent:", w_gd.round(3))
print("lstsq: ", w_ls.round(3))
print(f"largest difference: {np.max(np.abs(w_gd - w_ls)):.1e}")
Output
gradient descent: [476.466 230.069 -18.291 26.406 68.886 -83.372]
lstsq: [476.466 230.069 -18.291 26.406 68.886 -83.372]
largest difference: 4.3e-13

After 500 steps the weights match the closed-form solution to many decimals. Both methods minimize the same loss. Gradient descent gets there by walking, lstsq by algebra.

tol = 1e-6 # thousand USD, i.e. a tenth of a cent
assert np.allclose(w_gd, w_ls, rtol=0, atol=tol)
print(f"gradient descent matches lstsq within {tol} on every weight")
print(f"final loss {hist[-1]:,.4f} vs minimum {mse:,.4f}")
Output
gradient descent matches lstsq within 1e-06 on every weight
final loss 37,859.1258 vs minimum 37,859.1258

np.allclose(..., rtol=0, atol=tol) checks that every weight differs by at most tol. Write the tolerance down: “it matches” means nothing without a number. Here every weight is within a millionth of a thousand USD of the exact answer.

Step 5 — Undo the standardization for raw units

Section titled “Step 5 — Undo the standardization for raw units”
w_raw = w_gd[1:] / sigma
b_raw = w_gd[0] - np.sum(w_gd[1:] * mu / sigma)
print("per raw unit:", w_raw.round(4))
print(f"intercept: {b_raw:.2f}")
print("H0001 prediction:", round(b_raw + X[0] @ w_raw, 2), round(A[0] @ w_gd, 2))
Output
per raw unit: [ 0.323 -14.351 29.081 72.257 -16.042]
intercept: -236.89
H0001 prediction: 751.94 751.94

The model was trained on zj=(xj−μj)/σjz_j = (x_j - \mu_j)/\sigma_j. Substituting this into w0+∑jwjzjw_0 + \sum_j w_j z_j and collecting terms gives the code’s two lines:

wjraw=wjσjbraw=w0−∑jwj μjσjw_j^{\text{raw}} = \frac{w_j}{\sigma_j} \qquad b^{\text{raw}} = w_0 - \sum_{j} \frac{w_j\,\mu_j}{\sigma_j}

The result is in weights per raw unit: about 0.32k USD (323 USD) per extra sqft, for example. Both forms give the same prediction for H0001. In scikit-learn, a Pipeline with StandardScaler keeps this bookkeeping for you (module 34).

Common mistakes:

  • Running gradient descent on raw features. The sqft column needs a learning rate hundreds of thousands of times smaller than the bedrooms column, and no single rate suits both. Standardize first.
  • Choosing a learning rate without looking at the loss curve. A rising or zig-zag curve means “too large”; a slow straight slope means “too small”.
  • Claiming agreement without a tolerance. Use np.allclose with an explicit atol, or report the largest difference.

Example 6 — Speed up training with mini-batches

Section titled “Example 6 — Speed up training with mini-batches”

Goal: Train the same model with mini-batch gradient descent and compare it with batch gradient descent after the same number of epochs.

Step 1 — Write one epoch of mini-batch updates

Section titled “Step 1 — Write one epoch of mini-batch updates”
def minibatch_epoch(w, A, y, lr, batch_size, rng):
order = rng.permutation(len(y))
for batch in np.array_split(order, len(y) // batch_size):
w = w - lr * mse_grad(w, A[batch], y[batch])
return w
rng = np.random.default_rng(42)
w_mb = np.zeros(A.shape[1])
w_mb = minibatch_epoch(w_mb, A, y_k, lr=0.01, batch_size=32, rng=rng)
print(w_mb.round(1), round(mse_loss(w_mb, A, y_k), 1))
Output
[405.2 115.1 54.4 61.6 49.8 -62.4] 46723.1

The function is the batch update with A[batch] and y[batch] instead of all rows. Fancy indexing with the batch positions picks the rows. After a single epoch of 93 small steps, the loss is 46,723, already within 25% of the minimum of 37,859.

Step 2 — Compare 10 epochs of each method

Section titled “Step 2 — Compare 10 epochs of each method”
rng = np.random.default_rng(42)
w_mb, w_batch = np.zeros(6), np.zeros(6)
mb_hist, batch_hist = [], []
for _ in range(10):
w_mb = minibatch_epoch(w_mb, A, y_k, lr=0.01, batch_size=32, rng=rng)
w_batch = w_batch - 0.3 * mse_grad(w_batch, A, y_k) # one full step per epoch
mb_hist.append(mse_loss(w_mb, A, y_k))
batch_hist.append(mse_loss(w_batch, A, y_k))
print("mini-batch:", np.round(mb_hist[:5]).astype(int), "...", round(mb_hist[-1]))
print("batch: ", np.round(batch_hist[:5]).astype(int), "...", round(batch_hist[-1]))
Output
mini-batch: [46723 39834 38850 38456 38406] ... 37948
batch: [101994 57018 45907 42257 40694] ... 38620

Per epoch, both methods read every row once. Mini-batch makes 93 updates in that time. After one epoch its loss is less than half that of batch gradient descent, which makes one update per epoch. After 10 epochs, mini-batch is within 0.3% of the minimum and batch is still 2% above it. On big data, that difference is hours of training.

fig, ax = plt.subplots(figsize=(6.5, 4))
ax.plot(range(1, 11), batch_hist, "o-", label="batch (lr 0.3)")
ax.plot(range(1, 11), mb_hist, "s-", label="mini-batch 32 (lr 0.01)")
ax.axhline(mse, color="black", ls=":", label="closed-form minimum")
ax.set_xlabel("epoch")
ax.set_ylabel("MSE on all rows")
ax.set_ylim(37_000, 60_000)
ax.legend()
plt.show()
print(f"largest weight difference from lstsq: {np.max(np.abs(w_mb - w_ls)):.1f}")
Output
largest weight difference from lstsq: 9.8
MSE per epoch over 10 epochs. The mini-batch curve is at about 46,700 after epoch 1 and then stays just above the dotted closed-form minimum; the batch curve starts off the chart at epoch 1, is at 57,000 at epoch 2 and falls slowly toward the minimum.
Mini-batch gets close fast but stays noisy. Batch is exact but slow per epoch.

The mini-batch loss wobbles just above the minimum and never settles exactly, because each step follows a noisy gradient. Its weights are within about 10k USD of the exact answer, not within a tenth of a cent. In practice, a learning rate that shrinks over time (a learning-rate schedule) removes most of this noise. PyTorch training loops (module 42) are mini-batch loops of exactly this shape.

Common mistakes:

  • Forgetting to shuffle. If the rows are sorted (here by sale date), each batch sees one period only and the steps pull in turns.
  • Using the batch learning rate for mini-batches. Noisy gradients need smaller steps; the batch rate 0.3 makes mini-batch training jump around.
  • Expecting mini-batch weights to equal the closed-form solution. They land near it; judge them by the loss on validation data, not by exact equality.

Example 7 — From Bayes’ rule to logistic regression for churn

Section titled “Example 7 — From Bayes’ rule to logistic regression for churn”

Goal: Estimate churn probabilities. Start with Bayes’ rule on two pieces of evidence, then train logistic regression from scratch with the log-loss gradient and compare it with scikit-learn.

Step 1 — Combine two pieces of evidence with Bayes’ rule

Section titled “Step 1 — Combine two pieces of evidence with Bayes’ rule”
both = low & monthly
p_both_churn = both[churned].mean()
p_both_stay = both[~churned].mean()
post_both = p_both_churn * prior / (p_both_churn * prior + p_both_stay * (1 - prior))
print(f"P(churn | low logins, month-to-month) = {post_both:.3f}")
print(f"counted directly = {churned[both].mean():.3f}")
print(f"customers with both: {both.sum()}")
Output
P(churn | low logins, month-to-month) = 0.613
counted directly = 0.613
customers with both: 222

Two pieces of evidence raise the churn probability to 61%. But each extra condition shrinks the group: only 222 of 5,000 customers match both. With ten features, most combinations would contain no customers at all. A model that combines features with weights avoids this problem.

churn_cols = ["tenure_months", "logins_last_30d", "support_tickets",
"monthly_charges", "has_autopay"]
C = customers[churn_cols].to_numpy(dtype=float)
C_mu, C_sigma = C.mean(axis=0), C.std(axis=0)
A_c = np.column_stack([np.ones(len(C)), (C - C_mu) / C_sigma])
print(A_c.shape, y_churn.mean().round(4))
Output
(5000, 6) 0.1926

The recipe is the same as for houses: standardize the features and add a column of ones. The target is 0 or 1.

def log_loss_grad(w: np.ndarray, A: np.ndarray, y: np.ndarray) -> np.ndarray:
return A.T @ (sigmoid(A @ w) - y) / len(y)
w_check = np.array([-1.0, -0.5, 0.2, 0.3, 0.1, -0.2])
analytic = log_loss_grad(w_check, A_c, y_churn)
num = numerical_grad(lambda w: log_loss(y_churn, sigmoid(A_c @ w)), w_check)
rel_error = np.linalg.norm(analytic - num) / np.linalg.norm(analytic + num)
print("analytic: ", analytic.round(4))
print("numerical:", num.round(4))
print("gradient OK:", rel_error < 1e-7)
Output
analytic: [ 0.095 0.019 0.075 -0.014 -0.041 -0.011]
numerical: [ 0.095 0.019 0.075 -0.014 -0.041 -0.011]
gradient OK: True

The rule from Example 4 applies here too: check the gradient before you train with it. numerical_grad is the function from Example 4. The relative error is tiny, so the formula 1nA⊤(σ(Aw)−y)\frac{1}{n}A^\top(\sigma(A\mathbf{w}) - \mathbf{y}) derived in the lesson is right.

Step 4 — Train with gradient descent on log loss

Section titled “Step 4 — Train with gradient descent on log loss”
def train_logistic(A, y, lr, n_iter):
w = np.zeros(A.shape[1])
for _ in range(n_iter):
w = w - lr * log_loss_grad(w, A, y)
return w
w_log = train_logistic(A_c, y_churn, lr=2.0, n_iter=1000)
p_churn = sigmoid(A_c @ w_log)
print("weights:", w_log.round(4))
print(f"log loss: {log_loss(y_churn, p_churn):.4f}")
Output
weights: [-1.91 -1.116 -0.332 0.521 0.446 -0.217]
log loss: 0.4032

The loop is the same as for linear regression, with the log-loss gradient in place of the MSE gradient. The log loss has no closed-form solution, so iteration is the only way here. The weights read as log-odds per standard deviation: longer tenure and more logins lower the risk, more tickets and higher charges raise it.

from sklearn.linear_model import LogisticRegression
model = LogisticRegression(C=np.inf, tol=1e-10, max_iter=1000) # C=inf: no penalty
model.fit(A_c[:, 1:], y_churn)
w_sk = np.concatenate([model.intercept_, model.coef_[0]])
print("sklearn:", w_sk.round(4))
print(f"largest difference: {np.max(np.abs(w_sk - w_log)):.1e}")
assert np.allclose(w_sk, w_log, rtol=0, atol=1e-4)
Output
sklearn: [-1.91 -1.116 -0.332 0.521 0.446 -0.217]
largest difference: 3.0e-09

scikit-learn adds an L2 penalty by default; C=np.inf switches it off so that both minimize the same log loss. The weights agree within 10−410^{-4}. Your 5-line loop and the library compute the same model.

base_p = np.full(len(y_churn), y_churn.mean())
print(f"log loss, predict 0.1926 for all: {log_loss(y_churn, base_p):.4f}")
print(f"log loss, logistic regression: {log_loss(y_churn, p_churn):.4f}")
print(f"mean predicted churn: {p_churn.mean():.4f}")
Output
log loss, predict 0.1926 for all: 0.4900
log loss, logistic regression: 0.4032
mean predicted churn: 0.1926

Predicting the base rate for everyone is the maximum likelihood model with no features. The five features lower the log loss from 0.490 to 0.403. The average predicted probability equals the churn rate: a property of logistic regression with an intercept.

Common mistakes:

  • Computing np.log(p) when p can be exactly 0 or 1. The log loss becomes infinite. Libraries clip probabilities to a tiny range such as [1e-15, 1 - 1e-15].
  • Comparing with LogisticRegression() at default settings. Its L2 penalty shrinks the weights, so they differ from an unpenalized loop.
  • Multiplying many conditional probabilities by hand for many features. The groups become empty. Fit a model instead.
Mistake Symptom Fix
Distances or gradient descent on raw features One feature dominates; gradient descent diverges or crawls Standardize: (X - X.mean(axis=0)) / X.std(axis=0)
X @ w with the wrong length of w ValueError: matmul: Input operand 1 has a mismatch ... Print both shapes; the inner sizes must match
* instead of @ An array of products instead of predictions, or a broadcasting error @ for dot and matrix products, * for element-wise
np.linalg.inv(X.T @ X) @ X.T @ y Wrong weights on nearly dependent columns np.linalg.lstsq(X, y) or np.linalg.solve(X.T @ X, X.T @ y)
No column of ones in the design matrix The model goes through the origin; weights are distorted np.column_stack([np.ones(n), X])
np.linalg.norm(X - q) without axis=1 One number instead of one distance per row np.linalg.norm(X - q, axis=1)
A wrong analytic gradient Training runs but converges to a bad model Gradient check with central differences
Learning rate too large Loss rises or zig-zags, then nan Lower the rate; look at the loss curve
Learning rate too small Loss falls in a slow straight line Raise the rate, or standardize
“It matches” without a number A difference that hides a bug np.allclose(a, b, rtol=0, atol=tol) with a stated tol
Mini-batches without shuffling Steps pull in turns; loss oscillates rng.permutation(n) every epoch
Mixing up P(A∣B)P(A \mid B) and P(B∣A)P(B \mid A) A wildly wrong probability Name the condition; use Bayes’ rule to convert
Ignoring the prior Overestimating rare events (base-rate fallacy) Multiply by the prior and divide by the evidence
Multiplying many probabilities Underflow to 0.0 Add log-probabilities instead
np.log(0) in log loss inf or a warning Clip probabilities with np.clip(p, 1e-15, 1 - 1e-15)
  • Search and recommendations: search engines and shops turn documents, products and users into vectors and rank them by cosine similarity. Vector databases do exactly the U_std @ profile step of Example 2, on billions of rows.
  • Computer graphics and games: positions, velocities and light directions are vectors. The brightness of a surface is the dot product of its normal vector and the light direction, and every 3-D scene is drawn with matrix products.
  • Email and security: spam filters and fraud alerts update probabilities with Bayes’ rule. A “1 in 1,000” alert with a 1% false-alarm rate is still mostly false alarms, because of the base rate.
  • Engineering and finance: gradient descent and its variants tune controllers, fit curves to sensor data and optimize portfolios. scipy.optimize.minimize runs the same kind of loop with smarter steps.
  • A row of data is a feature vector; a dataset is a data matrix of shape (n, p). Vector arithmetic and standardization are element-wise.
  • A dot product is a weighted sum. A linear model is an intercept plus a dot product, and XwX\mathbf{w} predicts for every row at once.
  • The L2 norm is length; the norm of a difference is a distance. Standardize before you compare distances. L1 and L2 norms of the weights are the Lasso and Ridge penalties.
  • Cosine similarity compares directions and ignores length.
  • Matrix shapes follow one rule: (n, p) @ (p, k) gives (n, k). Check shapes before you multiply.
  • Write (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top\mathbf{y} on paper, but call lstsq or solve in code.
  • A derivative is a slope; a gradient is the vector of partial derivatives and points uphill. The chain rule multiplies slopes along a chain of functions. Check analytic gradients numerically.
  • Gradient descent repeats w←w−η∇L\mathbf{w} \leftarrow \mathbf{w} - \eta\nabla L. Standardize, pick the learning rate from a loss curve, and confirm against the closed-form solution with a stated tolerance. Mini-batches make many cheap, noisy steps.
  • Expectation is a probability-weighted average. Conditional probability restricts to the rows where the condition holds. Bayes’ rule flips the condition and needs the prior.
  • Logistic regression is a linear score passed through the sigmoid. Log loss is its negative mean log-likelihood, and its gradient is 1nX⊤(σ(Xw)−y)\frac{1}{n}X^\top(\sigma(X\mathbf{w}) - \mathbf{y}).

Q1. What is a feature vector, and what does position 2 of the vector x1 in this lesson mean?

Answer

A feature vector is one row of data as an ordered list of numbers, one position per feature. With features = ["sqft", "bedrooms", "bathrooms", ...], position 2 is the number of bathrooms (3.5 for H0001). The order must be the same for every row.

Q2. The weights are [0.2, 5, 15] and a house has the features [1000, 2, 1]. What is the dot product, and what does it mean?

Answer

0.2 × 1000 + 5 × 2 + 15 × 1 = 200 + 10 + 15 = 225. It is the weighted score of the house: with these weights, the features add 225 (thousand USD) to the base price.

Q3. Why does the raw Euclidean distance between two houses mostly measure the difference in sqft?

Answer

The L2 norm squares each difference. Sqft differences are in the hundreds, bedroom differences in the ones, so the squared sqft difference is tens of thousands of times larger and dominates the sum. Standardize the features so that each one is measured in standard deviations.

Q4. Review A has the word-count vector [2, 0, 1] and review B has [4, 0, 2]. What is their cosine similarity? Why?

Answer
  1. B is exactly 2 × A, so both point in the same direction. Cosine similarity ignores length, so a longer review with the same word proportions counts as identical in topic.

Q5. X has shape (3000, 5) and W has shape (5, 2). What is the shape of X @ W, of X.T @ X, and what happens with W @ X?

Answer

X @ W is (3000, 2): two predictions per row. X.T @ X is (5, 5). W @ X is (5, 2) @ (3000, 5): the inner sizes 2 and 3000 differ, so NumPy raises a ValueError.

Q6. Why should you call np.linalg.lstsq(X, y) instead of np.linalg.inv(X.T @ X) @ X.T @ y?

Answer

Both minimize the same squared error, but the inverse is slower and less accurate. Forming X.T @ X squares the condition number, and inverting it amplifies rounding errors further. With nearly dependent columns, the inverse gives wrong weights. lstsq works on X directly and handles dependent columns.

Q7. At the current weight, the derivative of the loss is −80. Should gradient descent increase or decrease the weight? What does it do when the derivative is 0?

Answer

Increase it. The update is w←w−η⋅(−80)=w+80ηw \leftarrow w - \eta \cdot (-80) = w + 80\eta. A negative slope means the loss falls as ww grows. With a derivative of 0, the step is 0: the weight sits at a flat spot, normally the minimum.

Q8. For one house, L=(wx−y)2L = (w x - y)^2. Use the chain rule to write dLdw\frac{dL}{dw}. What is it for x=2x = 2, y=10y = 10, w=3w = 3?

Answer

With u=wx−yu = wx - y: dLdw=2u⋅x\frac{dL}{dw} = 2u \cdot x. Here u=6−10=−4u = 6 - 10 = -4, so dLdw=2⋅(−4)⋅2=−16\frac{dL}{dw} = 2 \cdot (-4) \cdot 2 = -16. The negative slope says “increase ww”.

Q9. A loss curve rises after a few iterations and then shows nan. What is the most likely cause and the fix?

Answer

The learning rate is too large, so every step overshoots the minimum and the loss grows until the numbers overflow. Lower the learning rate (for example by a factor of 3 to 10). If the features are not standardized, standardize them first.

Q10. What is the difference between batch, mini-batch and stochastic gradient descent?

Answer

They differ in how many rows each gradient uses: all rows (batch), a small random batch such as 32 rows (mini-batch) or one row (stochastic). Fewer rows make each step cheaper and noisier, so the model makes more steps per epoch but lands near the minimum instead of exactly on it.

Q11. A test flags 90% of fraudulent payments and wrongly flags 2% of normal ones. 1 payment in 500 is fraud. What is the probability that a flagged payment is fraud?

Answer

Prior 0.002. Evidence: 0.9 × 0.002 + 0.02 × 0.998 = 0.0018 + 0.01996 = 0.02176. Posterior: 0.0018 / 0.02176 ≈ 0.083. Only about 8% of flagged payments are fraud, because fraud is rare (the base rate).

Q12. Why does logistic regression use the sigmoid, and why is log loss a good loss for it?

Answer

The sigmoid turns any score into a probability between 0 and 1. Log loss is the negative mean log-likelihood of the observed 0/1 outcomes, so minimizing it is maximum likelihood estimation. It punishes confident wrong predictions very strongly, and its gradient has the simple form 1nX⊤(σ(Xw)−y)\frac{1}{n}X^\top(\sigma(X\mathbf{w}) - \mathbf{y}).

Your progress

0 / 4 done

  • Exercises: 27 exercises with hints and full solutions, from warm-up to challenge.
  • Mini-project: build and test a gradient-descent house price model from scratch.
  • Cheat sheet: every formula of this module next to its NumPy one-liner.
  • Next module: 33. Feature engineering turns raw columns into good features: scaling, encoding, binning and leakage checks.
  • Go deeper later: 46. Linear algebra in depth (QR, eigen-decomposition, SVD) and 47. Calculus and optimization for ML (Taylor series, Jacobians, Hessians, integration, Lagrange multipliers, Adam and building reverse-mode autograd from scratch).