Math for ML — Vectors, Slopes and Chances, Built in Code
"If you can write a for-loop and read a table, you can do every piece of maths a machine-learning engineer actually uses. We build each idea in code first, and only then give it its name."
01 · The hookTwo Questions and One Sceptical VP
"Priya — two things before the city-wide rain-surge rollout goes to the board.
First, I keep being told the demand curve says 'each extra 0.1 of surge costs us about four ride requests an hour'. I want to know where that number comes from, and I do not want 'the library computed it'. Second, on 60 rainy evenings we ran the surge on half the zones. Finance says it lifted demand by ten requests per zone-hour. I say that is luck with a spreadsheet around it. The rollout touches 140 zones. Prove me wrong, or tell me I am right."
Priya Raman is RideNow's pricing analyst. She is good with Excel and with the SQL from Module 01d. She has not done any real maths since university, and the words "gradient" and "p-value" make her shoulders tense. This is the situation of most working engineers.
Marcus has asked two different kinds of question. The first is "how is a line fitted to data?". It needs vectors, slopes and a loop. The second is "is this difference real or luck?". It needs probability and a test. This module builds both answers from nothing but NumPy and a pencil.
There is a third reason to learn this now. Every model in the rest of the course is built from these parts. A neural network is a pile of matrix multiplications trained by gradient descent. A search engine over documents is a list of vectors compared by angle. Learn the parts once, here, in small numbers, and the later modules stop being mysterious.
You have written all of this without the vocabulary. A vector is an array. A dot product is a loop that multiplies two arrays slot by slot and sums the result. A matrix is an array of arrays, so a matrix times a vector is a loop over rows.
A derivative is what you measure when you change one input a tiny bit and watch the output, exactly like a profiler. A probability is a count divided by a total. Gradient descent is a retry loop with a step size, the same shape as a canary rollout. The maths is mostly naming things you already do.
| Maths word | What it is in code | RideNow question it answers |
|---|---|---|
| Vector | A NumPy array of numbers | "What does this zone's demand profile look like?" |
| Dot product, cosine | Multiply slot by slot, add up; divide out the size | "Are these two zones alike, whatever their size?" |
| Matrix | A 2-D array; X @ w is one dot product per row | "Score every zone at once" |
| Derivative | Nudge an input, measure how the output moves | "If I raise the price a little, how much does demand fall?" |
| Gradient | One derivative per knob, collected in a list | "Which way do I turn the slope and intercept to fit better?" |
| Gradient descent | A loop: measure slope, step the other way, repeat | "Fit the demand line without a library" |
| Probability | Count the cases you want, divide by all the cases | "How often do riders cancel in the rain?" |
| Hypothesis test | Shuffle the labels many times, count how often luck matches you | "Was the surge lift luck?" |
| Embedding | A vector whose angle to another vector means similar meaning | "Which support tickets are about the same problem?" |
- Question 1, the top row. Vectors and matrices give the data a shape, slopes tell us which way to turn the two knobs, and gradient descent finds w = −37.99 and b = 138.27.
- Question 2, the bottom row. Probability gives the language of luck (a rain request cancels 0.2504 of the time), and the hypothesis test says how often luck matches the surge gap: 0.0073.
- The bonus. Embeddings turn sentences into vectors so the cosine from the first section measures meaning. A real model scores two late-pickup complaints at 0.513.
You are not expected to remember any of the maths words in that table yet. Every one is built in code in the sections below, with numbers small enough to check on paper. Come back to this table at the end; it will read like a list of things you already did.
02 · VectorsA Vector Is a List of Numbers With a Direction
A vector is just a list of numbers, such as the requests a zone gets in the morning, afternoon and evening. Think of it as an arrow from the origin to that point. Without this idea you cannot say how alike two zones, two customers or two sentences are.
Marcus asked two questions, and the first one is about a line through demand data. Before anyone can fit a line, we need a way to talk about a whole row of numbers at once, as one object. That object is a vector, and the first thing to do with two of them is compare them.
A vector is an ordered list of numbers. The list [3, 4] can mean "3 steps east, 4 steps north". It can also mean "3 requests in the morning, 4 in the evening". Either way it is a point, and it is also an arrow from the origin (the point [0, 0]) to that point. The arrow has a length and it points somewhere.
Each number in the list is one dimension. A zone described by morning, afternoon and evening demand has three dimensions. A sentence described by a language model has 384 or 1,536. The arrow cannot be drawn past three dimensions, but every rule below works the same way at any size.
Three questions you can ask of any vectors
We have arrows now. RideNow wants to know which zones behave alike, so we need three tools: how long is an arrow, how much do two arrows agree, and how alike are their directions once size is removed.
- Length. How long is the arrow? Use Pythagoras: square each number, add them, take the square root. For
[3, 4]that is √(9 + 16) = 5. - Dot product. How much do two arrows agree? Multiply the matching slots and add up the products. For
[3, 4]and[4, 3]that is 3×4 + 4×3 = 24. - Cosine similarity. How alike are the directions, ignoring size? Divide the dot product by both lengths. For our pair that is 24 ÷ (5 × 5) = 0.96.
The cosine is the most useful of the three. It is the dot product with the size divided out. A value of 1 means the arrows point the same way. A value of 0 means they are at a right angle, with nothing in common. A value of −1 means they point opposite ways. Fig. 1e.1 draws all three cases with the real numbers.
- The arrow a = (3, 4). It goes 3 east and 4 north, so its length is 5 (the 3-4-5 triangle you may remember from school). Length is the first thing you can compute from any vector.
- The small angle between a and b. b = (4, 3) is a mirror image of a, and the arrows are only 16.3° apart. Their dot product is 24, and dividing by 5 × 5 gives a cosine of 0.96. Close to 1 means almost the same direction.
- The right angle between a and c. c = (−4, 3) points up and to the left. The dot product is 3×(−4) + 4×3 = −12 + 12 = 0. A zero dot product means a 90° angle, so these two vectors share nothing.
Why the size has to come out
The dot product alone has a flaw that RideNow's own data exposes in the next example. Two zones with the same daily rhythm but different sizes get very different dot products, so we divide the size out.
Take three RideNow zones, each described by requests in the morning, afternoon and evening. The airport gets [8, 2, 9]. Downtown gets exactly half of that, [4, 1, 4.5]. The suburb gets [1, 6, 1]. Airport and downtown have the same shape at different sizes. The suburb peaks in the afternoon instead.
- Airport against downtown, cosine 1.000. Every airport number is exactly twice the downtown one, so the arrows lie on the same line. The sizes are 12.2 and 6.1, and the cosine ignores that difference completely.
- Airport against suburb, cosine 0.385. The suburb's tall bar is in the middle, where the airport's is short. The arrows point in clearly different directions, and the cosine is far below 1.
If we had compared raw dot products, the airport would look more "similar" to downtown (74.5) than to any smaller zone, just because the numbers are big. Dividing by both lengths removes that effect. This is why every search engine and every embedding system in Module 05 and Module 08 uses cosine similarity.
The code below uses np.array, np.dot and np.linalg.norm, and you have not been taught them yet. Guess what each line does before you open the answers. The step-by-step list under the exercise walks through every line afterwards.
Step-by-step: what vectors_by_hand.py does, in plain English
- Import NumPy, the library that holds arrays of numbers and does maths on all of them at once.
- Make three arrows,
a,bandc, as NumPy arrays of two numbers each. - Print the length of
atwice: once with Pythagoras written by hand, once withnp.linalg.norm. Both must say 5. - Print the dot product of
aandbtwice, by hand and withnp.dot. Both must say 24. - Print the dot product of
aandc. It is 0, which means a right angle. - Define
cosine(u, v): the dot product divided by the product of the two lengths. - Print the cosine and the angle for
a–band fora–c.arccosturns a cosine into an angle in radians anddegreesconverts it. - Make a dictionary of three RideNow zones, each a 3-number array of morning, afternoon and evening requests.
- Print the cosine of airport against downtown and against suburb, and then the raw dot product of airport and downtown, to show that the dot product grows with size and the cosine does not.
# pip install "numpy>=2.5,<2.6"
# Vectors as lists of numbers: length, dot product, cosine similarity.
import numpy as np
a = np.array([3.0, 4.0]) # an arrow: 3 steps east, 4 steps north
b = np.array([4.0, 3.0])
c = np.array([-4.0, 3.0])
# length: Pythagoras, written the long way and the short way
print("length of a, by hand:", (3**2 + 4**2) ** 0.5)
print("length of a, numpy: ", np.linalg.norm(a))
# dot product: multiply matching slots, then add
print("a . b by hand:", 3 * 4 + 4 * 3)
print("a . b numpy: ", np.dot(a, b))
print("a . c:", np.dot(a, c), "(zero means a right angle)")
# cosine similarity: the dot product with the size divided out
def cosine(u, v):
return np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))
print("cos(a, b) =", round(cosine(a, b), 4), "-> angle", round(np.degrees(np.arccos(cosine(a, b))), 1), "degrees")
print("cos(a, c) =", round(cosine(a, c), 4), "-> angle", round(np.degrees(np.arccos(cosine(a, c))), 1), "degrees")
# the same idea on RideNow zones: requests in (morning, afternoon, evening)
zones = {
"airport": np.array([8.0, 2.0, 9.0]),
"downtown": np.array([4.0, 1.0, 4.5]), # exactly half of airport
"suburb": np.array([1.0, 6.0, 1.0]),
}
print("airport vs downtown:", round(cosine(zones["airport"], zones["downtown"]), 4))
print("airport vs suburb: ", round(cosine(zones["airport"], zones["suburb"]), 4))
print("dot airport.downtown:", np.dot(zones["airport"], zones["downtown"]), "(grows with size)")
length of a, by hand: 5.0
length of a, numpy: 5.0
a . b by hand: 24
a . b numpy: 24.0
a . c: 0.0 (zero means a right angle)
cos(a, b) = 0.96 -> angle 16.3 degrees
cos(a, c) = 0.0 -> angle 90.0 degrees
airport vs downtown: 1.0
airport vs suburb: 0.3854
dot airport.downtown: 74.5 (grows with size)
Read the output. The first two lines agree because NumPy's length is just Pythagoras. The dot product 24 matches the by-hand sum. The cosine of 0.96 equals 16.3°, and the right-angle pair gives exactly 0 and 90°. The last three lines are the point of the zones example: airport and downtown score a cosine of 1.0 even though the raw dot product is a large 74.5.
- Vector
- An ordered list of numbers; also an arrow from the origin to that point.
- Length
- Square each number, add, take the square root.
np.linalg.norm(v). - Dot product
- Multiply matching slots, add the products.
np.dot(u, v). Zero means a right angle. - Cosine similarity
- Dot product divided by both lengths. 1 same direction, 0 unrelated, −1 opposite. It ignores size.
- Why divide the size out
- A zone twice as busy has a bigger dot product with everything. The cosine compares shape only.
03 · Matrices, shapes and broadcastingA Matrix Is a Batch of Dot Products
A matrix is a grid of numbers, which you can read as a stack of vectors, one per row. Multiplying a matrix by a vector gives one dot product per row, all at once. Without it, you would write a loop for every model score.
Priya can now compare two zones. RideNow has 140 zones, and the model that Marcus asked about scores every zone-hour. Doing that with a loop of dot products is slow and clumsy, so the next tool is the matrix, which does all the dot products in one step.
Start small. Stack the three zone vectors from the last section on top of each other. You get a grid with three rows (zones) and three columns (morning, afternoon, evening). That grid is a matrix. Its shape is written (3, 3): rows first, then columns.
Now give each time slot a weight, say 1 for morning, 0.5 for afternoon and 2 for evening, as a vector w. Dot the first row with w: 8×1 + 2×0.5 + 9×2 = 27. Do the same for each row and you have one score per zone. NumPy's X @ w does exactly that, and Fig. 1e.3 draws it.
- Row 1 of X. It is the airport: 8 morning requests, 2 afternoon, 9 evening. The box marks the row that is being dotted with the weights.
- The weights w. One weight per column: 1, 0.5 and 2. The rule is that the number of columns in X (3) must equal the length of w (3).
- The result. Three numbers, one per row: 27, 13.5 and 6. The shape (3, 3) times (3,) gives (3,): the columns have been used up, and one number per row remains.
This is the single most common operation in machine learning. A linear model is X @ w + b. One layer of a neural network is X @ W + b with a grid of weights instead of a single vector. The whole of deep learning in Module 04 is this one move repeated and trained.
The same grid as a transform
So far the matrix has been a table of data. It has a second meaning that matters just as much: it can be a machine that moves arrows. Weights in a neural network are matrices of this second kind.
Give a 2×2 matrix an arrow, and it hands back a new arrow. The matrix [[2, 0], [0, 0.5]] stretches the east direction by 2 and squashes the north direction by 0.5. Our arrow (3, 4) becomes (6, 2). The matrix [[0, −1], [1, 0]] turns every arrow 90° anticlockwise, so (3, 4) becomes (−4, 3).
matrix @ arrow, stretches in one panel and turns in the other. The matrix is the machine; the arrow is what goes in.- The input arrow v = (3, 4). The faint arrow in both panels is the same input. It is the thing the matrix works on.
- The output of M. M @ v = (6, 2): the east part doubled (3 to 6) and the north part halved (4 to 2). The columns of a matrix say where the east and north arrows land.
You do not need to draw these in practice. The takeaway is that "multiply by a matrix" can mean "score every row" or "move every arrow", and the arithmetic is the same. In a neural network, the training process searches for the matrix whose moves make the output useful.
Shapes: the check that prevents most bugs
Both uses of a matrix depend on the sizes lining up. When they do not, NumPy stops with an error. Learning to read shapes is the cheapest debugging skill in this whole course.
The rule for @ is that the inner numbers must match and the outer numbers survive. A (3, 3) matrix times a (3,) vector works and gives (3,). A (3, 3) matrix times a (3, 3) matrix works and gives (3, 3). A (3, 4) matrix times a (3,) vector fails, because 4 does not equal 3.
Print .shape whenever you are unsure. Most machine-learning bugs that are not data bugs are shape bugs, so make it a habit to write the expected shape in a comment next to every array.
Broadcasting: when NumPy stretches a small array for you
Shapes also decide what happens when you add or subtract arrays of different sizes. Centring each column on its mean, a standard cleaning step, needs this. NumPy's rule is called broadcasting.
To subtract the column averages from every row, you do not write a loop. You write X - X.mean(axis=0). The average vector has shape (3,) and X has shape (3, 3). NumPy lines the shapes up from the right, sees that the missing axis can be treated as 1, and copies the average vector down the rows. Fig. 1e.5 shows the copy.
- The real row of averages. It has shape (3,). The three numbers are the column means of X: 4.33 for morning, 3.00 for afternoon, 4.83 for evening.
- The stretched copies. The dashed rows are not stored in memory; NumPy behaves as if they were there. After the stretch the shape is (3, 3), so the subtraction can go slot by slot.
- The alignment rule. Compare shapes from the right. Each pair must be equal, or one of them must be 1 (or missing). (3, 3) with (3,) passes. (3, 3) with (2,) fails on 3 against 2.
Four short ideas: transpose, identity, inverse, and why ML avoids the last
These four ideas appear in every textbook on the subject. You need only the plain meaning of each, and a reason why the last one rarely shows up in working code.
- Transpose. Flip a matrix so rows become columns:
X.T. The productX @ X.Tgives every zone dotted with every zone, a 3 × 3 table of similarities (the output below shows it). - Identity. The matrix that changes nothing, with 1s on the diagonal and 0s elsewhere:
np.eye(2). It is the matrix version of multiplying by 1. - Inverse. The matrix that undoes another:
np.linalg.inv(M). Apply M and then its inverse, and you are back where you started. The output below checks this.
ML rarely inverts a matrix, for three reasons. It is slow on large grids, because the work grows with the cube of the size. It is numerically fragile, because a nearly flat matrix makes tiny rounding errors huge. And it is unnecessary: gradient descent, which you build in the next section, finds the answer by small steps and never builds an inverse. When you do need to solve a system, np.linalg.solve is safer than inv.
Step-by-step: what matrices_and_shapes.py does, in plain English
- Build
X, a 3×3 grid of zone demand, andw, three weights. Print both shapes. - Compute
X @ w, and again with a Python loop ofnp.dotper row. The two answers must match: that is the "batch of dot products" claim. - Build a stretch matrix
Mand apply it to the arrow (3, 4). Build a rotation matrixRand apply it. - Compute
X @ X.Tand print its shape and values: each zone against every zone. - Compute the column means and subtract them from
X: broadcasting. - Try to add a length-2 vector to a 3×3 matrix inside
try/except, and print theValueErrorNumPy raises. - Show that the identity matrix leaves the arrow unchanged, and that
Mfollowed by its inverse gets the arrow back.
# pip install "numpy>=2.5,<2.6"
# Matrices as a batch of dot products, as a transform, plus shapes and broadcasting.
import numpy as np
# Three zones (rows) x three time slots (columns): requests per hour.
X = np.array([[8.0, 2.0, 9.0],
[4.0, 1.0, 4.5],
[1.0, 6.0, 1.0]])
w = np.array([1.0, 0.5, 2.0]) # one weight per time slot
print("X shape:", X.shape, "| w shape:", w.shape)
print("X @ w :", X @ w)
print("row by row, loop :", np.array([np.dot(row, w) for row in X]))
# the same matrix as a transform: it moves an arrow
M = np.array([[2.0, 0.0],
[0.0, 0.5]]) # stretch east x2, squash north x0.5
v = np.array([3.0, 4.0])
print("M @ v:", M @ v)
# the 90-degree turn: rows are where the east and north arrows land
R = np.array([[0.0, -1.0],
[1.0, 0.0]])
print("R @ v:", R @ v)
# shapes: (3, 3) @ (3,) -> (3,) and (3, 3) @ (3, 3) -> (3, 3)
print("X @ X.T shape:", (X @ X.T).shape)
print("X @ X.T:\n", X @ X.T) # every zone dotted with every zone
# broadcasting: line the shapes up from the right; a 1 (or missing axis) stretches
col_means = X.mean(axis=0) # shape (3,)
print("column means:", col_means)
print("X - col_means:\n", X - col_means)
try:
X + np.array([1.0, 2.0]) # shapes (3,3) and (2,) do not line up
except ValueError as err:
print("ValueError:", err)
# transpose, identity, inverse
I = np.eye(2)
print("I @ v:", I @ v)
print("M @ inv(M) @ v:", M @ np.linalg.inv(M) @ v)
X shape: (3, 3) | w shape: (3,)
X @ w : [27. 13.5 6. ]
row by row, loop : [27. 13.5 6. ]
M @ v: [6. 2.]
R @ v: [-4. 3.]
X @ X.T shape: (3, 3)
X @ X.T:
[[149. 74.5 29. ]
[ 74.5 37.25 14.5 ]
[ 29. 14.5 38. ]]
column means: [4.33333333 3. 4.83333333]
X - col_means:
[[ 3.66666667 -1. 4.16666667]
[-0.33333333 -2. -0.33333333]
[-3.33333333 3. -3.83333333]]
ValueError: operands could not be broadcast together with shapes (3,3) (2,)
I @ v: [3. 4.]
M @ inv(M) @ v: [3. 4.]
Read the output. Both ways of scoring the zones print 27, 13.5 and 6, so @ is a loop of dot products. M @ v gives (6, 2) and R @ v gives (−4, 3), the numbers in Fig. 1e.4. The first row of X @ X.T starts with 149, the airport's squared length. The column means and the subtraction match Fig. 1e.5. The ValueError message names both shapes, which is the first thing to read when a shape bug appears.
- Matrix
- A 2-D grid of numbers. Shape (rows, columns). A stack of vectors.
X @ w- One dot product per row of X. Needs X's column count to equal w's length.
- Matrix as transform
- Feed it an arrow, get a moved arrow. Neural-network weights are matrices that learn useful moves.
- Shape rule for @
- (m, n) @ (n, k) gives (m, k). The inner n must match.
- Broadcasting
- Align shapes from the right; a 1 or a missing axis stretches. Otherwise
ValueError. - Transpose / identity / inverse
X.Tflips rows and columns;np.eyechanges nothing;invundoes. ML rarely inverts because it is slow, fragile, and gradient descent does not need it.
04 · Slopes, gradients and the chain ruleA Derivative Is the Slope of a Tiny Step
A derivative says how much the output moves when you nudge the input a tiny bit. The gradient collects one such number for every knob. Without it, a program has no way to know which direction improves a model.
Marcus asked where "four fewer requests per 0.1 of surge" comes from. The answer is a line, and the line has two knobs: a slope and an intercept. To tune the knobs automatically we need to know, for each knob, which way to turn it. That is what a derivative tells us.
Step 1: measure a slope with code
We begin with the smallest possible example: one input, one output, no data. If this feels too easy, good. Everything else in the section is this move with more knobs.
Take the function f(x) = x², so f(3) = 9 and f(4) = 16. Going from x = 3 to x = 4 raises the output by 7 for a step of 1, so the average slope over that step is 7 ÷ 1 = 7. Now shrink the step to 0.1. The slope of the step is (f(3.1) − f(3)) ÷ 0.1 = 6.1. Shrink it again and it settles near 6.
That settling-down value is the derivative at x = 3: the slope of a step so tiny that the curve looks straight. Fig. 1e.6 draws it and prints the numbers.
- The point x = 3. Here f = 9. We want to know how steeply the curve is climbing at exactly this spot.
- The step to x = 4. The dashed line through (3, 9) and (4, 16) has slope 7. It is too steep, because the curve bends upward during the step.
- The tangent. The solid line that just touches the curve at x = 3 has slope 6. It is what the dashed line becomes as the step shrinks to nothing.
- The table. Steps of 1, 0.1, 0.001 and 0.000001 give 7.000000, 6.100000, 6.001000 and 6.000001. The extra amount is always equal to the step size, so it vanishes as the step shrinks.
You never need to do this by hand for real models. But you need to trust it, because it is exactly how we will check our gradient code later. It is also where the school formula comes from: the derivative of x² is 2x, and 2 × 3 = 6.
Step 2: two knobs, one gradient
A line has two knobs, so a loss depends on two numbers at once. The slope of a tiny step now needs a rule for which knob moves. That gives us the partial derivative and the gradient.
Use two data points, (x = 1, y = 3) and (x = 2, y = 5), and the line y = w·x + b. The loss is how wrong the line is: the sum of the squared gaps between the line and the points. With w = 0 and b = 0 the line predicts 0 for both, the gaps are −3 and −5, and the loss is 9 + 25 = 34.
Now nudge only w and keep b fixed. The loss changes by −26 per unit of w. That number is the partial derivative with respect to w. Nudge only b: −16 per unit of b. Collect the two into one list, (−26, −16). That list is the gradient.
The gradient points uphill, toward larger loss. We want smaller loss, so we step the opposite way. Here the negative signs mean the loss would grow if we lowered w or b, so we must raise both. Fig. 1e.7 draws the picture.
- The gradient at (0, 0). It is the arrow (−26, −16), drawn at the start. It points toward the outer, higher-loss rings. The start loss is 34.
- The downhill step. Move the opposite way by 0.05 times the gradient: w = 0 + 0.05 × 26 = 1.3 and b = 0 + 0.05 × 16 = 0.8. The loss falls from 34 to 3.37 in one step.
- The best pair. At w = 2 and b = 1 the line passes through both points and the loss is 0. The steps in the next section walk toward it.
Here is the code for both steps. It is short, with no data table and no model. Run it before reading on.
Step-by-step: what slopes.py does, in plain English
- Define
f(x) = x². - For four step sizes, compute
(f(x+h) − f(x)) / hat x = 3 and print it. The numbers close in on 6. - Define a two-knob loss from the two data points: the sum of the squared gaps.
- Nudge
wup and down by a tinyh, keepingbfixed, and divide the loss change by2h. That is the partial derivative forw. - Do the same for
b. Print both, as the gradient pair.
# pip install "numpy>=2.5,<2.6"
# Derivatives as the slope of a tiny step, then partial derivatives and the gradient.
import numpy as np
def f(x):
return x ** 2 # a bowl; its slope at x should be 2x
# the slope of a tiny step, with smaller and smaller steps
x = 3.0
for h in (1.0, 0.1, 0.001, 1e-6):
print(f"h={h:<8} (f(x+h) - f(x)) / h = {(f(x + h) - f(x)) / h:.6f}")
print("the formula 2x says:", 2 * x)
# two inputs: the partial derivative nudges one input and freezes the other.
# Two data points (x=1, y=3) and (x=2, y=5); the loss is the sum of squared errors.
def loss(w, b):
return (w * 1.0 + b - 3.0) ** 2 + (w * 2.0 + b - 5.0) ** 2
w0, b0, h = 0.0, 0.0, 1e-6
dw = (loss(w0 + h, b0) - loss(w0 - h, b0)) / (2 * h)
db = (loss(w0, b0 + h) - loss(w0, b0 - h)) / (2 * h)
print("loss at (0, 0):", loss(w0, b0))
print("partial wrt w:", round(dw, 4), "| partial wrt b:", round(db, 4))
print("the gradient is the pair:", (round(dw, 2), round(db, 2)), "-> it points uphill; we step the other way")
h=1.0 (f(x+h) - f(x)) / h = 7.000000
h=0.1 (f(x+h) - f(x)) / h = 6.100000
h=0.001 (f(x+h) - f(x)) / h = 6.001000
h=1e-06 (f(x+h) - f(x)) / h = 6.000001
the formula 2x says: 6.0
loss at (0, 0): 34.0
partial wrt w: -26.0 | partial wrt b: -16.0
the gradient is the pair: (-26.0, -16.0) -> it points uphill; we step the other way
Read the output. The first four lines are the table in Fig. 1e.6, closing in on 6. The loss at (0, 0) is 34, as computed by hand. The two partial derivatives, −26 and −16, are the gradient in Fig. 1e.7. The nudge uses a step on both sides of the point (w+h and w−h), which is more accurate than one side only.
Step 3: the chain rule, drawn as a graph
The loss we have used is simple. Real models stack many steps, such as multiply, add, square, so the loss depends on a knob through a chain. The chain rule is how a slope is passed back through that chain, and it is the heart of backpropagation.
Break the loss into small steps. Take w = 2, x = 3, b = 1 and y = 10. First a = w·x = 6. Then p = a + b = 7. Then the loss L = (p − y)² = 9. That is a computation graph: boxes joined by arrows, each box one tiny operation.
Walk it backwards. The slope of L with respect to p is 2(p − y) = −6. The slope of p with respect to a is 1. The slope of a with respect to w is x = 3. The chain rule says to multiply the slopes along the path: (−6) × 1 × 3 = −18.
- The loss node. L = (p − y)² = 9. The backward pass starts here with a slope of 1 for L itself.
- One local slope. At the plus node p = a + b, the slope of L with respect to p is −6. Plus passes the slope straight on, so dL/da and dL/db are also −6.
- The answer for w. −6 × 1 × 3 = −18, because a = w·x makes a move 3 units for each unit of w. This is the gradient number for w.
This is exactly what loss.backward() does in PyTorch. It builds the graph while it computes forward, then walks it backwards multiplying local slopes. You will see the full version in Module 04, where the graph has millions of boxes. Nothing there is harder than the six numbers above.
Step-by-step: what chain_rule.py does, in plain English
- Set the four numbers w, x, b, y.
- Forward pass: compute
a, thenp, thenL. Each line uses the one before. - Backward pass: write down each node's local slope. L with respect to p is
2·(p − y). Each input of a plus node has slope 1. a with respect to w isx. - Multiply the slopes along the path to get
dL/dwanddL/db. - Check
dL/dwwith a tiny two-sided step on the whole loss. It must agree. - Ask SymPy, a symbolic algebra library, for the derivative of x²; it answers
2*x.
# pip install "numpy>=2.5,<2.6" "sympy>=1.13,<2"
# The chain rule on a small computation graph: a = w*x ; p = a + b ; L = (p - y)^2
w, b, x, y = 2.0, 1.0, 3.0, 10.0
# forward pass: compute each node from the ones before it
a = w * x
p = a + b
L = (p - y) ** 2
print(f"forward: a={a} p={p} L={L}")
# backward pass: one local slope per node, multiplied along the path
dL_dp = 2 * (p - y) # L = (p-y)^2 -> slope 2(p-y)
dp_da, dp_db = 1.0, 1.0 # p = a + b -> slope 1 for each input
da_dw = x # a = w*x -> slope x with respect to w
dL_dw = dL_dp * dp_da * da_dw
dL_db = dL_dp * dp_db
print(f"backward: dL/dp={dL_dp} dL/dw={dL_dw} dL/db={dL_db}")
# check the chain rule against a tiny step
def L_of(w_, b_):
return (w_ * x + b_ - y) ** 2
h = 1e-6
print("numeric dL/dw:", round((L_of(w + h, b) - L_of(w - h, b)) / (2 * h), 4))
# optional: let SymPy do the algebra (pip install sympy)
import sympy as sp
xs = sp.symbols("x")
print("sympy derivative of x**2:", sp.diff(xs ** 2, xs))
forward: a=6.0 p=7.0 L=9.0
backward: dL/dp=-6.0 dL/dw=-18.0 dL/db=-6.0
numeric dL/dw: -18.0
sympy derivative of x**2: 2*x
Read the output. The forward line shows 6, 7 and 9, the numbers above the boxes in Fig. 1e.8. The backward line shows −6, −18 and −6, the red numbers below the boxes. The numeric check agrees with −18, so the chain-rule bookkeeping is right. SymPy agrees with the school formula. SymPy is useful when you want a formula; it is not how models are trained.
- Derivative
- The slope of a tiny step: (f(x+h) − f(x)) ÷ h as h shrinks. Tells you how much the output moves per nudge.
- Partial derivative
- The same, nudging one input and holding the others still.
- Gradient
- The list of partial derivatives, one per knob. Points toward higher loss; we step the opposite way.
- Loss
- One number for how wrong the model is. Smaller is better.
- Chain rule
- Multiply the local slopes along the path from the loss back to a knob. This is backpropagation.
- Computation graph
- Boxes for tiny operations. Forward pass computes values, backward pass computes slopes.
05 · Build it yourselfGradient Descent From Scratch, Five Chunks
Gradient descent fits a model by repeating one small step: measure which way is uphill, then move the knobs the other way. Without it, you would have to guess the line by hand, or know a closed-form formula for every model.
Priya now has every part. She has vectors for rows, a loss that says how wrong a line is, and a gradient that says which way to turn the slope and intercept. Marcus wants the demand line without a library, so she assembles the parts into a loop and checks it against the library afterwards.
The data is eight zone-hours on dry evenings. For each one she has the surge multiplier shown (1.0 means normal price, 1.8 means 80% higher) and the ride requests that hour. The line she wants is requests = w × surge + b, where w is the slope and b is the intercept.
The algorithm in four lines is this. Guess w and b. Compute the loss and the gradient. Move each knob a small step against its gradient. Repeat. The chant below says it aloud, and Fig. 1e.7 showed one step on two points.
Measure the error.
Find the slope of each knob.
Step the opposite way.
Repeat until the ground is flat.
Measure the error: the loss number, 34 at the start in marker 1 of Fig. 1e.7. Find the slope: the gradient arrow (−26, −16). Step the opposite way: marker 2, from (0, 0) to (1.3, 0.8). Repeat until flat: the loss curve in Fig. 1e.9 flattening out.
- The gradient box. The two slopes, −26 and −16, say which way the loss climbs. It is the only box that needs calculus; the others are arithmetic.
- The return arrow. After the update the loop starts again with w = 1.3 and b = 0.8. A computer repeats this thousands of times; you did it three times with a pencil.
This is the whole algorithm. The program below is the same thing with eight points instead of two, plus a check that the gradient is right. It is about 70 lines, so we build it in five chunks. Every chunk runs on its own, so you can stop after any of them with a working, smaller program.
Marcus's note about libraries is why we do it this way. np.polyfit in one line gives the same answer, and chunk 5 prints both. The point of the loop is that you will see the machine that sits underneath every model in this course. If you read Module 02 you have seen a 30-line version; this one adds the gradient check, and focuses on what each number means.
Build it in chunks
We build gradient_descent.py in five chunks: data, prediction, loss, gradient with a check, and the loop with a picture. Each chunk runs on its own; the whole file comes after chunk 5.
-
Chunk 1 — the data: eight zone-hours of surge and requests
Why this comes first: every later step needs data to be wrong about. Eight rows is small enough to read in full.
Step-by-step: what chunk 1 does, in plain English
- Import NumPy, the array library.
- Make
surge, an array of eight multipliers from 1.0 to 1.8. - Make
rides, the requests per hour seen in each of those eight zone-hours. - Print how many rows there are and the first pair, as a sanity check.
gradient_descent.py — chunk 1runs offline# pip install "numpy>=2.5,<2.6" "matplotlib>=3.9" # Fit rides = w * surge + b by gradient descent, with no ML library. import numpy as np # ── chunk 1: the data ── # One row per zone-hour: the surge multiplier shown, and ride requests that hour. surge = np.array([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.8]) rides = np.array([100.0, 96.0, 93.0, 91.0, 84.0, 80.0, 78.0, 70.0]) print("rows:", len(surge), "| first pair:", surge[0], "->", rides[0])np.array([...])— a list of numbers that supports maths on all of it at once.Run
python3 gradient_descent.py. You should see:terminalactual outputrows: 8 | first pair: 1.0 -> 100.0 -
Chunk 2 — the prediction: a line with a slope and an intercept
Why this comes next: before we can say how wrong a line is, we need a function that turns a guess for w and b into predicted requests.
Step-by-step: what chunk 2 does, in plain English
- Define
predict(w, b, x), which returnsw * x + b. NumPy applies it to every element ofxat once. - Print the predictions of a useless guess (w = 0, b = 0) for the first three rows: all zeros.
- Print the predictions of a sensible guess (w = −40, b = 140): 100, 96 and 92, close to the real 100, 96 and 93.
gradient_descent.py — chunk 2runs offlinedef predict(w, b, x): return w * x + b # a line: slope w, intercept b print("guess w=0, b=0 ->", predict(0.0, 0.0, surge[:3])) print("guess w=-40, b=140 ->", predict(-40.0, 140.0, surge[:3]))A plain function that works on a whole array. No loop is needed.
Run the file again. The new lines at the end are:
terminalactual outputguess w=0, b=0 -> [0. 0. 0.] guess w=-40, b=140 -> [100. 96. 92.] - Define
-
Chunk 3 — the loss: one number for how wrong a line is
Why this comes next: a guess is only "better" if something can be compared. The loss gives each line a single score, and gradient descent will push that score down.
Step-by-step: what chunk 3 does, in plain English
- Define
mse(w, b, x, y), short for mean squared error. - Compute the error for each row: prediction minus truth.
- Square each error so a +3 and a −3 cannot cancel, and take the average.
- Print the loss for the useless guess and for the sensible guess.
gradient_descent.py — chunk 3runs offlinedef mse(w, b, x, y): errors = predict(w, b, x) - y return np.mean(errors ** 2) # square so + and - errors cannot cancel print("loss of guess (0, 0): ", round(mse(0.0, 0.0, surge, rides), 2)) print("loss of guess (-40, 140): ", round(mse(-40.0, 140.0, surge, rides), 2))np.mean— the average of an array. The squaring is why the loss is a bowl with one lowest point.The new lines at the end:
terminalactual outputloss of guess (0, 0): 7573.25 loss of guess (-40, 140): 2.25 - Define
-
Chunk 4 — the gradient, and a check that it is right
Why this comes next: the loop needs a direction. We compute the gradient by the formula, and also by the tiny-step method from the slopes section, and make the program stop if they disagree.
Step-by-step: what chunk 4 does, in plain English
- Define
gradient. It computes the errors, thendw = 2 × mean(error × x)anddb = 2 × mean(error). These are the two partial derivatives of the loss. - Define
numeric_gradient. It nudgeswby ±1e-6 and measures the loss change, then does the same forb. This is slow but does not depend on any formula. - Print both gradients at (0, 0). They must agree to several decimals.
assert np.allclose(...)compares them at a second point and stops the program with an error if they differ by more than a tiny tolerance.
gradient_descent.py — chunk 4runs offlinedef gradient(w, b, x, y): errors = predict(w, b, x) - y dw = 2 * np.mean(errors * x) # how loss changes per tiny nudge of w db = 2 * np.mean(errors) # how loss changes per tiny nudge of b return dw, db def numeric_gradient(w, b, x, y, h=1e-6): # the slope of a tiny step, measured on both sides of the point dw = (mse(w + h, b, x, y) - mse(w - h, b, x, y)) / (2 * h) db = (mse(w, b + h, x, y) - mse(w, b - h, x, y)) / (2 * h) return dw, db print("analytic:", np.round(gradient(0.0, 0.0, surge, rides), 4)) print("numeric: ", np.round(numeric_gradient(0.0, 0.0, surge, rides), 4)) assert np.allclose(gradient(-40.0, 140.0, surge, rides), numeric_gradient(-40.0, 140.0, surge, rides), rtol=1e-4) print("gradient check passed")assert— stops the program with anAssertionErrorif a claim is false.np.allclose— compares arrays within a tolerance.The new lines at the end:
terminalactual outputanalytic: [-230.975 -173. ] numeric: [-230.975 -173. ] gradient check passed - Define
-
Chunk 5 — the loop, the answer, and a picture
Why this comes last: everything it needs, a prediction, a loss and a trusted gradient, now exists. The loop only has to repeat the step, and the picture shows that it worked.
Step-by-step: what chunk 5 does, in plain English
- Import matplotlib and choose the
Aggbackend, which draws to a file instead of opening a window. - Start at
w = 0,b = 0with learning rate 0.1 (the step size). - Repeat 5,001 times: record the loss, print it at six chosen steps, compute the gradient, and move both knobs a small step against it.
- Ask
np.polyfitfor the library's answer and print both side by side. - Draw the data with the fitted line on the left, and the first 400 losses on the right. Save to
gradient_descent.png.
gradient_descent.py — chunk 5runs offlineimport matplotlib matplotlib.use("Agg") # draw to a file, no window needed import matplotlib.pyplot as plt w, b, lr = 0.0, 0.0, 0.1 history = [] for step in range(5001): history.append(mse(w, b, surge, rides)) if step in (0, 1, 10, 100, 1000, 5000): print(f"step {step:>4} w={w:8.3f} b={b:8.3f} loss={history[-1]:9.3f}") dw, db = gradient(w, b, surge, rides) w, b = w - lr * dw, b - lr * db # step downhill lib_w, lib_b = np.polyfit(surge, rides, 1) # the library's answer, for comparison print(f"ours: w={w:.4f} b={b:.4f}") print(f"polyfit: w={lib_w:.4f} b={lib_b:.4f}") fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.4)) left.scatter(surge, rides, color="black") left.plot(surge, predict(w, b, surge), color="tab:blue") left.set(xlabel="surge multiplier", ylabel="ride requests per hour", title="the fitted line") right.plot(history[:400]) right.set(xlabel="step", ylabel="loss (MSE)", title="loss, first 400 steps") fig.tight_layout() fig.savefig("gradient_descent.png", dpi=110) print("saved gradient_descent.png")w, b = w − lr × dw, b − lr × db— the whole algorithm in one line.plt.subplots— two charts side by side.The new lines at the end. The two answers agree to four decimals:
terminalactual outputstep 0 w= 0.000 b= 0.000 loss= 7573.250 step 1 w= 23.098 b= 17.300 loss= 1657.211 step 10 w= 37.126 b= 33.650 loss= 357.947 step 100 w= 12.964 b= 67.309 loss= 165.227 step 1000 w= -36.944 b= 136.805 loss= 1.069 step 5000 w= -37.995 b= 138.268 loss= 0.999 ours: w=-37.9950 b=138.2682 polyfit: w=-37.9950 b=138.2682 saved gradient_descent.png - Import matplotlib and choose the
The whole program
Lines 1–10 are chunk 1 (data), 11–17 chunk 2 (prediction), 18–25 chunk 3 (loss), 26–44 chunk 4 (gradient and check), and 45–71 are chunk 5 (loop and picture). Every chunk starts with a # ── chunk n ── comment, and the file lives in code/01e-math-for-ml/.
# pip install "numpy>=2.5,<2.6" "matplotlib>=3.9"
# Fit rides = w * surge + b by gradient descent, with no ML library.
import numpy as np
# ── chunk 1: the data ──
# One row per zone-hour: the surge multiplier shown, and ride requests that hour.
surge = np.array([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.8])
rides = np.array([100.0, 96.0, 93.0, 91.0, 84.0, 80.0, 78.0, 70.0])
print("rows:", len(surge), "| first pair:", surge[0], "->", rides[0])
# ── chunk 2: the prediction ──
def predict(w, b, x):
return w * x + b # a line: slope w, intercept b
print("guess w=0, b=0 ->", predict(0.0, 0.0, surge[:3]))
print("guess w=-40, b=140 ->", predict(-40.0, 140.0, surge[:3]))
# ── chunk 3: the loss ──
def mse(w, b, x, y):
errors = predict(w, b, x) - y
return np.mean(errors ** 2) # square so + and - errors cannot cancel
print("loss of guess (0, 0): ", round(mse(0.0, 0.0, surge, rides), 2))
print("loss of guess (-40, 140): ", round(mse(-40.0, 140.0, surge, rides), 2))
# ── chunk 4: the gradient, and a check on it ──
def gradient(w, b, x, y):
errors = predict(w, b, x) - y
dw = 2 * np.mean(errors * x) # how loss changes per tiny nudge of w
db = 2 * np.mean(errors) # how loss changes per tiny nudge of b
return dw, db
def numeric_gradient(w, b, x, y, h=1e-6):
# the slope of a tiny step, measured on both sides of the point
dw = (mse(w + h, b, x, y) - mse(w - h, b, x, y)) / (2 * h)
db = (mse(w, b + h, x, y) - mse(w, b - h, x, y)) / (2 * h)
return dw, db
print("analytic:", np.round(gradient(0.0, 0.0, surge, rides), 4))
print("numeric: ", np.round(numeric_gradient(0.0, 0.0, surge, rides), 4))
assert np.allclose(gradient(-40.0, 140.0, surge, rides),
numeric_gradient(-40.0, 140.0, surge, rides), rtol=1e-4)
print("gradient check passed")
# ── chunk 5: the loop, and a picture ──
import matplotlib
matplotlib.use("Agg") # draw to a file, no window needed
import matplotlib.pyplot as plt
w, b, lr = 0.0, 0.0, 0.1
history = []
for step in range(5001):
history.append(mse(w, b, surge, rides))
if step in (0, 1, 10, 100, 1000, 5000):
print(f"step {step:>4} w={w:8.3f} b={b:8.3f} loss={history[-1]:9.3f}")
dw, db = gradient(w, b, surge, rides)
w, b = w - lr * dw, b - lr * db # step downhill
lib_w, lib_b = np.polyfit(surge, rides, 1) # the library's answer, for comparison
print(f"ours: w={w:.4f} b={b:.4f}")
print(f"polyfit: w={lib_w:.4f} b={lib_b:.4f}")
fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.4))
left.scatter(surge, rides, color="black")
left.plot(surge, predict(w, b, surge), color="tab:blue")
left.set(xlabel="surge multiplier", ylabel="ride requests per hour", title="the fitted line")
right.plot(history[:400])
right.set(xlabel="step", ylabel="loss (MSE)", title="loss, first 400 steps")
fig.tight_layout()
fig.savefig("gradient_descent.png", dpi=110)
print("saved gradient_descent.png")
Read the output. The loss starts at 7,573 and falls to 357.9 by step 10. It then falls slowly, to 165.2 at step 100, and 1.07 at step 1,000. Past that it is flat at 0.999, which is the noise in the data: no straight line can do better. The final w = −37.9950, b = 138.2682 match polyfit to four decimals. That is Marcus's number: about −3.8 requests per 0.1 of surge.
- The fitted line. w = −37.99 means each extra 1.0 of surge multiplier costs about 38 requests per hour, so each 0.1 costs about 3.8. b = 138.27 is the line's value at a multiplier of 0, which is outside the data and only needed to place the line.
- The quick drop, then the long slide. The loss drops from 7,573 to 358 in ten steps, then takes about a thousand more steps to reach the floor. The slope and intercept pull against each other, so the descent winds down a narrow valley. Module 02's follow-up on scaling shows how to straighten that valley.
- The floor. At step 1,000 the loss is 1.07; at step 5,000 it is 0.999. The last bit of improvement is tiny, which is the sign to stop.
- Prediction
w * x + b: a line with slope w and intercept b.- Loss (MSE)
- The average of the squared gaps between prediction and truth. One number; smaller is better.
- Gradient
dw = 2·mean(error·x),db = 2·mean(error). Points uphill.- The update
w = w − lr × dw, and the same for b. Repeat.- Gradient check
- Compare the formula's gradient with a tiny-step gradient. If they differ, the formula has a bug.
- Stop when
- The loss stops falling by a meaningful amount. Here it is flat near 1.0 by step 1,000.
06 · Watch it breakTwo Ways Gradient Descent Goes Wrong Quietly
Gradient descent rarely crashes. When it goes wrong, it hands back a smooth-looking wrong answer. The two common causes are a step size that is wrong, and a gradient formula with a bug in it.
Priya's loop matched the library, so she trusts it. Before she hands it to anyone, she wants to know how it fails, because a pricing model that is quietly wrong costs real money. There are two failure shapes, and both can be drawn.
Failure 1: the step size
The learning rate was 0.1 in chunk 5 and it worked. We try 0.001 and 0.8 on the same data and watch the loss.
The learning rate is the size of each downhill step, as a multiple of the gradient. Too small and the loop crawls. Too large and each step overshoots the valley and lands higher on the other side. Fig. 1e.10 draws all three on the same data, with real numbers from lr_three_runs.py.
- Too small (0.001). The loss starts at 7,573 and is still 4,406 after 50 steps. It is heading the right way but would need thousands more steps. Nothing is wrong except patience.
- About right (0.1). The loss falls to 254 in 50 steps, and to about 1 by step 1,000. This is the curve you want: steep at first, then flattening.
- Too big (0.8). The first step jumps from 7,573 to 95,000, and by step 3 the loss is past a million. By step 10 it is around 1015. Each overshoot is larger than the last, so the numbers explode.
The practical rule: try a few values a few times apart, throw out any whose loss climbs, and keep the largest one that falls smoothly. A "good" value depends on the units of your data, which is why the learning-rate sweep in Module 02 works on scaled columns, and why its scaling follow-up matters. We do not repeat that story here.
Failure 2: a bug in the gradient
A step size can be tuned by looking at a curve. A bug in the gradient formula cannot, because the loop still runs and the loss still falls. The only defence is to compare the formula to the tiny-step method.
The most common mistake is forgetting one factor. Here the author forgot to multiply the error by x in the slope's gradient. The code runs without an error, the loss goes down, and the final line is plausible. It is simply wrong.
Step-by-step: what gradient_bug.py does, in plain English
- Load the same eight points and define the loss
mse. - Define
buggy_gradient, which giveswthe same formula asbby mistake. - Define
numeric_gradient, the tiny-step version, which cannot have this bug because it only calls the loss. - Print both gradients at (0, 0) and whether they agree.
- Train for 5,000 steps with the buggy gradient and print where it ends up, next to the correct final loss.
# pip install "numpy>=2.5,<2.6"
# The numeric gradient catching a classic bug: forgetting to multiply the error by x.
import numpy as np
surge = np.array([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.8])
rides = np.array([100.0, 96.0, 93.0, 91.0, 84.0, 80.0, 78.0, 70.0])
def mse(w, b):
return np.mean((w * surge + b - rides) ** 2)
def buggy_gradient(w, b):
errors = w * surge + b - rides
return 2 * np.mean(errors), 2 * np.mean(errors) # BUG: dw forgot "* surge"
def numeric_gradient(w, b, h=1e-6):
return ((mse(w + h, b) - mse(w - h, b)) / (2 * h),
(mse(w, b + h) - mse(w, b - h)) / (2 * h))
print("buggy: ", np.round(buggy_gradient(0.0, 0.0), 3))
print("numeric:", np.round(numeric_gradient(0.0, 0.0), 3))
print("agree? ", np.allclose(buggy_gradient(0.0, 0.0), numeric_gradient(0.0, 0.0), rtol=1e-4))
# what the bug does to training: descend with the buggy gradient for 5,000 steps
w = b = 0.0
for _ in range(5000):
dw, db = buggy_gradient(w, b)
w, b = w - 0.1 * dw, b - 0.1 * db
print(f"after 5,000 buggy steps: w={w:.3f} b={b:.3f} loss={mse(w, b):.2f} (correct loss: 0.999)")
buggy: [-173. -173.]
numeric: [-230.975 -173. ]
agree? False
after 5,000 buggy steps: w=36.614 b=36.614 loss=348.03 (correct loss: 0.999)
Read the output. The buggy gradient says (−173, −173), and the numeric one says (−230.975, −173). They disagree on the first number, so the check fails in a single line of output. The training run shows why it matters. After 5,000 steps the buggy loop reports w = 36.614, a positive slope that claims demand rises with price, and a loss of 348 instead of 0.999. It never crashed.
This is why chunk 4 in the program has an assert. Write the gradient check once, run it whenever you change the loss, and you will catch this class of bug in seconds. Deep learning libraries run the same kind of check on their own operations before they ship them.
Tonight's talk: the Formula Gradient and the Tiny-Step Gradient argue over the question, "Which of us do you trust?"
I am the one that trains the model. I cost two array operations, and I give the exact slope for all knobs at once. The loop in chunk 5 runs me 5,001 times and still finishes in a blink.
The formula version is fast: two lines of NumPy, one value for each knob, no matter how many knobs.
You are fast, and you can be wrong. I am the one who caught you in gradient_bug.py: you said (−173, −173) and the truth was (−230.975, −173). I need no algebra, so I cannot have an algebra bug.
The tiny-step version only calls the loss, so it cannot share the formula's mistakes. It caught the missing factor of x.
And you are far too slow to train anything. For a model with a million knobs, you would run the loss two million times for every single step. I run once.
The tiny-step version needs two loss evaluations per knob, so it is hopeless as a training method for large models.
Agreed. I am not here to train. I am the test that you pass on a handful of points before anyone trusts you. We will meet again in module 04, when I check the gradients of a whole network, one layer at a time.
The usual split: formula for training, tiny-step as a unit test on a few points. That arrangement is used in deep-learning libraries too.
Questions you might be asking now
Four questions that gradient descent usually raises. Every answer uses the same two data points, (x = 1, y = 3) and (x = 2, y = 5), with the line y = w·x + b, so you can check each number on paper.
| Point | x | y (truth) | Prediction at w = 0, b = 0 | Error (prediction − y) |
|---|---|---|---|---|
| P1 | 1 | 3 | 0 | −3 |
| P2 | 2 | 5 | 0 | −5 |
Why do we subtract the gradient? Isn't the gradient the direction we want?
No. The gradient points toward more loss, so we move the opposite way. The minus sign in w = w − lr × dw is what turns "uphill" into "downhill".
At w = 0, b = 0, the gradient is (−26, −16). Both numbers are negative, which says "the loss goes down as w and b go up". Read it carefully: the gradient is the slope, and the loss climbs in the direction the slope points. Here, that direction is toward smaller w and b, which is where the loss is higher.
- Gradient for w. 2 × (−3×1 + −5×2) = 2 × (−13) = −26.
- Subtract it, with step 0.05. w = 0 − 0.05 × (−26) = 0 + 1.3 = 1.3. Subtracting a negative number adds.
- Same for b. b = 0 − 0.05 × (−16) = 0.8.
- Check the result. The loss at (1.3, 0.8) is 3.37, far below 34 at (0, 0).
| Move | New (w, b) | New loss |
|---|---|---|
| Subtract the gradient (correct) | (1.3, 0.8) | 3.37 |
| Add the gradient (wrong way) | (−1.3, −0.8) | (−1.3−0.8−3)² + (−2.6−0.8−5)² = 26.01 + 70.56 = 96.57 |
Adding the gradient would send the loss from 34 to 96.57. People who want to maximise something (a reward, a likelihood) add the gradient instead, and call it gradient ascent. The idea is the same.
The gradient points uphill. Subtract it to go downhill.
Show me the second and third steps, with the numbers.
Each step uses the new w and b from the last. The gradient shrinks as you approach the bottom, so the steps get smaller on their own. The loss goes 34, then 3.37, then 0.3385.
The loop below is in one_step_by_hand.py. Here are the three steps, lettered.
- Step 0 (start). w = 0, b = 0. Errors −3 and −5, loss 34, gradient (−26, −16).
- Step 1. w = 1.3, b = 0.8. Predictions 2.1 and 3.4, errors −0.9 and −1.6, loss 0.81 + 2.56 = 3.37. Gradient: dw = 2 × (−0.9×1 + −1.6×2) = −8.2, db = 2 × (−0.9 + −1.6) = −5.
- Step 2. w = 1.3 + 0.05×8.2 = 1.71, b = 0.8 + 0.05×5 = 1.05. Predictions 2.76 and 4.47, errors −0.24 and −0.53, loss 0.0576 + 0.2809 = 0.3385. Gradient (−2.6, −1.54).
- Step 3. w = 1.71 + 0.05×2.6 = 1.84, b = 1.05 + 0.05×1.54 = 1.127. The target is (2, 1), and we are close.
| Step | w | b | Loss | Gradient (dw, db) |
|---|---|---|---|---|
| 0 | 0 | 0 | 34 | (−26, −16) |
| 1 | 1.3 | 0.8 | 3.37 | (−8.2, −5) |
| 2 | 1.71 | 1.05 | 0.3385 | (−2.6, −1.54) |
| 3 | 1.84 | 1.127 | — | — |
The honest limit: this problem is a perfect bowl with a loss of exactly 0 at (2, 1). Real data has noise, so the loss flattens above zero, as it did at 0.999 in the eight-point program.
Each step shrinks the gradient, so the loop slows itself as it nears the bottom.
Why do we square the errors, and why take the average?
We square so that errors of opposite sign cannot cancel. We average so the loss does not grow just because there is more data. The average also keeps the learning rate meaning the same thing on 8 rows or 8 million.
Imagine a line whose errors on our two points were −3 and +3. Without squaring, they add to 0 and the line looks perfect. With squaring, the loss is 9 + 9 = 18, which tells the truth.
- Add the errors, no squaring. (−3) + (+3) = 0. The line looks perfect, and it is not.
- Square first. 9 + 9 = 18. Both errors now count against the line.
- Average. 18 ÷ 2 = 9. With ten times the data the sum would be ten times larger and the average would still be 9.
The tiny dataset above uses the sum (34) to keep the numbers whole. The eight-point program uses the mean, so its gradient is divided by 8 compared with a sum. A sum would need a learning rate 8 times smaller.
Square so signs cannot cancel; average so the size of the data does not change the scale.
How do I pick the learning rate?
Try a few values, each three to ten times apart, and watch the loss. Drop any where it climbs. Keep the largest where it falls smoothly, then go one notch lower for safety.
Fig. 1e.10 is exactly this test. On the surge data, 0.8 explodes, 0.1 is good, and 0.001 is safe but slow.
- Run 50 steps at each of 0.001, 0.1 and 0.8. The losses at step 50 are 4,406, 254 and about 1059.
- Discard the one that grew. 0.8 is gone.
- Keep the largest that fell. 0.1 wins. 0.001 works, but after 50 steps its loss is 17 times higher than that of 0.1.
The honest limit: this works here because the surge column is small (1.0 to 1.8). With columns in thousands, even 0.0001 can blow up, which is the scaling story in Module 02. Bigger models use schedulers and adaptive optimisers such as Adam, covered in Module 04.
Largest learning rate whose loss still falls smoothly, then a notch lower.
- Learning rate too small
- Loss falls but crawls: 4,406 after 50 steps against 254 for lr 0.1. Fix: increase it.
- Learning rate too big
- Loss climbs each step and explodes: past a million by step 3 at lr 0.8. Fix: shrink it.
- Silent gradient bug
- The loop runs, the loss falls, the answer is wrong. Defence: compare the formula's gradient with the tiny-step gradient.
- Gradient check rule
- Run it on a handful of points, whenever the loss or its formula changes; do not use it for training.
07 · Probability by simulationProbability Is Counting, Done Many Times
A probability is the fraction of cases where something happens. When the counting is hard, you can let the computer play the game 100,000 times and count. Without it, "is this difference luck?" has no answer.
The first of Marcus's questions is answered: the demand line, and where it comes from. The second needs a way to say how surprising a result is. To do that, we first need the plain language of chance, and the fastest way to learn it is to simulate RideNow requests and count.
Start with ten requests, two of them made in the rain. The probability of rain is 2 out of 10, or 0.2. That is the whole definition: the number of cases you care about, divided by the number of cases. Everything below is this one move, repeated on larger piles.
Five ideas, each as a count
We will simulate 100,000 requests where 20% happen in rain, riders cancel more in the rain, and phone type has nothing to do with the weather. Then each idea becomes a line that counts.
- Event. Something that either happens or does not: "this request is in the rain". Its probability is the fraction of requests where it is true.
- Conditional probability. The probability of one event among only the cases where another holds. "Cancel, given rain" is the cancel rate among rainy requests only. In code: filter the rows, then count.
- Independence. Two events are independent if knowing one tells you nothing about the other. Then the chance of both is the product of the two chances.
- Expectation. The long-run average outcome: each value times its probability, added up.
- The normal distribution. The bell curve that sums and averages of many small random pieces tend to follow. It is described by a centre and a spread.
Fig. 1e.11 shows the first three ideas with the real counts from the simulation. The rain slice is small, but it has a very different cancel rate from the dry slice, and that gap is the lesson.
- The first split. 19,982 of the 100,000 requests are in rain, which is 0.1998, close to the 0.20 we set. With more simulated requests it would land closer still.
- The second split. Among rainy requests 5,003 were cancelled (0.2504); among dry ones 7,865 of 80,018 (0.0983). These two numbers are the conditional probabilities. The shaded part of each bar is the cancelled share.
Independence shows up when you compare the joint count with the product. Rain and cancel together happen in 5% of requests, while the product of their separate probabilities is 0.1998 × 0.1287 = 0.0257. The joint count is nearly double the product, so the two are not independent. Rain and Android, by contrast, give 0.1200 against 0.1199: independent.
If you want to see how base rates and Bayes' rule build on these ideas, Module 01b covers them with the fraud example. We do not repeat that here. What we need next is the bell curve, because a difference in averages follows one.
The normal distribution, with a count
Priya's test compares two average demand numbers. The normal curve tells her how far an average can wander by luck alone, so she needs its two dials and its three famous percentages.
Imagine a zone whose daily request count has a centre of 120 and a typical wobble of 15. The centre is the mean. The wobble is the standard deviation, a typical distance from the centre; Module 01b builds it step by step. A normal curve with those two numbers says how many days fall near the centre.
About 68% of days fall within one standard deviation of the mean (105 to 135 requests). About 95% fall within two (90 to 150). About 99.7% fall within three (75 to 165). A day above 150 is two standard deviations high, and the curve says that happens on 2.3% of days.
- The middle. The curve peaks at 120 requests, the mean. Days near the centre are the most common.
- The shaded tail. Days above 150 are two standard deviations out. The shaded area is 2.3% of all days, about one day in 44.
- The three bands. The brackets under the axis show how much of the curve lies within 1, 2 and 3 standard deviations: 68.3%, 95.4% and 99.7%.
The next block of code uses np.random.default_rng and scipy.stats, and you have not seen either. You only need to know that the random generator makes reproducible fake data, and that stats.norm holds the normal curve. Read the output rather than the syntax.
Step-by-step: what probability_sims.py does, in plain English
- Create a random-number generator with a fixed seed (7), so every run gives the same numbers.
- Simulate 100,000 requests. Each is in rain with probability 0.20. A request cancels with probability 0.25 in rain and 0.10 otherwise. A separate coin decides "Android" with probability 0.60.
- Print the fraction in rain and the fraction cancelled, next to the values you get by hand.
- Conditional probability: use the rain flags to pick out only the rainy rows, and average their cancel flags. Do the same for dry rows.
- Independence: compare "rain and cancel" with "rain times cancel", then "rain and Android" with its product.
- Expectation: compute the fare average by hand (6×0.5 + 10×0.3 + 20×0.2 = 10), then draw 100,000 fares and average them.
- Normal: draw 10,000 days from a bell curve with mean 120 and sd 15, count the share within 1, 2 and 3 sd, and compare with the exact curve from SciPy.
# pip install "numpy>=2.5,<2.6" "scipy>=1.14"
# Probability by simulation: events, conditional, independence, expectation, the normal curve.
import numpy as np
from scipy import stats
rng = np.random.default_rng(7)
n = 100_000 # simulated ride requests
# events: each request has a weather and a cancel flag
rain = rng.random(n) < 0.20 # 20% of requests happen in rain
cancel_chance = np.where(rain, 0.25, 0.10) # riders cancel more in rain
cancel = rng.random(n) < cancel_chance
android = rng.random(n) < 0.60 # phone type has nothing to do with weather
print("P(rain) ~", round(rain.mean(), 4), "(set to 0.20)")
print("P(cancel) ~", round(cancel.mean(), 4), "(theory 0.2*0.25 + 0.8*0.10 = 0.13)")
# conditional: keep only the rows where the condition holds, then count
print("P(cancel | rain) ~", round(cancel[rain].mean(), 4))
print("P(cancel | dry) ~", round(cancel[~rain].mean(), 4))
# independence: if A and B are independent, P(A and B) = P(A) * P(B)
for name, other in (("cancel", cancel), ("android", android)):
joint = (rain & other).mean()
product = rain.mean() * other.mean()
print(f"rain & {name:<8}: {joint:.4f} vs product {product:.4f}")
print("-> cancel is not independent of rain; android is")
# expectation: the long-run average, weighted by how likely each outcome is
fares = np.array([6.0, 10.0, 20.0])
probs = np.array([0.5, 0.3, 0.2])
print("E[fare] by hand :", float(np.sum(fares * probs)))
draws = rng.choice(fares, size=n, p=probs)
print("mean of", n, "draws:", round(draws.mean(), 3))
# the normal distribution: daily requests in one zone, mean 120, spread 15
days = rng.normal(120, 15, size=10_000)
for k in (1, 2, 3):
inside = np.mean(np.abs(days - 120) < k * 15)
print(f"within {k} sd of the mean: {inside:.3f} (curve says {stats.norm.cdf(k) - stats.norm.cdf(-k):.3f})")
print("days above 150 requests:", round(np.mean(days > 150), 4), "| curve says", round(stats.norm.sf(150, 120, 15), 4))
P(rain) ~ 0.1998 (set to 0.20)
P(cancel) ~ 0.1287 (theory 0.2*0.25 + 0.8*0.10 = 0.13)
P(cancel | rain) ~ 0.2504
P(cancel | dry) ~ 0.0983
rain & cancel : 0.0500 vs product 0.0257
rain & android : 0.1200 vs product 0.1199
-> cancel is not independent of rain; android is
E[fare] by hand : 10.0
mean of 100000 draws: 9.972
within 1 sd of the mean: 0.693 (curve says 0.683)
within 2 sd of the mean: 0.954 (curve says 0.954)
within 3 sd of the mean: 0.996 (curve says 0.997)
days above 150 requests: 0.0239 | curve says 0.0228
Read the output. The simulated rain rate (0.1998) and cancel rate (0.1287) are close to the 0.20 and 0.13 that theory predicts. The conditional rates, 0.2504 and 0.0983, are the numbers in Fig. 1e.11. The "rain and cancel" line, 0.05 against a product of 0.0257, says not independent; the Android line says independent. The fare average is 9.972 against a hand value of 10.0, and the normal-curve counts agree with the curve to within a few thousandths.
Simulation is a powerful habit. When the algebra is hard, write a loop that plays the game and counts. The hypothesis test in the next section is built entirely this way.
- Probability
- Cases you want ÷ all cases. Between 0 and 1.
- Conditional probability
- The same, counted only among cases where another event holds.
cancel[rain].mean(). - Independent
- Knowing one event says nothing about the other; P(A and B) = P(A) × P(B). Rain and cancel were not; rain and Android were.
- Expectation
- Each value times its probability, summed. Fare: 6×0.5 + 10×0.3 + 20×0.2 = 10.
- Normal distribution
- Bell curve with a mean and a standard deviation. 68% / 95% / 99.7% lie within 1 / 2 / 3 sd.
- Simulation
- When the algebra is hard, play the game many times and count. A fixed seed makes it repeatable.
08 · Hypothesis testingWas the Surge Lift Real, or Luck?
A hypothesis test asks how often pure luck would produce a gap as big as the one you saw. If luck rarely does, you have evidence the effect is real. Without it, every random wobble in a dashboard looks like a discovery.
Priya has the second of Marcus's questions to answer. On 60 rainy evenings, 30 zones got the surge test and 30 did not, and demand per zone-hour was higher in the surge group. Module 01b gave her the idea of a p-value in words. Now she builds the mechanics, starting with a case small enough for a pencil.
The test group and control group were picked at random: 30 zone-evenings each, rainy evenings only, so the weather is the same on both sides. The surge arm also had a driver bonus that shortened pickup waits. The outcome is requests per zone-hour. The comparison is the difference in averages between the two groups.
Step 1: six numbers and a pencil
Start with three surge evenings and three normal ones, so small that every case can be listed. Priya wants to know what the gap in averages would look like if the surge label meant nothing.
The surge evenings had 118, 124 and 121 requests. The normal evenings had 110, 119 and 108. The surge average is 121.0 and the normal average is 112.33, so the gap is +8.67. A skeptic says: "with only six numbers, any three could have carried the surge label."
Take the skeptic literally. If the label is meaningless, each way of choosing which 3 of the 6 numbers wear the "surge" label is equally likely. There are exactly 20 ways. For each, compute the gap in averages. Then count how many of the 20 reach +8.67 or more. That fraction is the p-value.
- The pile of ordinary gaps. Most relabelings give a gap close to 0, between −5 and +5. This is what "label means nothing" looks like.
- Our result and its twin. The two dark dots are the relabelings with a gap of +8.67 (our actual split) and +9.33. Two of 20 is 0.10, so p = 0.10. A tenth of the time, shuffling alone makes a gap this large.
Step-by-step: what permutation_by_hand.py does, in plain English
- Store the surge numbers and the normal numbers. Compute the observed gap, +8.67.
- Pool all six numbers. Use
itertools.combinationsto list every way of picking 3 positions out of 6: 20 ways. - For each way, treat the picked three as "surge" and the other three as "normal", and compute the gap in averages.
- Count the relabelings whose gap is at least the observed one (a tiny tolerance guards against rounding), and divide by 20.
- Print the p-value and the five largest gaps.
# pip install "numpy>=2.5,<2.6"
# A permutation test small enough to do with a pencil: 3 surge evenings vs 3 normal evenings.
from itertools import combinations
import numpy as np
surge = [118, 124, 121] # requests per zone-hour on surge evenings
normal = [110, 119, 108] # on normal evenings
observed = np.mean(surge) - np.mean(normal)
print("surge mean", np.mean(surge), "| normal mean", np.mean(normal), "| difference", round(observed, 3))
# if the surge label meant nothing, any 3 of the 6 numbers could have carried it.
pool = surge + normal
splits = list(combinations(range(6), 3)) # all ways to pick which 3 get the label
print("ways to relabel:", len(splits))
diffs = []
for chosen in splits:
a = [pool[i] for i in chosen]
b = [pool[i] for i in range(6) if i not in chosen]
diffs.append(np.mean(a) - np.mean(b))
diffs = np.array(diffs)
as_big = int(np.sum(diffs >= observed - 1e-9))
print("relabelings with a difference as big as ours:", as_big, "of", len(diffs))
print("one-sided p-value:", as_big / len(diffs))
print("sorted differences (top 5):", np.round(np.sort(diffs)[::-1][:5], 2))
surge mean 121.0 | normal mean 112.33333333333333 | difference 8.667
ways to relabel: 20
relabelings with a difference as big as ours: 2 of 20
one-sided p-value: 0.1
sorted differences (top 5): [9.33 8.67 7.33 5.33 3.33]
Read the output. The program finds 20 relabelings and 2 of them reach our gap, so the one-sided p-value is 0.1. The top gaps are 9.33, 8.67, 7.33, 5.33 and 3.33, the same dots as Fig. 1e.13. Counting both directions would also include the two relabelings at −8.67 and −9.33, giving 4 of 20 = 0.20. Everything a hypothesis test does is a larger version of this, with a shuffle in place of the full list.
Step 2: the real 60 rows, and a shuffle in place of a list
Sixty rows have far too many relabelings to list; 30-from-60 is over a hundred quadrillion. Priya does what a simulation always does when counting is too big: she samples. She shuffles the labels 10,000 times.
The recipe has four lines. Pool all 60 numbers. Shuffle them. Call the first 30 "control" and the last 30 "surge". Record the gap. Repeat 10,000 times. The recorded gaps show what luck alone does. Fig. 1e.14 shows them for the real data, with sizes from the lab program in section 12.
- The luck-only histogram. It centres on 0 and its typical spread (standard deviation) is 3.81 requests. When the label means nothing, gaps within about ±7.6 (two spreads) are ordinary.
- The real gap. +9.93 is 2.6 spreads out. Only 0.73% of the shuffles reach as far as 9.93 in either direction, so the two-sided p-value is 0.0073.
- The mirror image. A gap of −9.93 would have been just as surprising, so we count both tails. That is what "two-sided" means.
Two-sided is the honest choice here. Marcus did not say "show me demand rose"; he wanted to know whether the surge changed demand at all. Counting both tails gives p = 0.0073. Counting only the upper tail would halve it, and a skeptic would rightly object to that.
"If SciPy has a t-test, why shuffle the labels ten thousand times? It sounds like the long way round."
— a nine-year engineer who values libraries, right about now
The shuffle is the definition. The t-test is a formula that approximates what the shuffle does, and it works when the data is well behaved. If you only run the formula, you will not know what the p-value means, and Marcus will ask exactly that. Once you have seen the shuffle, the t-test is a shortcut you understand.
The honest downside: shuffling is random, so two runs give p-values that differ in the third decimal (0.0073 here), and it is slower on big data. The formula gives the same answer every time. Use the formula for routine work and the shuffle when the formula's assumptions are doubtful, or when you need to explain it.
Step 3: the t-test, the p-value and the confidence interval, in plain words
The shuffle gave Priya p = 0.0073. Her colleagues will ask for "the t-test" because it is standard. SciPy has it in one call, and it also gives an interval, which answers Marcus's real question: how big is the lift?
The t-test divides the gap in averages by how much that gap is expected to wobble from luck alone (its standard error). For the real data: 9.93 ÷ 3.69 = 2.69. A gap 2.7 times its own wobble is unusual. The test converts that number into a p-value, 0.0092, close to the shuffled 0.0073.
The confidence interval is a range of plausible true lifts. Ours is +2.55 to +17.32 requests per zone-hour. In plain words: the data are consistent with a real lift anywhere from small (+2.5) to large (+17), and a lift of zero is not among the plausible values. Fig. 1e.15 draws it.
- The interval. The thick bar runs from +2.55 to +17.32. It says the true lift is plausibly anywhere in that range, which is wide: the test is informative about direction, not about size.
- The estimate. The dot at +9.93 is the best single guess, but it is no more likely than other values near it.
- The "no effect" line. Zero lies outside the interval, which agrees with the small p-value. If zero had been inside, the surge would not have been shown to do anything.
The next call, stats.ttest_ind, returns a result object with a statistic, a p-value and a method for an interval. You do not need to memorise its fields yet. The anatomy below labels each part of the call, and you will use it in the lab.
res = stats.ttest_ind1(surge2, control,
equal_var=False3)
print(res.statistic, res.pvalue4)
ci = res.confidence_interval5(confidence_level=0.95)
ttest_ind. Compare the averages of two independent groups. "Independent" means different zone-evenings in each group. For the same zones measured before and after, you wantttest_rel. The mistake is usingttest_indon paired data.- The first group. The first argument is the one the lift is measured for: the result is mean(first) − mean(second). Pass them in the other order and the sign of the lift flips, which confuses readers.
equal_var=False. This is Welch's version: it does not assume both groups wobble equally. It costs almost nothing when they do, so it is the safe default. The mistake is leaving the default (True) and assuming equal spread.res.pvalue. The two-sided p-value: the chance, if only luck were at work, of a gap at least this large in either direction. It is not the chance that the effect is real.confidence_interval. The range of plausible lifts. At0.95the method is right 95 times in 100 repeats of the experiment. The mistake is reading it as "95% chance the truth is in this range".
Step 4: what the numbers do not say
Priya has p = 0.0073 and a confidence interval. Before she tells Marcus "proved", she checks how much weight one test can bear. A simulation where the truth is known shows two limits that every analyst should know.
In the simulation the true lift is +7 requests per zone-hour. We repeated the whole experiment 2,000 times. The 95% interval caught the true +7 in 1,906 of 2,000 runs, or 95.3%, so the interval does what it promises. But only 38.2% of the experiments reached p < 0.05. A 30-versus-30 test is too small to spot a +7 lift reliably.
There is a second, quieter effect. Among the experiments that did reach p < 0.05, the average measured lift was 11.04, not 7. Winning experiments are the lucky ones, so they overstate the effect. Our measured +9.93 is probably too high, and an honest report says so.
Step-by-step: what ci_coverage.py does, in plain English
- Fix the true lift at 7, which only a simulation can do. In real life you never know it.
- Repeat 2,000 times: draw 30 control values and 30 surge values (surge centred 7 higher), run Welch's t-test, take its 95% interval, and note whether the interval contains 7.
- Print the fraction of intervals that caught the truth.
- Repeat 2,000 more experiments. Count how many reach p < 0.05, and average the measured lift among just those.
# pip install "numpy>=2.5,<2.6" "scipy>=1.14"
# What "95% confidence" means: repeat the whole experiment many times and count how often the interval catches the truth.
import numpy as np
from scipy import stats
rng = np.random.default_rng(5)
true_lift = 7.0 # the real effect, known only because we are simulating
trials, caught = 2000, 0
for _ in range(trials):
control = rng.normal(112, 16, 30)
surge = rng.normal(112 + true_lift, 16, 30)
ci = stats.ttest_ind(surge, control, equal_var=False).confidence_interval(0.95)
caught += ci.low <= true_lift <= ci.high
print(f"intervals containing the true lift {true_lift}: {caught} of {trials} = {caught / trials:.3f}")
# and how often does a single experiment of this size even reach p < 0.05? (its "power")
hits, estimates_when_significant = 0, []
for _ in range(trials):
control = rng.normal(112, 16, 30)
surge = rng.normal(112 + true_lift, 16, 30)
if stats.ttest_ind(surge, control, equal_var=False).pvalue < 0.05:
hits += 1
estimates_when_significant.append(surge.mean() - control.mean())
print(f"experiments with p < 0.05: {hits / trials:.3f}")
avg = np.mean(estimates_when_significant)
print(f"average measured lift among 'significant' experiments: {avg:.2f} (truth: {true_lift})")
intervals containing the true lift 7.0: 1906 of 2000 = 0.953
experiments with p < 0.05: 0.382
average measured lift among 'significant' experiments: 11.04 (truth: 7.0)
Read the output. The first line, 0.953, is the meaning of "95%": over many repeats, about 95% of the intervals catch the truth. It says nothing about any single interval. The second line, 0.382, is the test's power, its chance of detecting a real +7 effect. The third, 11.04, is the lucky-winner inflation. Together they say: report the interval, not just the p-value, and treat the point estimate with care.
Step 5: the multiple-testing trap
The test passed, and Marcus's next move is predictable: "which zones did it work in?". Priya could test each of the 20 zones separately. This is where careful analysts get caught, so she tests the trap with data where the surge did nothing at all.
Run 20 tests where the true lift is zero. Each test has a 5% chance of a false alarm, so across 20 tests you expect about one. In our run, zone 4 shows p = 0.031. A report that said "the surge works in zone 4" would be wrong, and it would look convincing.
- The one false win. Zone 4's dot sits below the dashed 0.05 line, with p = 0.031. Nothing was happening in that zone; it is the luck you should expect once in twenty looks.
- The corrected bar. Bonferroni's fix divides the bar by the number of looks: 0.05 ÷ 20 = 0.0025. It sits almost on the axis, and no zone passes it. The fix is blunt, but it protects you.
How often does this happen? The program repeats the do-nothing experiment 2,000 times. At least one zone shows p < 0.05 in 66.4% of them, close to the theory value 1 − 0.9520 = 64.2%. Two experiments in three produce a "finding" from nothing.
Step-by-step: what multiple_testing.py does, in plain English
- For each of 20 zones, draw 30 control and 30 surge values from the same distribution, so the true effect is zero, and keep the t-test's p-value.
- Count how many of the 20 p-values fall under 0.05, and show the smallest.
- Apply the Bonferroni bar: 0.05 ÷ 20 = 0.0025, and count how many pass.
- Repeat the whole 20-zone experiment 2,000 times, in one vectorised call, and count how often at least one zone passes 0.05.
- Print the theory value for comparison.
# pip install "numpy>=2.5,<2.6" "scipy>=1.14"
# The multiple-testing trap: slice a test that did nothing into 20 zones and one of them "wins".
import numpy as np
from scipy import stats
rng = np.random.default_rng(3)
n_zones, n = 20, 30
# in EVERY zone the surge changes nothing: both arms come from the same distribution
pvals = []
for zone in range(n_zones):
control = rng.normal(110, 15, n)
surge = rng.normal(110, 15, n)
pvals.append(stats.ttest_ind(surge, control, equal_var=False).pvalue)
pvals = np.array(pvals)
print("zones with p < 0.05:", int(np.sum(pvals < 0.05)), "of", n_zones)
print("smallest p-value:", round(pvals.min(), 4), "in zone", int(pvals.argmin()) + 1)
# the fix, in its simplest form: Bonferroni divides the bar by the number of looks
bar = 0.05 / n_zones
print(f"Bonferroni bar: {bar:.4f} -> zones passing: {int(np.sum(pvals < bar))}")
# how often does a do-nothing experiment produce at least one "win"?
wins = 0
trials = 2000
for _ in range(trials):
a = rng.normal(110, 15, (n_zones, n))
b = rng.normal(110, 15, (n_zones, n))
p = stats.ttest_ind(a, b, axis=1, equal_var=False).pvalue
wins += np.any(p < 0.05)
print(f"at least one p<0.05 in {trials} do-nothing experiments: {wins / trials:.3f}")
print(f"theory: 1 - 0.95**{n_zones} = {1 - 0.95 ** n_zones:.3f}")
zones with p < 0.05: 1 of 20
smallest p-value: 0.031 in zone 4
Bonferroni bar: 0.0025 -> zones passing: 0
at least one p<0.05 in 2000 do-nothing experiments: 0.664
theory: 1 - 0.95**20 = 0.642
Read the output. One of 20 zones passes at 0.05, with a smallest p of 0.031 in zone 4. At the corrected bar of 0.0025 none pass. Across 2,000 repeats, 66.4% of experiments contained at least one false win, near the theory 64.2%. The rule that follows: decide how many comparisons you will make before you look, and correct the bar for that number.
Bonferroni is the simplest fix, and it is conservative. Methods that control the share of false discoveries, such as Benjamini-Hochberg, lose less power; the statsmodels library has them. Priya does not need those for one report. She needs to say "we tested one question, and slicing by zone is exploratory".
Questions you might be asking now
Four questions that hypothesis tests usually raise. Every answer uses the six evenings from the pencil exercise: surge = 118, 124, 121 and normal = 110, 119, 108, with a gap of +8.67.
| Group | Values | Average |
|---|---|---|
| Surge | 118, 124, 121 | 121.00 |
| Normal | 110, 119, 108 | 112.33 |
| Gap | +8.67 | |
What does p = 0.10 actually mean? Is it the chance that the surge does nothing?
No. The p-value is the fraction of relabelings that match or beat the real gap when the label means nothing. For our six numbers that fraction is 2 of 20 = 0.10. It does not say how likely the surge is to work.
It answers a narrower question: "if the label were meaningless, how often would luck alone give a gap this big?". The reverse question, "how likely is it that the surge works?", needs prior beliefs as well, which is the Bayesian reasoning in Module 01b.
- List the relabelings. There are 20 ways to pick 3 of 6 numbers as "surge".
- Gap for each. Our split gives +8.67, and one other gives +9.33. The remaining 18 are all smaller.
- Count the matches. 2 of 20 reach +8.67, so p = 2 ÷ 20 = 0.10.
| Reading | True? |
|---|---|
| "If the label meant nothing, luck would give a gap this big 1 time in 10." | Yes |
| "There is a 10% chance the surge does nothing." | No |
| "There is a 90% chance the surge works." | No |
A p-value measures how surprising the data is under "no effect", not how likely "no effect" is.
Why does shuffling the labels test anything?
If the surge label did nothing, the six numbers would look the same whichever three we called "surge". Shuffling the labels shows what gaps appear when the label is meaningless. Comparing the real gap to that set tells you whether the real gap stands out.
Think of dealing six cards into two hands of three. If hand one is no better than hand two, any deal is equally likely. Our real deal is one of the 20.
- Real deal. Surge = {118, 124, 121}: gap +8.67.
- Another deal. Surge = {124, 121, 119}: mean 121.33, other hand {118, 110, 108} mean 112, gap +9.33.
- A deal the other way. Surge = {110, 108, 118}: mean 112, other hand mean 121.33, gap −9.33.
Across all 20, gaps range from −9.33 to +9.33 and cluster near 0. Our +8.67 is near the edge but not outside, so the data does not rule out luck. With 60 rows the same method gives p = 0.0073, because there are far fewer ways for luck to look this strong.
Shuffling shows what "no effect" looks like, so you can see whether your result looks different.
So there is a 95% chance the true lift is inside the interval, right?
Not quite. The 95% describes the method: if you repeated the experiment many times, about 95% of the intervals would contain the truth. Any single interval either contains it or does not.
The simulation in ci_coverage.py shows it. We knew the true lift (+7) and repeated the experiment 2,000 times.
- Repeat. Draw new control and surge data and compute a 95% interval each time.
- Count. 1,906 of the 2,000 intervals contained +7.
- Divide. 1,906 ÷ 2,000 = 0.953.
The practical reading is still useful: "values inside the interval are consistent with the data, values outside are not". The honest limit is that the interval depends on assumptions, such as independent zone-evenings. If the same zone appears many times, the interval is too narrow.
"95%" is about the method over many repeats, not about one interval.
The real lift is +7 but we measured +9.93. Is something wrong?
Nothing is wrong. A single experiment lands above or below the truth by luck, and experiments that reach p < 0.05 are mostly the high ones. In the simulation, the "significant" experiments averaged +11.04 against a truth of +7.
- One experiment. The measured lift varies around the truth. Its typical wobble is the standard error, about 4 requests for 30 versus 30.
- Filter on success. Only 38.2% of runs reached p < 0.05. Those are mainly the ones whose luck pushed the lift up.
- Average the winners. 11.04 is higher than 7, so selecting on significance inflates the estimate.
The practical rule: when you read a headline effect from one test, expect the true value to be smaller, and plan the rollout on the lower end of the interval.
Winning experiments overstate the effect; plan on the lower end of the interval.
- Hypothesis test
- Ask how often "no effect" would produce a result as extreme as yours. Rare means evidence.
- Permutation test
- Shuffle the labels many times; the fraction of shuffles with a gap as big as the real one is the p-value.
- p-value
- The share of luck-only outcomes at least as extreme as yours. Not the probability that the effect is real.
- t-test (Welch)
- The gap divided by its expected wobble.
stats.ttest_ind(a, b, equal_var=False). - Confidence interval
- Plausible true effects. 95% means the method catches the truth in about 95 of 100 repeats.
- Two-sided
- Count both directions. The default unless you committed to one direction in advance.
- Multiple testing
- Twenty looks give about one false win. Divide the bar by the number of looks (Bonferroni) or plan the questions first.
- Power and inflation
- A 30-v-30 test detected a real +7 lift in 38% of runs; the winners averaged +11.
09 · EmbeddingsEmbeddings: Vectors Where Angle Means Meaning
An embedding turns a word or a sentence into a vector so that similar meanings point in similar directions. Then "find tickets like this one" becomes "find vectors with a high cosine". Without it, search only matches identical words.
Priya's two answers are done, but Marcus has a follow-up: RideNow's support team receives thousands of tickets about late pickups and surge fares, worded a hundred ways. Grouping them needs a measure of "means the same thing". The vectors and cosines she has just learned are exactly that measure, once the words become vectors.
Start with a toy you can hold in your head. Invent three axes: "is it a vehicle trip", "is it about money" and "is it about waiting". Give each word three numbers by hand. "Fare" is [0.2, 0.9, 0.1], mostly about money. "Wait" is [0.15, 0.1, 0.95], mostly about waiting. Now the cosine from the first section can compare meanings.
- Fare and price. Both arrows lean toward the money axis. Their cosine is 0.993, nearly the same direction, so these two words mean nearly the same thing.
- Queue and wait. Both lean toward the waiting axis, with a cosine of 0.999.
- Taxi against fare, and taxi against queue. These pairs have cosines of 0.434 and 0.430: related to ride-hailing, but not close. Taxi lives mostly on the vehicle axis, which this drawing leaves out.
Step-by-step: what embeddings_toy.py does, in plain English
- Store seven words, each as a hand-made 3-number vector on the three invented axes.
- Define
cosine(u, v), the same function as in the vectors section. - Print the cosine for five word pairs, three similar pairs and two unrelated ones.
- Rank every other word by cosine against "wait" and print the top three. That is nearest-neighbour search.
- Subtract the vector for "taxi" from "fare" to get a direction, add it to "cab", and find the closest word.
# pip install "numpy>=2.5,<2.6"
# Embeddings as vectors: hand-made 3-d "meaning" coordinates for ride-hailing words.
import numpy as np
# axes (made up by hand): [is-a-vehicle-trip, is-about-money, is-about-waiting]
words = {
"taxi": np.array([0.9, 0.2, 0.3]),
"cab": np.array([0.85, 0.25, 0.35]),
"ride": np.array([0.8, 0.3, 0.3]),
"fare": np.array([0.2, 0.9, 0.1]),
"price": np.array([0.1, 0.95, 0.15]),
"queue": np.array([0.1, 0.1, 0.9]),
"wait": np.array([0.15, 0.1, 0.95]),
}
def cosine(u, v):
return float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)))
for a, b in [("taxi", "cab"), ("fare", "price"), ("queue", "wait"), ("taxi", "fare"), ("taxi", "queue")]:
print(f"cosine({a:>5}, {b:<5}) = {cosine(words[a], words[b]):.3f}")
# nearest neighbours: the heart of semantic search
query = "wait"
ranked = sorted(((cosine(words[query], v), w) for w, v in words.items() if w != query), reverse=True)
print(f"closest to '{query}':", [(w, round(s, 3)) for s, w in ranked[:3]])
# the classic trick: directions carry meaning, so arithmetic on them works
shift = words["fare"] - words["taxi"]
print("fare - taxi =", np.round(shift, 2))
moved = words["cab"] + shift
best = max((cosine(moved, v), w) for w, v in words.items() if w != "cab")
print("cab + (fare - taxi) closest to:", best[1])
cosine( taxi, cab ) = 0.996
cosine( fare, price) = 0.993
cosine(queue, wait ) = 0.999
cosine( taxi, fare ) = 0.434
cosine( taxi, queue) = 0.430
closest to 'wait': [('queue', 0.999), ('cab', 0.527), ('ride', 0.497)]
fare - taxi = [-0.7 0.7 -0.2]
cab + (fare - taxi) closest to: price
Read the output. The similar pairs score 0.993 to 0.999 and the unrelated pairs about 0.43. The nearest neighbour of "wait" is "queue" at 0.999, with "cab" a distant second at 0.527. That ranking is a search engine in four lines: embed everything, then sort by cosine. The last line shows a famous trick: a direction such as "fare minus taxi" can be added to another word and lands near "price". It works here because we built the vectors to make it work.
The honest limit: these axes are invented and tiny. A real model has hundreds of axes that nobody labelled, learned from huge amounts of text. You cannot say what axis 87 means. You can only trust that similar texts point the same way.
A real model, run locally
The toy proves the idea; Marcus's tickets need the real thing. Priya loads a small public model that turns any sentence into a vector of 384 numbers. It runs on a laptop CPU and needs no account or API key.
This code uses sentence-transformers, a library that wraps a language model. You do not need to know how the model works inside; Module 05 opens it up. The only thing to see is that sentences go in and vectors come out.
- The sentences. They share no content words. "Took forever to arrive" and "very late" are the same complaint in different language.
- The model. The same small model reads both sentences. Same model, same 384 axes: that is what makes the two vectors comparable.
- The cosine. The two vectors have length 1, so their dot product is the cosine, 0.513, the highest score in the set for a lateness sentence.
Step-by-step: what embeddings_real.py does, in plain English
- Tell the Hugging Face library to work offline (it skips the network and uses the model file already on disk).
- Load
all-MiniLM-L6-v2, a small public model (about 90 MB). - Make five RideNow-style sentences: two about lateness, two about price, one unrelated.
model.encodeturns each into a 384-number vector, scaled to length 1 so that the dot product is the cosine.- Multiply the vectors by their own transpose to get every pair's cosine, and print the ten pairs.
# pip install "sentence-transformers>=3,<7" # pulls in torch: about 2 GB of RAM while it runs
# The first run downloads all-MiniLM-L6-v2 (about 90 MB) from Hugging Face; after that it runs offline.
import os
os.environ.setdefault("HF_HUB_OFFLINE", "1") # remove this line for the first, downloading run
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
sentences = [
"My driver took forever to arrive",
"The pickup was very late",
"Why is the fare so expensive tonight?",
"Surge pricing doubled my price in the rain",
"How do I change my profile photo?",
]
vecs = model.encode(sentences, normalize_embeddings=True) # unit length, so dot product = cosine
print("embedding shape:", vecs.shape)
sims = vecs @ vecs.T
for i in range(len(sentences)):
for j in range(i + 1, len(sentences)):
print(f"{sims[i, j]:.3f} {sentences[i]!r} vs {sentences[j]!r}")
This model was already cached on the course machine, so the script ran offline. On a fresh machine, delete the HF_HUB_OFFLINE line for the first run: it downloads about 90 MB from Hugging Face once, and later runs work offline. The output we measured:
embedding shape: (5, 384)
0.513 'My driver took forever to arrive' vs 'The pickup was very late'
0.235 'My driver took forever to arrive' vs 'Why is the fare so expensive tonight?'
0.167 'My driver took forever to arrive' vs 'Surge pricing doubled my price in the rain'
-0.010 'My driver took forever to arrive' vs 'How do I change my profile photo?'
0.230 'The pickup was very late' vs 'Why is the fare so expensive tonight?'
0.118 'The pickup was very late' vs 'Surge pricing doubled my price in the rain'
-0.078 'The pickup was very late' vs 'How do I change my profile photo?'
0.412 'Why is the fare so expensive tonight?' vs 'Surge pricing doubled my price in the rain'
0.028 'Why is the fare so expensive tonight?' vs 'How do I change my profile photo?'
0.092 'Surge pricing doubled my price in the rain' vs 'How do I change my profile photo?'
Read the output. "My driver took forever to arrive" and "The pickup was very late" share no content words, yet score 0.513, the highest pair involving lateness. The two price sentences score 0.412. Anything compared with "How do I change my profile photo?" is near zero or slightly negative. Real models give lower cosines than our toy: 0.4 to 0.5 already means "clearly related". The scale is model-specific, so you pick thresholds by looking at examples.
"This is keyword search with extra steps. Why not just match words?"
— a nine-year engineer who has run Elasticsearch, right about now
Keyword search needs shared words, and the first pair above has none: "forever to arrive" and "pickup was very late". The embedding matches them by meaning, with a cosine of 0.513, which is the highest pair in the set. That is the case embeddings exist for.
The honest downside: embeddings blur exact details. They can match "no surge" with "surge", ignore a specific order number, and cost a model to run. Production search usually combines both, with keywords for exact terms and embeddings for meaning. Module 08 builds that hybrid.
Two bridges forward. In Module 05 you will open the model that produces these vectors and see why a sentence's vector depends on its context. In Module 08, the "sort by cosine" idea becomes a vector database and a retrieval pipeline over millions of documents. Every piece of maths used there is on this page.
- Embedding
- A vector for a word, sentence or image where similar meanings have similar directions.
- Similarity
- Cosine of two embeddings. High means similar meaning; scale depends on the model.
- Nearest neighbour
- Embed everything, sort by cosine to the query, take the top few. That is semantic search.
- Normalised vectors
- Scaled to length 1, so the dot product equals the cosine.
normalize_embeddings=True. - Limits
- Blur exact details and negation; unlabelled axes; need a model; combine with keyword search for exact terms.
10 · The stack, and whyHow Professionals Do It, and Why These Tools
In real work you rarely write the loop or the shuffle yourself. You call a library that does it faster and checks the edge cases. This section names the tools you used, the rivals you could have used, and the situations that should make you switch.
Priya has built the gradient loop and the shuffle from scratch, and she has seen the library calls that match them. Before the report goes out she needs to be able to answer the next question: why these tools and not others? Interviewers ask "why not X?" more often than "how does X work?".
Two habits run through the module. The first is to build the idea once with plain NumPy, so you know what the library does. The second is to use the library for real work, because it is tested, fast and familiar to reviewers. The table below places each tool in that scheme.
The stack, and why
The one question that decides most of these rows: does the job need automatic gradients or a GPU, or is it small numbers on a laptop that a reader should be able to check by hand?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Arrays and linear algebra | NumPy 2.5 | PyTorch 2.12 tensors, JAX | Simplest, runs anywhere, numbers can be checked with a pencil. It is bad at GPUs and has no automatic gradients. | PyTorch when you need automatic gradients or a GPU: any model with more than about 100,000 parameters, or training that takes more than a few minutes on CPU (Module 04). JAX when you want to compile and vectorise your own numerical code for research. |
| Derivatives | A hand formula, checked by a tiny-step gradient; SymPy for algebra | Automatic differentiation in PyTorch or JAX | Writing the formula teaches what a gradient is, and the check catches bugs. It does not scale to many layers. | Automatic differentiation as soon as the model has more than one layer or you change the loss weekly. Keep a gradient check as a unit test. |
| Statistical tests | SciPy 1.18 stats | statsmodels 0.14, pingouin 0.6 | One call gives the statistic, p-value and interval, with few dependencies. It has no regression tables and no multiple-test corrections. | statsmodels for regression with adjustments, ANOVA across more than two groups, or Benjamini-Hochberg corrections. pingouin for effect sizes and tidy tables, if its GPL-3.0 licence is acceptable in your company. |
| Resampling | Our own NumPy shuffle loop | scipy.stats.permutation_test, scipy.stats.bootstrap | You see exactly what is being counted. It is easy to get the tail wrong or forget the seed. | The SciPy functions for a report others will review, or when the statistic is not a plain mean (a median, a ratio, a percentile). |
| Plotting | matplotlib 3.11 | plotly, seaborn | Static PNGs that save to a file and need no browser. The API is verbose. | plotly when readers need hover and zoom in a dashboard; seaborn for quick statistical plots in a notebook. |
| Embeddings | sentence-transformers 6.0 with all-MiniLM-L6-v2, local | OpenAI text-embedding-3 API, open models such as BGE-M3 | Free, private, offline after one 90 MB download. It cuts text after about 256 tokens, uses 1 to 2 GB of RAM, and is weaker on other languages. | An API when you embed more than a few hundred thousand texts without a GPU, or need strong multilingual quality. A larger open model when your documents are longer than about 256 tokens. |
| Where code runs | Plain .py scripts | Jupyter, marimo notebooks | Reproducible, easy to diff and to run in CI. No inline charts. | Jupyter when you explore interactively with charts; marimo when you want a reactive notebook stored as a plain Python file. |
NumPy and SciPy are enough for everything on this page; move to PyTorch the day you need gradients you do not want to derive.
| The question | Choose | Avoid when | Typical output |
|---|---|---|---|
| Do two independent groups have different averages? | Welch t-test: stats.ttest_ind(a, b, equal_var=False) | The same zones appear in both groups (paired data); the data has huge outliers | t, p-value, confidence interval |
| Same, with few rows or a strange shape | Permutation test: shuffle the labels yourself | You need an answer that is exactly the same on each run | p-value to about 3 decimals, with run-to-run noise |
| The same zones before and after | Paired test: stats.ttest_rel | Different zones in the two periods | t, p-value for the average difference |
| Three or more groups | ANOVA in statsmodels or pingouin | Only two groups (use the t-test) | F statistic, p-value, then follow-up tests |
| Rates such as cancel or no-cancel | A proportions test or chi-square, stats.chi2_contingency | Counts are tiny (under about 5 per cell) | chi-square, p-value |
| Twenty slices of one test | Correct for the number of looks (Bonferroni, Benjamini-Hochberg) | You planned exactly one comparison | Adjusted p-values |
Step-by-step: how to choose a test, in plain English
- Write the question in one sentence: "Did surge change average demand?"
- Ask whether the two groups are different units (independent) or the same units measured twice (paired).
- Count the groups and the number of comparisons you plan. More than two groups, or more than one comparison, means ANOVA or a correction.
- Pick the tool from the table. If you are unsure whether the formula applies, run the shuffle too and see whether it agrees.
- Report the estimate, the interval and the p-value together, never the p-value alone.
There are no dumb questions
- Why not simply use scikit-learn's
LinearRegressionfor the demand line? - For production, you should. We built the loop to learn what that class does underneath, and
np.polyfitmatched our answer to four decimals. Scikit-learn solves the line in one algebra step, which is exact and fast for a line. Gradient descent matters when no such step exists, as in neural networks. - Is a small p-value the same as a big effect?
- No. A tiny lift measured on millions of rows can have p near zero and be worth nothing in money. A big lift on 6 rows can have a large p-value. Report the size (the interval) first and the p-value second.
- What is the difference between a p-value of 0.049 and 0.051?
- Almost nothing. The 0.05 line is a convention, not a cliff. Treat 0.049 and 0.051 as the same weak-to-moderate evidence, and decide with the interval and the cost of being wrong.
- Do I have to be able to derive gradients by hand?
- You should be able to for a line, as you just did, and to explain the chain rule on a small graph. For a real network you let PyTorch do it, but you still need the idea to read a loss curve and to debug a model that does not learn.
- How many shuffles are enough?
- 10,000 gives a p-value accurate to about a tenth of a percentage point near 0.01. For a p-value near 0.0001 you need far more shuffles, or an exact method.
"Marcus, here is the answer in three lines. Demand falls about four requests an hour for every 0.1 of surge, and I can show you the loop that computes it. On the rainy-evening test, surge evenings averaged about ten more requests per zone-hour. If surge did nothing, shuffled labels would match that gap less than 1 time in 100. The plausible lift is between 2.5 and 17, so plan the rollout for the low end, and I would not claim success in any single zone."
The ROI frame: the test itself ran 30 zone-evenings on the old pricing. A correctly sized rollout across 140 zones is worth more than the test, and a wrong one, based on a lucky number, costs more than the test saved. Statistics is the cheapest insurance in the project.
- NumPy vs PyTorch
- NumPy for small checkable maths; PyTorch when you need automatic gradients or a GPU.
- SciPy vs statsmodels vs pingouin
- SciPy for one test; statsmodels for regression and corrections; pingouin for effect sizes (GPL-3.0).
- Local vs API embeddings
- Local MiniLM for free, private, modest scale; API or larger model for volume, long text or other languages.
- Test choice
- Independent groups: Welch. Same units twice: paired. Three or more: ANOVA. Many looks: correct the bar.
11 · Under the hoodThe Math, If You Want It
Every idea in this module has a short formula behind it. They are optional: the code above already did the work. Open them when you want the exact statement, or when an interviewer asks for it.
Priya's report is built, and each number in it came from code. If Marcus's analysts ask for the formulas behind the code, here they are, in the same order as the module, each with every symbol spoken aloud and a worked number from the page.
| Symbol | How to say it | What it means in plain words |
|---|---|---|
| u · v | "u dot v" | Multiply matching slots of u and v, then add the products. |
| ‖v‖ | "norm of v", or "length of v" | The length of the arrow v: square every slot, add, take the square root. |
| cos θ | "cosine theta" | The cosine similarity; θ (theta) is the angle between two arrows. |
| √ | "square root" | The number that, multiplied by itself, gives what is inside. |
| Σ | "sigma", "sum of" | Add up the expression for every item, from the first to the last. |
| x̄ | "x-bar" | The average of the x values. |
| f′(x), d/dx | "f-prime of x", "d by dx" | The derivative: the slope of a tiny step in x. |
| ∂L/∂w | "partial L, partial w" | The slope of the loss L when only w is nudged and everything else is held still. |
| η | "eta" | The learning rate: how big each downhill step is. |
| μ, σ | "mu", "sigma" | The centre (mean) and the typical spread (standard deviation) of a bell curve. |
| s, n | "s", "n" | A sample's standard deviation, and how many values are in the sample. |
| SE | "standard error" | How much an average is expected to wobble from luck alone. |
| α, m | "alpha", "m" | The bar for p-values (usually 0.05), and the number of tests you run. |
| ≈, ± | "approximately", "plus or minus" | Nearly equal; and a range on both sides of a number. |
The dot product and the cosine — why dividing by the lengths removes size
The dot product of two vectors with n slots is the sum, over every slot, of the two matching numbers multiplied:
u · v = Σ ui vi = ‖u‖ ‖v‖ cos θ
Symbol key: u · v is the dot product; Σ ("sigma") means add up the term for every slot i from 1 to n; ui and vi are slot i of each vector; ‖u‖ is the length of u, which is √(Σ ui²); cos θ is the cosine of the angle θ ("theta") between the two arrows.
The second equality is the useful one: the dot product equals both lengths times the cosine of the angle. Divide both sides by the lengths and you get the cosine alone:
cos θ = (u · v) ÷ (‖u‖ ‖v‖)
Symbol key: ÷ is divide; the other symbols are as above. With our numbers: u · v = 24, ‖a‖ = ‖b‖ = 5, so cos θ = 24 ÷ 25 = 0.96, and θ = 16.3°. A zone with doubled counts doubles ‖u‖ and doubles u · v, so the ratio does not change: that is why the airport and downtown scored exactly 1.
The derivative and the chain rule — the slope of a tiny step, written down
The derivative is the number the slope of a step settles on as the step shrinks:
f′(x) = limit as h → 0 of [ f(x + h) − f(x) ] ÷ h
Symbol key: f′(x) ("f-prime of x") is the derivative; h is the size of the step; "limit as h → 0" means "what the value settles on as h shrinks toward zero"; ÷ is divide. For f(x) = x² at x = 3: [ (3 + h)² − 9 ] ÷ h = 6 + h, which settles on 6.
The chain rule says that when one quantity depends on another through a middle step, the slopes multiply:
dL/dw = (dL/dp) × (dp/da) × (da/dw)
Symbol key: L is the loss, p the prediction, a the weighted input a = w·x, and w the weight; each d/d fraction is the slope of the top quantity with respect to the bottom one; × is multiply. In Fig. 1e.8: (−6) × 1 × 3 = −18.
The gradient of the mean squared error — where the two lines of code come from
For a line ŷ = w·x + b and n data points, the loss is the average of the squared errors:
L(w, b) = (1/n) Σ ( w·xi + b − yi )²
Symbol key: L is the loss; ŷ ("y-hat") is a prediction; w is the slope; b is the intercept; xi and yi are the i-th input and true output; Σ adds over all n points; (1/n) turns the sum into an average. Call each error ei = w·xi + b − yi.
Differentiate each squared error with the chain rule: the derivative of ei² is 2 ei times the derivative of ei. Inside, ei changes by xi per unit of w and by 1 per unit of b:
∂L/∂w = (2/n) Σ ei xi ∂L/∂b = (2/n) Σ ei
Symbol key: ∂L/∂w ("partial L, partial w") is the slope of the loss when only w moves; ei is the error at point i. In code these are 2 * np.mean(errors * x) and 2 * np.mean(errors). The update rule then is:
w ← w − η ∂L/∂w b ← b − η ∂L/∂b
Symbol key: ← means "is replaced by"; η ("eta") is the learning rate. With the two points and the sum instead of the average: ∂L/∂w = 2(−3×1 + −5×2) = −26, and w becomes 0 − 0.05 × (−26) = 1.3.
The normal curve and the z-score
A value's z-score says how many standard deviations it is from the mean:
z = (x − μ) ÷ σ
Symbol key: x is the value; μ ("mu") is the mean; σ ("sigma") is the standard deviation; z is the z-score. A day with 150 requests, when μ = 120 and σ = 15, has z = (150 − 120) ÷ 15 = 2. The normal curve puts about 2.3% of days above z = 2, and 68.3%, 95.4% and 99.7% within z = ±1, ±2, ±3.
The curve itself is:
density(x) = [1 ÷ (σ √(2π))] × e−(x − μ)² ÷ (2σ²)
Symbol key: density(x) is the height of the curve at x; π ("pi") is 3.14159…; e is 2.71828…, the base of natural logarithms; the exponent −(x − μ)² ÷ (2σ²) is what makes the curve fall away on both sides. You never compute it by hand; stats.norm does.
The Welch t statistic, the standard error and the confidence interval
The expected wobble of the gap in averages, called the standard error, is built from each group's spread and size:
SE = √( s1² ÷ n1 + s2² ÷ n2 )
Symbol key: SE is the standard error; s1 and s2 are the two groups' standard deviations; n1 and n2 are their sizes; ² is squared. With s1 = 13.96 (surge), s2 = 14.60 (control) and n = 30 each: SE = √(6.496 + 7.105) = √13.60 = 3.69.
The t statistic is the gap divided by its wobble, and the interval is the gap plus or minus a multiple of the wobble:
t = ( x̄1 − x̄2 ) ÷ SE 95% interval = ( x̄1 − x̄2 ) ± tcrit × SE
Symbol key: x̄1 and x̄2 ("x-bar one", "x-bar two") are the group averages, 119.53 and 109.60; ± is plus or minus; tcrit is the cut-off from the t distribution, about 2.00 for 57.9 degrees of freedom. Result: t = 9.93 ÷ 3.69 = 2.69, and the interval is 9.93 ± 2.00 × 3.69 = 9.93 ± 7.38, from +2.55 to +17.32, the numbers SciPy printed.
The "Welch" part is how the degrees of freedom (57.9 rather than 58) are adjusted when the two spreads differ. It is why equal_var=False is the safe default.
Why twenty looks give a false win two times in three
If each test has a chance α of a false alarm and the tests are independent, the chance of at least one false alarm in m tests is:
P(at least one) = 1 − (1 − α)m
Symbol key: α ("alpha") is the p-value bar, 0.05; m is the number of tests, 20; (1 − α) is the chance of no false alarm in one test; raising it to the power m gives the chance of none in all m tests; subtracting from 1 gives the chance of at least one. With the numbers: 1 − 0.9520 = 1 − 0.358 = 0.642, and the simulation gave 0.664.
Bonferroni's fix shrinks the bar to α ÷ m = 0.05 ÷ 20 = 0.0025, which keeps the chance of any false alarm at or below α. The price is lost power: real effects need a smaller p-value to count.
- Cosine
- cos θ = (u · v) ÷ (‖u‖ ‖v‖): the dot product with both lengths divided out.
- Derivative
- f′(x) = the value of [f(x + h) − f(x)] ÷ h as h shrinks to 0.
- Chain rule
- Multiply the slopes along the path: dL/dw = dL/dp × dp/da × da/dw.
- MSE gradient
- ∂L/∂w = (2/n) Σ e·x and ∂L/∂b = (2/n) Σ e; update w ← w − η ∂L/∂w.
- z-score
- z = (x − μ) ÷ σ: distance from the mean in standard deviations.
- Welch t and interval
- SE = √(s₁²/n₁ + s₂²/n₂); t = gap ÷ SE; interval = gap ± tcrit × SE.
- Many looks
- P(at least one false win) = 1 − (1 − α)m; Bonferroni bar = α ÷ m.
12 · The labTest the Surge Claim on Ride-Hailing Demand Data
The lab turns the pencil example into a repeatable report. You load demand data, measure the gap, test it by shuffling, test it again with SciPy, and write the result in words a sceptical VP can read.
Priya has the ideas and the pictures. Marcus wants a document he can read in two minutes and challenge in ten. So she turns the whole analysis into one program that takes the demand table in and prints the verdict out, built in five chunks that each run on their own.
The data here is simulated to look like the real export: 30 control and 30 surge zone-evenings on rainy days, six zones, requests per zone-hour. The true lift in the simulation is +7, which only a simulation can promise. Chunk 1 writes the data to a CSV file and loads it back, so replacing it with your real file is a one-line change.
- The data and the gap. Sixty rows split 30 and 30. The averages are 109.60 and 119.53, so the gap is +9.93.
- The shuffle. The permutation step shuffles the labels 10,000 times and finds p = 0.0073. The two routes after it, SciPy and the report, only restate or confirm this number.
Build it in chunks
We build demand_tests.py in five chunks: load and validate, difference in means, permutation test, t-test with an interval, and the report. Each chunk runs on its own, and the whole file comes after chunk 5.
-
Chunk 1 — make the demand data, load it, and refuse bad rows
Why this comes first: a test on bad rows gives a confident wrong answer, so the program checks the labels and the counts before any statistics.
Step-by-step: what chunk 1 does, in plain English
- Import NumPy and pandas, the table library from Module 01c.
- Define
simulate_demand: draw 30 control and 30 surge values from bell curves centred 7 apart, round to whole requests, and build a table with columnsarm,zoneandrequests. - Save the table to
rain_demand.csv, then read it back, as you would read a real export. assertthat the only arm labels arecontrolandsurge, and that no request count is missing or negative.- Split the counts into two NumPy arrays,
controlandsurge, and print how many rows each has.
demand_tests.py — chunk 1runs offline# pip install "numpy>=2.5,<2.6" "pandas>=2.2" "scipy>=1.14" # Did the rainy-evening surge test raise demand? Simulated RideNow data, tested by hand and with scipy. import numpy as np import pandas as pd # ── chunk 1: make the demand data, save it, load it, refuse bad rows ── def simulate_demand(seed=11, n_per_arm=30): rng = np.random.default_rng(seed) control = rng.normal(112, 16, n_per_arm) # normal pricing, rainy evening treated = rng.normal(119, 16, n_per_arm) # surge test, same kind of evening return pd.DataFrame({ "arm": ["control"] * n_per_arm + ["surge"] * n_per_arm, "zone": [f"Z{i % 6 + 1}" for i in range(2 * n_per_arm)], "requests": np.round(np.concatenate([control, treated])).astype(int), }) simulate_demand().to_csv("rain_demand.csv", index=False) # swap in your real export here df = pd.read_csv("rain_demand.csv") assert set(df["arm"]) == {"control", "surge"}, "unexpected arm label" assert df["requests"].notna().all() and (df["requests"] >= 0).all(), "bad request counts" control = df.loc[df["arm"] == "control", "requests"].to_numpy(dtype=float) surge = df.loc[df["arm"] == "surge", "requests"].to_numpy(dtype=float) print(f"loaded {len(df)} rows: {len(control)} control, {len(surge)} surge")pd.read_csv— reads a file into a table..to_numpy(dtype=float)— turns a column into a NumPy array.Run
python3 demand_tests.py. You should see:terminalactual outputloaded 60 rows: 30 control, 30 surge -
Chunk 2 — the difference in means
Why this comes next: the claim is "surge raised demand", and the first thing to measure is how much, with the spread beside it so the gap has context.
Step-by-step: what chunk 2 does, in plain English
- Compute
observed: the surge average minus the control average. Surge comes first, so a positive number means a lift. - Print both averages and the gap.
- Print each group's standard deviation.
ddof=1divides by n − 1, the usual choice for a sample.
demand_tests.py — chunk 2runs offlineobserved = surge.mean() - control.mean() print(f"control mean {control.mean():.2f} | surge mean {surge.mean():.2f} | difference {observed:+.2f}") print(f"spread (sd): control {control.std(ddof=1):.2f} | surge {surge.std(ddof=1):.2f}").std(ddof=1)— sample standard deviation.The new lines at the end:
terminalactual outputcontrol mean 109.60 | surge mean 119.53 | difference +9.93 spread (sd): control 14.60 | surge 13.96 - Compute
-
Chunk 3 — the permutation test, by hand
Why this comes next: it is the 20-relabelings idea from section 08, with a shuffle instead of a list. It needs only NumPy, so it is the version you can explain to anyone.
Step-by-step: what chunk 3 does, in plain English
- Create a random generator with seed 0 so the answer repeats.
- Pool all 60 numbers into one array.
- Ten thousand times: shuffle the pool, call the last 30 "surge" and the first 30 "control", and record the gap in averages.
- The p-value is the fraction of shuffled gaps whose size (absolute value) is at least the observed one: two-sided.
- Print the spread and range of the shuffled gaps, and the p-value.
demand_tests.py — chunk 3runs offlinerng = np.random.default_rng(0) pool = np.concatenate([control, surge]) shuffled_diffs = np.empty(10_000) for i in range(10_000): rng.shuffle(pool) # throw the labels away shuffled_diffs[i] = pool[len(control):].mean() - pool[:len(control)].mean() p_perm = np.mean(np.abs(shuffled_diffs) >= abs(observed)) # two-sided print(f"shuffled differences: sd {shuffled_diffs.std():.2f}, range {shuffled_diffs.min():+.1f} to {shuffled_diffs.max():+.1f}") print(f"permutation p-value (two-sided): {p_perm:.4f}")rng.shuffle— reorders an array in place.np.abs(...) >= ...then.mean()— the fraction of cases that are true.The new lines at the end:
terminalactual outputshuffled differences: sd 3.81, range -13.7 to +14.8 permutation p-value (two-sided): 0.0073 -
Chunk 4 — the same question with SciPy, plus a confidence interval
Why this comes next: the shuffle answered "is it luck?", and the library gives a second opinion and the interval that says how big. If the two disagree badly, something is wrong.
Step-by-step: what chunk 4 does, in plain English
- Import
statsfrom SciPy. - Call
stats.ttest_ind(surge, control, equal_var=False), Welch's t-test, which does not assume equal spreads. - Ask the result for its 95% confidence interval.
- Print the t statistic, the p-value, the degrees of freedom, and the interval.
demand_tests.py — chunk 4runs offlinefrom scipy import stats res = stats.ttest_ind(surge, control, equal_var=False) # Welch: allows unequal spreads ci = res.confidence_interval(confidence_level=0.95) print(f"Welch t = {res.statistic:.3f}, p = {res.pvalue:.4f}, df = {res.df:.1f}") print(f"95% CI for the lift: {ci.low:+.2f} to {ci.high:+.2f} requests per zone-hour")res.confidence_interval(confidence_level=0.95)— an object with.lowand.high.The new lines at the end. The p-value, 0.0092, is close to the shuffle's 0.0073:
terminalactual outputWelch t = 2.693, p = 0.0092, df = 57.9 95% CI for the lift: +2.55 to +17.32 requests per zone-hour - Import
-
Chunk 5 — the report a VP can read
Why this comes last: numbers do not persuade anyone until they are in a sentence that states the claim, the evidence, the range and the limits.
Step-by-step: what chunk 5 does, in plain English
- Choose a verdict phrase: "unlikely to be luck alone" if the p-value is below 0.05, otherwise "could easily be luck".
- Print a divider and four sentences: the two averages and the gap; how often shuffled labels matched the gap; the plausible range; the caveats.
- The caveats are fixed text on purpose: sample size, one city, one test.
demand_tests.py — chunk 5runs offlineverdict = "unlikely to be luck alone" if res.pvalue < 0.05 else "could easily be luck" print("-" * 60) print(f"Surge evenings averaged {surge.mean():.1f} requests vs {control.mean():.1f} ({observed:+.1f}).") print(f"If the surge did nothing, shuffled labels gave a gap this big {p_perm:.1%} of the time -> {verdict}.") print(f"Plausible true lift: {ci.low:+.1f} to {ci.high:+.1f} per zone-hour (95% interval).") print("Caveats: 60 zone-evenings, one city, 6 zones; this is one test, not a rollout case.")An
f"…"string with format codes such as:.1%(percent with one decimal) and:+.1f(always show the sign).The new lines at the end are the report:
terminalactual output------------------------------------------------------------ Surge evenings averaged 119.5 requests vs 109.6 (+9.9). If the surge did nothing, shuffled labels gave a gap this big 0.7% of the time -> unlikely to be luck alone. Plausible true lift: +2.6 to +17.3 per zone-hour (95% interval). Caveats: 60 zone-evenings, one city, 6 zones; this is one test, not a rollout case.
The whole program
Lines 1–24 are chunk 1 (load and validate), 25–29 chunk 2 (difference in means), 30–40 chunk 3 (permutation test), 41–47 chunk 4 (SciPy and the interval), and 48–54 chunk 5 (the report). It is saved as code/01e-math-for-ml/demand_tests.py.
# pip install "numpy>=2.5,<2.6" "pandas>=2.2" "scipy>=1.14"
# Did the rainy-evening surge test raise demand? Simulated RideNow data, tested by hand and with scipy.
import numpy as np
import pandas as pd
# ── chunk 1: make the demand data, save it, load it, refuse bad rows ──
def simulate_demand(seed=11, n_per_arm=30):
rng = np.random.default_rng(seed)
control = rng.normal(112, 16, n_per_arm) # normal pricing, rainy evening
treated = rng.normal(119, 16, n_per_arm) # surge test, same kind of evening
return pd.DataFrame({
"arm": ["control"] * n_per_arm + ["surge"] * n_per_arm,
"zone": [f"Z{i % 6 + 1}" for i in range(2 * n_per_arm)],
"requests": np.round(np.concatenate([control, treated])).astype(int),
})
simulate_demand().to_csv("rain_demand.csv", index=False) # swap in your real export here
df = pd.read_csv("rain_demand.csv")
assert set(df["arm"]) == {"control", "surge"}, "unexpected arm label"
assert df["requests"].notna().all() and (df["requests"] >= 0).all(), "bad request counts"
control = df.loc[df["arm"] == "control", "requests"].to_numpy(dtype=float)
surge = df.loc[df["arm"] == "surge", "requests"].to_numpy(dtype=float)
print(f"loaded {len(df)} rows: {len(control)} control, {len(surge)} surge")
# ── chunk 2: the difference in means ──
observed = surge.mean() - control.mean()
print(f"control mean {control.mean():.2f} | surge mean {surge.mean():.2f} | difference {observed:+.2f}")
print(f"spread (sd): control {control.std(ddof=1):.2f} | surge {surge.std(ddof=1):.2f}")
# ── chunk 3: the permutation test, by hand ──
rng = np.random.default_rng(0)
pool = np.concatenate([control, surge])
shuffled_diffs = np.empty(10_000)
for i in range(10_000):
rng.shuffle(pool) # throw the labels away
shuffled_diffs[i] = pool[len(control):].mean() - pool[:len(control)].mean()
p_perm = np.mean(np.abs(shuffled_diffs) >= abs(observed)) # two-sided
print(f"shuffled differences: sd {shuffled_diffs.std():.2f}, range {shuffled_diffs.min():+.1f} to {shuffled_diffs.max():+.1f}")
print(f"permutation p-value (two-sided): {p_perm:.4f}")
# ── chunk 4: the same question with scipy, plus a confidence interval ──
from scipy import stats
res = stats.ttest_ind(surge, control, equal_var=False) # Welch: allows unequal spreads
ci = res.confidence_interval(confidence_level=0.95)
print(f"Welch t = {res.statistic:.3f}, p = {res.pvalue:.4f}, df = {res.df:.1f}")
print(f"95% CI for the lift: {ci.low:+.2f} to {ci.high:+.2f} requests per zone-hour")
# ── chunk 5: the report a VP can read ──
verdict = "unlikely to be luck alone" if res.pvalue < 0.05 else "could easily be luck"
print("-" * 60)
print(f"Surge evenings averaged {surge.mean():.1f} requests vs {control.mean():.1f} ({observed:+.1f}).")
print(f"If the surge did nothing, shuffled labels gave a gap this big {p_perm:.1%} of the time -> {verdict}.")
print(f"Plausible true lift: {ci.low:+.1f} to {ci.high:+.1f} per zone-hour (95% interval).")
print("Caveats: 60 zone-evenings, one city, 6 zones; this is one test, not a rollout case.")
Read the output. Surge evenings averaged 119.53 requests against 109.60, a gap of +9.93. The spreads are similar (13.96 and 14.60), which is why the plain and Welch t-tests would agree. The shuffled gaps have a spread of 3.81 and only 0.73% reach ±9.93, so the permutation p-value is 0.0073. SciPy says t = 2.693 and p = 0.0092, and a 95% interval from +2.55 to +17.32. The report says all this in four sentences and ends with the caveats, which a VP trusts more than a clean "proven".
Mission: extend demand_tests.py into the one-page analysis Marcus asked for. You have about 80% of the code from this module; the 20% you write is the part that makes it a report rather than a script: the slicing, the correction and the plain-English paragraph.
- Replace the simulated data with your own file: a CSV with the same three columns, or a different outcome such as cancel rate. The validation asserts must still pass, and one must be added for a new rule you chose.
- Add a bootstrap interval for the lift (resample each group with replacement 10,000 times and take the 2.5th and 97.5th percentiles) and compare it with the SciPy interval. They should be close; explain any gap.
- Slice the test by zone (six zones in the file). Report each zone's p-value, correct the bar for six looks, and state in one sentence whether any zone passes the corrected bar.
- Run the 2,000-repeat power simulation from
ci_coverage.pyfor your sample size, and state how large a test you would need to detect a +7 lift 80% of the time. - Measurement criterion: your report states the estimate, the interval, the p-value and the number of looks. No sentence says "proved" or "the probability the surge works is…".
- README documents three failure modes you found (for example: unequal zone sizes, rain intensity differing between arms, a zone that appears twice) and what you changed.
Stretch goal: fit the demand-versus-price line with gradient_descent.py on your data, then test whether its slope differs from zero with a permutation test on the slope instead of the mean gap.
- Pipeline
- Load, validate, measure the gap, shuffle-test, library test with interval, report.
- Validation
- Assert the labels and counts before testing. A test on bad rows is confidently wrong.
- Report shape
- Averages and gap; how often luck matches; plausible range; caveats.
- Cross-check
- Shuffle p (0.0073) and Welch p (0.0092) should be close. If not, find out why.
- Reproducibility
- Fixed seeds and a saved CSV mean the same numbers every run.
13 · Interview radarHow This Shows Up in Interviews
Maths questions in AI interviews are rarely "derive this". They test whether you can explain an idea in plain words, spot the trap, and say what you would check. Every answer below is something you can say aloud.
"What is cosine similarity, and when would you use it instead of Euclidean distance?"
The real test Whether you know it compares direction, not size, and why that suits embeddings and text.
Strong answer Cosine similarity is the dot product of two vectors divided by both their lengths, so it measures the angle between them and ignores size. Two zones with demand [8, 2, 9] and [4, 1, 4.5] have a cosine of exactly 1, because one is double the other, while their Euclidean distance is large. For embeddings, size often reflects things such as text length that we do not care about, so cosine, or a dot product on length-normalised vectors, is the standard.
Land it Use cosine when shape matters and size does not; use Euclidean distance when the actual magnitudes carry meaning.
"What is a gradient, why do we step against it, and how would you check that your implementation is correct?"
The real test Whether you have implemented it, and know the numerical gradient check.
Strong answer The gradient is the list of partial derivatives of the loss, one per parameter. It points toward higher loss, so we subtract it, scaled by a learning rate. To check an implementation, I compare it with a tiny-step estimate: nudge a parameter by 1e-6 each way and divide the loss change by the step. In my own code the check caught a gradient that forgot a factor of x: it printed (−173, −173) against a true (−230.975, −173), while the training loop still ran and returned a plausible wrong slope.
Land it Write the gradient by formula, verify it by the tiny-step method on a few points, and keep that check as a unit test.
"Your A/B test shows p = 0.03. Do we ship?"
The real test Whether you look past the p-value to size, interval, power and how many comparisons were made.
Strong answer Not yet. I want four things. The estimated lift and its confidence interval, because p = 0.03 with an interval running from nearly zero to large is weak. How many metrics or segments were looked at, since twenty looks produce about one false win. Whether the test was sized in advance: a small test that reaches significance tends to overstate the effect. And whether the lift is worth the cost. In our rain test the measured lift was +9.9 but the interval was +2.5 to +17.3, so I would plan on the low end.
Land it A p-value tells you whether to be surprised; the interval tells you whether to act.
"You sliced results by 20 segments and one segment is significant at p < 0.05. What do you report?"
The real test Whether you know the multiple-testing trap and the simplest correction.
Strong answer I report that it is probably noise, and say why. With 20 independent looks at a 5% bar, the chance of at least one false win is 1 − 0.9520, about 64%. In my simulation, 20 zones with no real effect gave one zone at p = 0.031 and 66% of repeats had at least one. I would correct the bar, for example Bonferroni at 0.05 ÷ 20 = 0.0025, label the slice exploratory, and confirm it with a new test planned in advance.
Land it Count the looks before you read the results, and treat a lone winner as a hypothesis for the next test.
"What does a 95% confidence interval mean?"
The real test Whether you avoid the common wrong reading.
Strong answer It describes the method, not one interval. If you repeated the experiment many times and built an interval each time, about 95% of those intervals would contain the true value. I checked it by simulation: with a true lift of 7, 1,906 of 2,000 intervals contained it. For one interval, the practical reading is that values inside are consistent with the data and values outside are not.
Land it The 95% belongs to the procedure; do not say "95% chance the truth is in here".
"Your model's training loss shoots up to infinity after a few steps. What do you check?"
The real test A debugging order that starts from the cheap and likely causes.
Strong answer First, the learning rate: a value that is too large overshoots, and on our line fit 0.8 pushed the loss past a million in three steps. I would cut it by ten and rerun. Second, the data scale: columns with very different sizes make the stable learning rate tiny, so I scale them. Third, the gradient itself, with the tiny-step check on a few points. Fourth, bad values such as NaN or infinity in the data.
Land it Learning rate, scale, gradient check, bad data, in that order: cheapest and most likely first.
"When would you not use a hosted embedding API?"
The real test Vendor-agnostic judgment with concrete conditions, not brand loyalty.
Strong answer I would use a local open model when the text is private and must not leave our network, when the volume is high enough that per-call cost adds up, or when I need to run offline. A small model such as all-MiniLM-L6-v2 runs on a laptop CPU and gives 384-number vectors for free. I would choose an API when I need top quality across many languages, long documents, or I cannot host the model. Whichever I pick, I record the model name and version with the vectors, because vectors from different models cannot be compared.
Land it Privacy, volume and quality decide it; and never mix embeddings from two models in one index.
14 · RecapWhat You Can Do Now
- You can compute the length, dot product and cosine of two vectors by hand and in NumPy, and say why cosine ignores size.
- You can read matrix shapes, predict whether
@and broadcasting will work, and explain a matrix as both a batch of dot products and a transform. - You can measure a derivative with a tiny step, write the gradient of a two-parameter loss, and follow the chain rule on a small computation graph.
- You can fit a line with gradient descent in about 70 lines, check the gradient numerically, and recognise a learning rate that is too small or too large from the loss curve.
- You can estimate probabilities, conditional probabilities and expectations by simulation, and describe the normal curve with the 68/95/99.7 rule.
- You can run a permutation test and a Welch t-test, read the p-value and the confidence interval in plain words, and say what neither of them tells you.
- You can spot the multiple-testing trap, correct for it, and explain why a "winning" experiment overstates its effect.
- You can explain embeddings as vectors where cosine means similar meaning, and run a local sentence-embedding model.
From this module: without looking back, sketch the gradient descent loop in four lines of plain English, then say what happens to the loss for a learning rate that is far too big. Then write down, from memory, how many zones out of 20 you expect to show p < 0.05 when the surge does nothing.
From an earlier module: in Module 01b, a fraud alarm with a good model was still mostly false alarms because honest payments were so common. How is that the same kind of trap as the 20-zone slicing here? (Hint: both are about how many chances there are for a false alarm.)
Reveal the answer
The loop: measure the loss, find the gradient, step against it, repeat until the loss is flat. A learning rate that is too large overshoots, so the loss climbs and explodes. Expect about one of 20 zones.
In both traps a small false-alarm rate is applied to a very large number of chances. 2% of 9,920 honest payments gives 198 false alarms, and 5% of 20 zone tests gives about one false win. The fix in both is to count the chances before reading the alarm.
Next up is Module 02, where the gradient loop you built here is applied to a real prediction problem, with scaling, train and test splits, and what happens when the data is messy.