Part 02 / Stage 1
The maths you need
Goal: Learn only the maths that machine learning actually uses — vectors, gradients, probability, softmax — and check every piece with code. Time: ~3 hours · Needs: Part 1
What you will learn
- Vectors and matrices: shapes, matrix multiplication, transpose
- Dot product, norms and cosine similarity
- Derivatives and gradients
- The chain rule, and why it powers backpropagation
- Probability basics: mean, variance, Bayes' rule
- Softmax and log probabilities, numerically stable
- Checking analytic maths with numerical estimates
Topics in this part
Practice
Exercise 1: Shape prediction
For A of shape (4, 2) and B of shape (2, 5): write down the shapes of A @ B, A.T, B.T @ A.T before running, then check all three in code.
Show the solution to Exercise 1
# Exercise 1: Shape prediction
import numpy as np
A = np.ones((4, 2))
B = np.ones((2, 5))
print("A @ B:", (A @ B).shape) # predicted (4, 5)
print("A.T:", A.T.shape) # predicted (2, 4)
print("B.T @ A.T:", (B.T @ A.T).shape) # predicted (5, 4) — it is (A @ B).T
Exercise 2: Cosine ranking
Given the query vector q = [1, 1, 0] and candidates [[1, 1, 0.1], [0, 0, 1], [-1, -1, 0], [2, 2, 0]], rank the candidates by cosine similarity to q and print them best-first with their scores.
Show the solution to Exercise 2
# Exercise 2: Cosine ranking
import numpy as np
q = np.array([1.0, 1.0, 0.0])
candidates = np.array([[1.0, 1.0, 0.1], [0.0, 0.0, 1.0], [-1.0, -1.0, 0.0], [2.0, 2.0, 0.0]])
def cosine(u, v):
return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))
scores = [cosine(q, c) for c in candidates]
for i in np.argsort(scores)[::-1]:
print(f"{scores[i]:+.3f} {candidates[i]}")
Exercise 3: Gradient check
Derive df/dw for f(w) = w**3 - 4*w by hand, then verify your formula numerically at w = 2.0 and w = -1.0.
Show the solution to Exercise 3
# Exercise 3: Gradient check
# f(w) = w^3 - 4w -> df/dw = 3w^2 - 4
f = lambda w: w ** 3 - 4 * w
grad = lambda w: 3 * w ** 2 - 4
h = 1e-6
for w in [2.0, -1.0]:
numerical = (f(w + h) - f(w - h)) / (2 * h)
print(f"w={w}: analytic={grad(w)} numerical={round(numerical, 4)}")
Exercise 4: Stable softmax
Write softmax(z) with the max-subtraction trick. Check that (a) the output sums to 1 for z = [2.0, 1.0, 0.1], and (b) it returns finite values for z = [1000.0, 999.0].
Show the solution to Exercise 4
# Exercise 4: Stable softmax
import numpy as np
def softmax(z):
e = np.exp(z - np.max(z))
return e / e.sum()
small = softmax(np.array([2.0, 1.0, 0.1]))
print(small.round(4), "sum =", small.sum())
big = softmax(np.array([1000.0, 999.0]))
print(big.round(4), "all finite:", np.isfinite(big).all())
Mini-project: Maths in code
Implement three functions and test each against NumPy or a hand-worked value:
cosine(u, v)— compare with 1.0 for parallel vectors and 0.0 for orthogonal onessoftmax(z)— stable; outputs sum to 1numerical_grad(f, w)— central difference; test it on f(w) = (3w − 12)²
A complete version is in solutions/mini_maths_in_code.py.
Stretch: extend the gradient checker to vector inputs and use it on softmax cross-entropy.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Confusing * with @ |
* is elementwise; @ is matrix/dot product |
Use @ for projections, predictions, attention |
| Comparing embeddings by distance only | Length differences swamp direction | Cosine similarity, or normalise first |
| Naive softmax | exp(1000) overflows to NaN |
Subtract z.max() first |
| Multiplying many probabilities | Underflows to 0 | Sum log probabilities |
| Trusting a derived gradient | One sign error ruins training silently | Check against a numerical gradient |
Quick recap
- Rows are examples, columns are features; predictions are matrix products.
- The dot product and the norms together give cosine similarity — the measure behind embeddings.
- The gradient points uphill; training steps against it.
- Backpropagation is the chain rule, applied layer by layer.
- Bayes' rule explains why, with rare events, most alarms are false.
- Softmax — subtract the max first for stability — turns logits into probabilities, and logs turn products into sums.
- Always check analytic gradients numerically.
Checklist
- I can predict the shape of
A @ Bbefore running it. - I can compute cosine similarity and explain what 1, 0, −1 mean.
- I can derive df/dw for (w·x − y)² and verify it numerically.
- I can explain the disease-test result in one sentence.
- I can write a stable softmax from memory.
- I know why ML sums log probabilities.
Read more: NumPy linear algebra routines