Math for ML
The handful of ideas from linear algebra, calculus and probability that machine learning runs on. You work each one out on tiny numbers first, then let NumPy do it, and finish by computing attention by hand.
- Beginner
- 4 units, 12 lessons, 154 exercises
- Python with NumPy
- Builds on school algebra
Unit 01 · 3 lessons
Vectors and matrices
Treat data as lists of numbers and models as tables of them
- 01Vectors
Lists of numbers you can add, scale and measure
- 02The dot product
Multiply matching entries, add: one number for alignment
- BOSSA layer is a matrix
Shapes, matrix products, and one neural-network layer
Read the unit guide
A vector is a list of numbers. You can read it as a point (a house with 3 rooms, 2 floors, 12 years old is [3, 2, 12]) or as an arrow from zero to that point. Machine learning turns everything into vectors: pixels, words, users.
Vectors add and scale entry by entry: [3, 4] + [1, -2] is [4, 2], and 2 × [3, 4] is [6, 8]. The length of a vector, its norm, is the square root of the sum of its squared entries, so [3, 4] has length 5. The distance between two points is the length of their difference.
The dot product multiplies matching entries and adds the results, giving one number: [3, 4] · [2, 5] is 26. It is large when two arrows point the same way, zero when they are perpendicular, negative when they point apart. Divide it by both lengths and you get cosine similarity, which runs from -1 to 1 and ignores how long the arrows are.
A matrix is a table of numbers with a shape: (rows, columns). A matrix times a vector takes the dot product of each row with the vector. For two matrices the shape rule is (m, n) times (n, p) gives (m, p): the inner sizes must match, and they disappear.
A neural-network layer is exactly this: W @ x + b. Each row of W holds the weights of one output, b adds one bias per output. A layer from 3 inputs to 2 outputs has a (2, 3) weight matrix and 2 biases: 8 numbers to learn.
In NumPy, +, - and * work entry by entry, @ is the dot or matrix product, .shape tells you the shape, and .T flips rows and columns. Most bugs in ML code are shape bugs, so read shapes before values.
Unit 02 · 3 lessons
Change
Measure how a small nudge to an input moves the output
- 01Slopes
A derivative is rise over run on a tiny step
- 02Gradients
One slope per input, and the step that goes downhill
- BOSSBackprop by hand
Multiply local slopes backward through one neuron
Read the unit guide
A derivative is a slope: how much the output of a function changes per unit of change in its input, at one particular spot. You can always estimate it by nudging: (f(x + h) - f(x)) / h for a tiny h. The smaller the nudge, the better the estimate.
For simple functions there are shortcuts. The power rule says the slope of xⁿ is n·xⁿ⁻¹, so x² has slope 2x and x³ has slope 3x². A constant has slope 0, a number in front stays in front, and sums are handled term by term. Where the slope is zero the curve is flat: the bottom of a bowl or the top of a hill.
A function of several inputs has one slope per input, called a partial derivative: nudge one input and hold the others still. Collect them in a vector and you have the gradient. It points in the direction in which the function climbs fastest.
Gradient descent is the whole trick of training: compute the gradient of the loss, take a small step the opposite way, repeat. new = old - learning_rate × gradient. Too small a learning rate crawls. Too large a one overshoots the valley and can blow up.
The chain rule handles functions built from other functions: if x changes u and u changes y, the slopes multiply. A neural network is a long chain, so its gradient is a product of local slopes. Backpropagation is just that product computed from the loss backward, reusing the values stored on the way forward.
Never trust a hand-derived gradient until you have checked it against the nudge estimate. If the two numbers disagree, the algebra is wrong.
Unit 03 · 3 lessons
Uncertainty
Read and build the beliefs a model outputs
- 01Distributions
Probabilities sum to one; averages and spread
- 02Conditional probability
What you believe after seeing the evidence
- BOSSFrom scores to probabilities
Softmax, logs and the cross-entropy loss
Read the unit guide
A probability is a number from 0 (never) to 1 (always). A distribution lists every possible outcome with its probability, and the list must sum to exactly 1. A classifier does not answer "cat": it answers a distribution, such as cat 0.7, dog 0.2, eel 0.1.
The expected value is the long-run average: multiply each value by its probability and add, which is a dot product. The variance is the average squared distance from that mean, and its square root, the standard deviation, tells you the typical spread in the original units. A normal distribution is the bell curve: about 68% of it lies within one standard deviation of the mean, about 95% within two.
P(A | B) is the probability of A given that B happened: look only at the cases where B is true. It is not the same as P(B | A). Events are independent when knowing one tells you nothing about the other; then, and only then, P(A and B) = P(A) × P(B).
Bayes' rule turns a prior belief into a posterior one after seeing evidence: P(A | B) = P(B | A) × P(A) / P(B). The prior matters enormously: a positive result from a good test for a rare disease still usually comes from a healthy person, because healthy people are so much more common.
Softmax turns any list of scores into a distribution: exponentiate each score, then divide by the total. Only the gaps between scores matter. Logarithms turn products of many small probabilities into sums that a computer can hold, which is why models work with log-probabilities.
Cross-entropy is the loss built from all this: minus the log of the probability the model gave to the right answer. It is 0 for a confident correct answer and grows without limit for a confident wrong one. Minimising it is the same as making the training data as likely as possible.
Unit 04 · 3 lessons
Putting it to work
Assemble vectors, slopes and probabilities into learning
- 01Loss and descent
Measure how wrong, then step downhill
- 02Linear regression
Fit a line by gradient descent and read its loss curve
- BOSSThe math inside attention
Dot products, softmax and a weighted average, for three tokens
Read the unit guide
Learning needs a number that says how wrong the model is: the loss. For predicting quantities the standard choice is mean squared error, the average of (prediction - target)². Squaring keeps errors from cancelling and makes one big miss count for more than several small ones.
The loss depends on the weights, so you can picture it as a landscape over them. Training walks downhill on that landscape: compute the gradient of the loss, step against it, repeat. The walk stops wherever the gradient is zero, which may be a local minimum rather than the lowest valley.
For the model pred = w·x + b the chain rule gives the two slopes directly: ∂loss/∂w = mean(2 · error · x) and ∂loss/∂b = mean(2 · error). Notice the x: a feature with huge values produces huge slopes. That is why features are standardised first (subtract the mean, divide by the standard deviation), so one learning rate suits every weight.
A loss curve is the first thing to read. Falling then flattening: converged. Climbing or bouncing: the learning rate is too high. Training loss falling while validation loss rises: the model is memorising its training data, which is called overfitting.
Attention, the heart of language models, is built from the same parts. Dot products between a query and each key measure relevance. Dividing by √d keeps the scores in a range where softmax stays soft. Softmax turns scores into weights that sum to 1, and the output is the weighted average of the value vectors.
Nothing in this unit is new math. It is unit one's dot products, unit two's gradients and unit three's softmax, wired together.
Learn Math for ML on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.