Math for ML, by Hand: Linear Algebra, Calculus and Probability for Machine Learning, Worked on One Tiny Model
One model small enough to check with a pencil, opened box by box: vectors, matrices, gradients, curvature, probability and cross-entropy.
Part 1: Why Is a Data Point an Arrow? · Part 2: What Does a Weight Matrix Actually Do to Your Data? · Part 3: Why Does Gradient Descent Bounce? · Part 4: Why Is Your Loss Function an Expected Value?
Part 1: Why Is a Data Point an Arrow?
vectors, length and angle, worked on one tiny model you can check with a pencil.

A neural network is trained with calculus but described with linear algebra. Most of the confusion people carry about the math of machine learning lives in the seam between those two, and most explanations make it worse by switching examples every few paragraphs.
This series does the opposite. It follows one model so small that every number fits on a napkin, and it asks each branch of math one question about that model. By the end of part 4, every box in the model below has been opened and every number in it has been computed by hand.
The tiny model

Here is the model. Two users visit a site. The first viewed 3 pages and stayed 4 minutes, then clicked. The second viewed 1 page, stayed 2 minutes and left. The model reads each user as two numbers, passes them through a matrix A, a weight vector w and a bias b, and returns a probability of clicking.
Both users come out at p = 0.5. The model cannot tell them apart. Fixing that is what training is for, and it is the thread that runs through all four parts. Part 1 is about the first box: what it means for a user to be the vector x = (3, 4).
Every number below can be changed and recomputed on the companion page: Math for ML, by Hand, part 1.
Vectors: a data point is an arrow

A data point and an arrow from the origin are the same object, written two ways.

Draw two axes: pages viewed across, minutes on site up. Walk 3 along and 4 up and put a dot there. That dot is the first user.
Now draw an arrow from the origin to the dot. The arrow is the vector x. It carries exactly the information the two numbers carry, nothing more. What the picture adds is a set of moves you can see: arrows can be laid end to end, stretched, compared by length and compared by direction.
The second user, x′ = (1, 2), is a shorter arrow pointing in nearly the same direction. Keep that in mind. Most of this part is about measuring how far apart, and how aligned, these two arrows are.
![Worked by hand: x = [3, 4] ← pages viewed, minutes on site ; x′ = [1, 2] ; shape: (2,) one row of the data table = one arrow in R²](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-01-vectors.gif)
Why ML cares: Every input a model sees is a vector: a row of features, a pixel grid flattened into one long list, a 768-number text embedding. The picture of an arrow still holds in 768 dimensions; we just cannot draw it.
What it cannot do: The picture says where x is. It does not yet say how to combine arrows.
Try it: Vectors on the companion page
Adding and scaling

Add arrows tip to tail; scale them by stretching.

To add x′ to x, slide x′ so its tail sits on the tip of x. The new tip lands at (4, 6). In numbers this is just position-by-position addition: 3 + 1 and 4 + 2.
Scaling is simpler. 2x = (6, 8) doubles both entries, and the arrow gets twice as long without turning. Multiply by −1 and the arrow flips to point the other way.
A vector space is any collection of objects where these two moves behave the way they do on this grid. The formal definition is a list of rules (addition is commutative, there is a zero vector, scaling distributes over addition, and so on). For machine learning, the practical reading is: anything you can add and scale like arrows can be fed to the rest of this series.
![Worked by hand: x + x′ = [3+1, 4+2] = [4, 6] ; 2·x = [2·3, 2·4] = [6, 8] ; −1·x = [−3, −4] same length, opposite direction](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-02-add-scale.gif)
Why ML cares: A weighted sum of vectors, a·x + b·x′, is the most common operation in a network. Every neuron computes one.
What it cannot do: Nothing here says how long an arrow is. For that we need a norm.
Try it: Adding and scaling on the companion page
Length in two dimensions

The length of an arrow is the Pythagorean theorem.

The tempting answer to "how long is x?" is 3 + 4 = 7. That number is real, but it counts grid steps, not the length of the arrow.
The arrow is the long side of a right triangle with legs 3 and 4. Put a square on each leg: their areas are 9 and 16, and they add to 25. The square on the long side has the same area, so the arrow has length √25 = 5.
The notation ‖x‖₂ with its square root looks heavier than the idea. It is Pythagoras with a subscript.
![Worked by hand: x = [3, 4] ; squares = [9, 16] ; sum = 25 ; ‖x‖₂ = √25 = 5](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-03-norm-2d.gif)
Why ML cares: Lengths turn up as weight decay (the L2 penalty adds ‖w‖² to the loss), as gradient clipping (rescale when ‖∇L‖ is too large) and as normalisation layers.
What it cannot do: Two coordinates only. Real inputs have more.
Try it: Length in two dimensions on the companion page
Length in three dimensions (and more)

Each extra coordinate adds one more right triangle.

Give the first user a third feature, scroll depth 12, so x = (3, 4, 12). Along the floor the arrow covers the 2-D distance we already know, 5. Then it climbs 12 straight up.
Those two pieces form a new right triangle with legs 5 and 12, and Pythagoras gives √(25 + 144) = √169 = 13. Expanding the 5 back into 3 and 4 gives the general rule: square every coordinate, add, take the root.
In n dimensions the triangle step repeats n − 1 times, and the formula keeps the same shape: ‖x‖₂ = √(x₁² + … + xₙ²).
![Worked by hand: x = [3, 4, 12] ; squares = [9, 16, 144] ; sum = 169 ; ‖x‖₂ = √169 = 13 (= √(5² + 12²), Pythagoras twice)](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-04-norm-3d.gif)
Why ML cares: A text embedding with 768 coordinates has a length computed exactly this way. Cosine similarity, used to compare embeddings, divides by two of these lengths.
What it cannot do: One way of measuring length is not the only way, and it is not always the right one.
Try it: Length in three dimensions (and more) on the companion page
Distance: L2, L1 and the rest of the family

A distance is the norm of the difference, and there is more than one legitimate norm.

The gap between the two users is x − x′ = (2, 2). Measured in a straight line (p = 2) that is 2.83. Measured along the grid (p = 1, the Manhattan or taxicab norm) it is 2 + 2 = 4. With p = ∞ you keep only the largest coordinate, 2.
It is tempting to call the longer staircase "wrong". It is not. A taxi on a street grid really does drive 4 blocks. Each norm answers a different question, and each has its own shape of "all points at distance 1": a diamond for L1, a circle for L2, a square for L∞.
Any function that behaves like length earns the name norm: it is zero only for the zero vector, it scales with the vector, and it obeys the triangle inequality, ‖a + b‖ ≤ ‖a‖ + ‖b‖. That last rule is why p must be at least 1. At p = 0.5, ‖e₁ + e₂‖ = 4 while ‖e₁‖ + ‖e₂‖ = 2. The shortcut is longer than the detour, so the formula has stopped measuring a distance.
![Worked by hand: x − x′ = [2, 2] ; L2: √(2² + 2²) = 2.83 ; L1: |2| + |2| = 4 ; L∞: max(2, 2) = 2 ; p = 0.5: ‖(1,1)‖ = (1 + 1)² = 4 > ‖(1,0)‖ + ‖(0,1)‖ = 2 ✗ not a norm](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-05-norms.gif)
Why ML cares: L1 penalties push weights to exactly zero (sparse models); L2 penalties shrink them smoothly. Nearest-neighbour search and k-means change their answers when you change the norm.
What it cannot do: A norm measures size, but not direction. Two arrows can have equal lengths and point in opposite directions.
Try it: Distance on the companion page
Inner products: one number for agreement

Multiply matching coordinates and add: the result says how much two arrows agree.

Multiply the two users position by position and add: 3·1 + 4·2 = 11. The result is large and positive because the arrows point almost the same way. Divide by the two lengths and you get cos θ = 0.984, an angle of 10.3°.
Turn x by a right angle to (−4, 3) and the same recipe gives 3·(−4) + 4·3 = 0. Zero is the signature of a right angle; such vectors are called orthogonal. Point against x, for instance with (−1, 0), and the result goes negative: −3.
So unlike a norm, an inner product can be negative. It maps two vectors to any real number. What it cannot be is negative for a vector paired with itself, because ⟨x, x⟩ = ‖x‖² = 25. That link runs both ways: every inner product defines a norm by ‖x‖ = √⟨x, x⟩.
![Worked by hand: x = [3, 4] ; x′ = [1, 2] ; x ⊙ x′ = [3, 8] → sum 11 ; cos θ = 11 / (5 · √5) = 0.984 ; x · (−4, 3) = −12 + 12 = 0 orthogonal](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-05b-inner-product.gif)
Why ML cares: The score in our model, z = w·h + b, is an inner product: it measures how much the hidden vector h agrees with the learned direction w. Attention scores in a transformer are inner products of query and key vectors.
What it cannot do: Agreement between two arrows is still relative to the axes we drew. Change the axes and the coordinates change, which needs the idea of a basis.
Try it: Inner products on the companion page
Bases: coordinates are measurements

A basis is a set of measuring sticks; with an orthonormal basis, each coordinate is one inner product.

The numbers 3 and 4 are weights on two fixed arrows, e₁ = (1, 0) and e₂ = (0, 1): x = 3e₁ + 4e₂. Any set of arrows that can build every vector in this way, with none of them redundant, is a basis.
Tilt the measuring sticks by 45°: q₁ = (1, 1)/√2 and q₂ = (1, −1)/√2. They still have length 1 and still meet at a right angle, so the basis is orthonormal. In this basis the coordinates of x are found by one inner product each: ⟨x, q₁⟩ = 7/√2 = 4.95 and ⟨x, q₂⟩ = −1/√2 = −0.71. Rebuild 4.95·q₁ + (−0.71)·q₂ and you land exactly back on (3, 4).
That shortcut only works because the sticks are orthonormal. For a skewed basis you would have to solve a small system of equations instead. The tilted sticks are not arbitrary, either: (1, 1) and (1, −1) are the directions that our matrix A only stretches, which is where part 2 picks up.
![Worked by hand: q₁ = [1, 1]/√2 q₂ = [1, −1]/√2 ; ⟨x, q₁⟩ = (3 + 4)/√2 = 4.95 ; ⟨x, q₂⟩ = (3 − 4)/√2 = −0.71 ; 4.95·q₁ + (−0.71)·q₂ = [3, 4] ✓ ; Gram grid ⟨qᵢ, qⱼ⟩ = [[1, 0], [0, 1]]](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p1-06-basis.gif)
Why ML cares: PCA chooses an orthonormal basis aligned with the directions where the data varies most, then keeps only the first few coordinates. Every coordinate it keeps is one inner product.
What it cannot do: Everything so far is static: arrows sitting still. A model has to move them, and moving every arrow at once is what a matrix does.
Try it: Bases on the companion page
Where this leaves us
The habit to carry forward is the one the inner product teaches: a single number that says how much two vectors agree. The score z = w·h + b in our model is exactly that, an inner product plus a constant.
Part 2 asks what the matrix A does to x before that score is taken. It moves the whole grid at once, and the way it moves the grid explains matrix products, determinants, eigenvectors and the SVD.
Part 2: What Does a Weight Matrix Actually Do to Your Data?
linear maps, matrix products, determinants, eigenvectors and the SVD, on one 2×2 matrix.

A dense layer computes Ax + b, and most people learn to read A as a table of weights. That reading is correct and almost useless. It does not say what the layer does to the data.
A better reading is geometric. A matrix moves every point of the space at once, and it moves them in a very constrained way: straight lines stay straight, parallel lines stay parallel, and the origin stays put. Everything in this part follows from that.
The tiny model
We keep the cast from part 1: x = (3, 4) for the user who clicked, x′ = (1, 2) for the user who did not, and the model's first box, h = Ax with A = [[2, 1], [1, 2]]. Our two users land at h = (10, 11) and h′ = (4, 5).
Every number below can be changed and recomputed on the companion page: Math for ML, by Hand, part 2.
Linear maps move the whole grid

A linear map keeps grid lines straight, parallel and evenly spaced, and keeps the origin fixed.

Rotate the plane by 90° around the origin. Every grid line turns together, and x = (3, 4) lands on (−4, 3). Its length is still 5, and the new arrow is at a right angle to the old one (the inner product from part 1 is 0).
The rule in the equation says that scaling and adding can happen before or after the map with the same result. Check it on A: A(x + x′) = (14, 16), and Ax + Ax′ = (10, 11) + (4, 5) = (14, 16).
A curved warp fails this test. If grid lines bend, then mapping the sum is no longer the sum of the maps. That is why the layers of a network need a separate nonlinearity, such as σ or ReLU, to bend anything: the matrix itself cannot.
The payoff of linearity is that two arrows decide everything. Once you know where e₁ and e₂ go, every other vector follows, because every vector is a weighted sum of e₁ and e₂. Write those two images as columns and you have the matrix.
![Worked by hand: R = [[0, −1], [1, 0]] columns = where e₁ and e₂ land ; R x = 3·(0, 1) + 4·(−1, 0) = (−4, 3) ; A x = 3·(2, 1) + 4·(1, 2) = (6 + 4, 3 + 8) = (10, 11)](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p2-07-linear-maps.gif)
Why ML cares: h = Ax in our model is a linear map. So is every dense layer, every convolution and the query, key and value projections in attention.
What it cannot do: One map at a time. Networks stack layers, so we need to know what happens when maps are chained.
Try it: Linear maps move the whole grid on the companion page
The matrix product is one map after another

Multiplying matrices composes the maps, so the formula is whatever makes (AB)x = A(Bx) true.

Rotate first, then apply A. Each entry of the combined matrix AR is one row of A against one column of R. Entry (2, 1) uses row 2 of A, (1, 2), and column 1 of R, (0, 1): 1·0 + 2·1 = 2. All four entries give AR = [[1, −2], [2, −1]].
The formula looks arbitrary until you test what it buys. Route A combines the maps first: (AR)x = (−5, 2). Route B applies them one at a time: Rx = (−4, 3), then A(Rx) = (−5, 2). Same answer, by construction. The row-times-column rule is the only rule that makes this hold for every x.
Order matters. RA = [[−1, −2], [2, 1]] applies A first and then rotates, and it is a different map. Matrix multiplication is associative, (AB)C = A(BC), but not commutative.
![Worked by hand: row 2 of A · column 1 of R = 1·0 + 2·1 = 2 ; AR = [[2·0 + 1·1, 2·(−1) + 1·0], ; [1·0 + 2·1, 1·(−1) + 2·0]] = [[1, −2], [2, −1]] ; (AR)x = (1·3 − 2·4, 2·3 − 1·4) = (−5, 2) ; A(Rx) = A(−4, 3) = (−8 + 3, −4 + 6) = (−5, 2) ✓](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p2-08-matrix-product.gif)
Why ML cares: Stacking two linear layers without a nonlinearity between them gives one linear layer, W₂W₁. Associativity also decides cost: in attention, computing (QKᵀ)V and Q(KᵀV) gives the same result at very different prices.
What it cannot do: The product says how to compute the map, not how much it stretches space. That is the determinant's job.
Try it: The matrix product is one map after another on the companion page
The determinant is the area factor

The determinant says how much a map scales area, and its sign says whether it flips orientation.

Send the unit square through A. It becomes a parallelogram with corners at (0, 0), (2, 1), (3, 3) and (1, 2), and its area is 3. Every shape in the plane has its area multiplied by the same factor, so det A = 3.
A tempting misreading is that det = 0 means nothing happened. It means the opposite. The matrix [[1, 2], [2, 4]] sends both columns onto the same line, so the square is flattened to a segment with area 0. Two different inputs now share one output, and the map cannot be undone. Zero determinant means not invertible.
Negative determinants mean a mirror. The flip [[0, 1], [1, 0]] swaps the axes, keeps every area, and has det = −1: a letter F drawn in the square comes out reading backwards.
The general formula for an n×n determinant is a sum over permutations, and it is rarely computed that way in practice. The geometric meaning is the one to keep. 3Blue1Brown's video on determinants animates it well.
![Worked by hand: det A = 2·2 − 1·1 = 3 ; shoelace area of A(unit square) = 3 ✓ ; det [[1, 2], [2, 4]] = 4 − 4 = 0 flattened ; det [[0, 1], [1, 0]] = 0 − 1 = −1 mirrored](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p2-09-determinant.gif)
Why ML cares: Normalizing flows track how a map stretches probability density, which is a log-determinant. A near-zero determinant warns that a layer is collapsing directions and losing information.
What it cannot do: One number for the whole map. It does not say which directions get stretched and which get squeezed.
Try it: The determinant is the area factor on the companion page
Eigenvectors: the directions a matrix only stretches

An eigenvector keeps its direction under the map; the eigenvalue is how much it stretches.

Feed A a unit arrow and draw where it lands. Most arrows get turned as well as stretched. Sweep the input around the circle and two directions stand out: along (1, 1) the output stays on the same line and is 3 times longer, and along (1, −1) it does not move at all. A has eigenvalues 3 and 1.
Our user x = (3, 4) is not one of them. Ax = (10, 11), and 10/3 is not 11/4, so the output points somewhere new.
These are the tilted measuring sticks from part 1. In that basis, A is easy: x has coordinates 4.95 and −0.71, and A multiplies them by 3 and 1. Rebuild with the scaled coordinates and you get (10, 11) again. Diagonal matrices are the easiest maps there are, and eigenvectors are the basis in which a matrix becomes diagonal.
To find eigenvalues by hand, ask when A − λI flattens space, that is, when det(A − λI) = 0. Here that is (2 − λ)² − 1 = 0, so λ = 3 or λ = 1.

Why ML cares: PCA's directions are the eigenvectors of the data's covariance matrix. The eigenvalues of the loss curvature decide how large a learning rate can be, which part 3 shows on this exact model.
What it cannot do: Not every matrix has a full set of real eigenvectors. A rotation turns every arrow, so it has none. We need a decomposition that works for every matrix.
Try it: Eigenvectors on the companion page
The SVD: rotate, stretch, rotate

Every matrix is a rotation, then a stretch along the axes, then another rotation.

Take a matrix with no nice eigenvectors, B = [[3, 0], [4, 5]], and watch what it does to the unit circle. The SVD splits the map into three steps. Vᵀ rotates (the circle looks unchanged, but the two marked axes turn). Σ stretches along the axes by 6.71 and 2.24, so the circle becomes an ellipse. U rotates the ellipse into its final place. The result matches B applied to the circle exactly.
The stretch factors are the singular values. They are the lengths of the ellipse's semi-axes, and their product, 6.71 × 2.24 = 15, is the area factor |det B|. A linear map can never turn a circle into a square, because it has to send the circle to an ellipse.
For a symmetric matrix like our A, the two rotations line up with the eigenvectors, and the singular values are the eigenvalues 3 and 1. In general they differ, and the SVD exists even when eigenvectors do not.
![Worked by hand: BᵀB = [[25, 20], [20, 25]] eigenvalues 45, 5 ; singular values = √45 = 6.71, √5 = 2.24 ; U Σ Vᵀ = [[3, 0], [4, 5]] = B ✓ ; 6.71 × 2.24 = 15 = |det B|](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p2-11-svd.gif)
Why ML cares: Keep only the largest singular values and you get the best low-rank approximation of a matrix. That is PCA, latent semantic analysis, matrix-factorisation recommenders and LoRA fine-tuning.
What it cannot do: All of part 2 treats A as fixed. Training changes it, and to change it in the right direction we need derivatives.
Try it: The SVD on the companion page
Where this leaves us
The single idea to keep: a matrix is a map, and the matrix product is one map after another. Determinants, eigenvalues and singular values are three ways of summarising what the map does to areas and directions.
Part 3 lets the map change. Training adjusts A, w and b to lower the loss, and that needs derivatives: how the output moves when one weight moves.
Part 3: Why Does Gradient Descent Bounce?
derivatives, integrals, gradients, the chain rule and the Hessian, on a model you can train with a pencil.

Set the learning rate to 0.05 on our tiny model and the loss goes 1.386, 1.622, 1.436, 1.759. It rises, falls and rises again, and after 11 steps it is still above where it started. Nothing is wrong with the gradient.
By the end of this part the reason will be a single number, 0.031, read off the second derivatives of the loss. Getting there takes the whole of calculus for machine learning: slopes, areas, surfaces, gradients, the chain rule and curvature.
The tiny model
The cast is unchanged: A = [[2, 1], [1, 2]], w = (1, −1), b = 1. Both users get z = 0 and p = 0.5, and each has loss −ln 0.5 = 0.693, so the total over the two users is 1.386. Training means changing A, w and b to push that number down.
Every number below can be changed and recomputed on the companion page: Math for ML, by Hand, part 3.
The derivative is the slope of a tangent

The derivative is the slope of the secant line in the limit as its two points merge.

Turn one knob, the bias b, and watch the clicking user's loss. At b = 1 it is 0.693. Take a second point h further along and draw the secant line through both. With h = 1 its slope is −0.380; with h = 0.1 it is −0.488; with h = 0.01 it is −0.499; with h = 0.001 it is −0.4999.
The slopes settle on −0.5. That limit is the derivative, the slope of the tangent at b = 1. For sigmoid followed by log-loss it has a clean closed form: ∂L/∂b = p − y = 0.5 − 1 = −0.5. Negative means increasing b lowers the loss.
At a minimum or maximum the derivative is 0, but a zero derivative alone does not prove either: f(x) = x³ has f′(0) = 0 and keeps rising through it. The second derivative decides. Here it is p(1 − p) = 0.25 > 0, so the curve bends upward.

Why ML cares: Every weight update in training uses a derivative. Finite differences, the secant slopes above, are how practitioners check a hand-written gradient.
What it cannot do: One knob at a time, on a curve. Before moving to many knobs, the other half of calculus: area.
Try it: The derivative is the slope of a tangent on the companion page
The integral is signed area

An integral adds up a function over an interval, counting area below the axis as negative.

Take f(x) = x² − 1 on [0, 2]. It dips below the axis until x = 1 and rises above it after. The tempting answer adds all the shaded area as positive. An integral keeps the sign: the part below contributes −2/3, the part above 4/3, and the total is 2/3.
Two routes give that number. The fast one uses the fact that integration undoes differentiation: x³/3 − x has derivative x² − 1, so the integral is its change from 0 to 2. The slow one cuts the interval into rectangles and adds their signed areas: 4, 8, 16 and 64 rectangles give sums that close in on 2/3.

Why ML cares: The expected loss over a continuous distribution of inputs is an integral, and so are entropy and KL divergence for continuous variables. Training replaces each of these integrals with an average over a sample, which part 4 justifies.
What it cannot do: Still one variable. Our loss depends on many weights at once.
Try it: The integral is signed area on the companion page
The loss as a surface

With two weights the loss is a height over a plane, a surface you can draw.

Fix b = 1 and let the two entries of w vary. Every pair (w₁, w₂) gives one total loss, so the loss is a surface over the plane of weights. Our starting point w = (1, −1) sits at height 1.386.
Seen from above, the surface becomes a contour map: each line joins weights with equal loss. These contours are long, thin and tilted. That shape is not decoration. It is the reason gradient descent struggles on this model, and section 16 measures it.

Why ML cares: A real network has millions of weights, so its loss surface cannot be drawn. The two-weight picture is still the right mental model, and the tools below work in any number of dimensions.
What it cannot do: A picture shows the shape, but training needs slopes in numbers.
Try it: The loss as a surface on the companion page
Partial derivatives: freeze all but one

A partial derivative is an ordinary derivative along one axis, with every other variable held still.

Freeze w₂ at −1 and vary only w₁. The surface becomes a curve, and its slope at w₁ = 1 is an ordinary derivative: ∂L/∂w₁. Do the same along w₂. For the clicking user the two slopes are −5 and −5.5.
Stack them into a vector and you have the gradient, ∇L = (−5, −5.5). The closed form explains the numbers: z = w·h + b depends on w₁ through h₁ = 10 and on w₂ through h₂ = 11, and each is scaled by the same p − y = −0.5.
The two tangent lines span a tangent plane, the flat surface that best matches the loss near w. The gradient describes that plane completely.
![Worked by hand: ∂L/∂w₁ = (p − y)·h₁ = −0.5 · 10 = −5 ; ∂L/∂w₂ = (p − y)·h₂ = −0.5 · 11 = −5.5 ; ∇L = [−5, −5.5] ; finite differences (step 1e−6): [−5.000000, −5.500000] ✓](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p3-15-partials.gif)
Why ML cares: A framework's autograd computes this vector for every weight in the model on every step. The next section is what it does with it.
What it cannot do: The gradient is a direction and a steepness. It does not say how far to walk.
Try it: Partial derivatives on the companion page
Gradient descent, and why it bounces

Step against the gradient, with a step size set by the steepest curvature.

The gradient points the way the loss rises fastest. A step of 0.01 along it raises the clicking user's loss from 0.693 to 0.770. The same step against it lowers the loss to 0.622, lower than a step of the same length along the w₁ axis (0.644) or the w₂ axis (0.640). So we subtract the gradient, scaled by a learning rate η.
With both users and η = 0.05, the loss goes 1.386, 1.622, 1.436, 1.759: it bounces, and after 11 steps it is still above its start. The path in weight space zig-zags across the narrow valley from section 14, overshooting the floor on every step.
The second derivatives say why. Their matrix, the Hessian, is H = [[29, 32.5], [32.5, 36.5]] for our two users, with eigenvalues 65.47 and 0.034. Along the steep direction the loss behaves like a parabola with curvature 65.47, and any step size above 2/65.47 = 0.031 overshoots it and lands higher on the far wall. 0.05 is above that limit.
At η = 0.02, below the limit, every step goes down: 1.386, 1.249, 1.239, reaching 1.204 after 12 steps. The descent is also slow, because the valley is about 1,900 times steeper across than along. After 12 steps the model still gives the user who did not click p = 0.596, and it takes 104 steps before both users are on the right side of 0.5. Momentum, Adam and feature scaling all exist to deal with this ratio.
![Worked by hand: total ∇L at w = (1, −1): (−5, −5.5) + 0.5·(4, 5) = (−3, −3) ; H = [[29, 32.5], [32.5, 36.5]] eigenvalues 0.034, 65.47 ; η_max = 2 / 65.47 = 0.031 ; η = 0.05: 1.386 → 1.622 → 1.436 → 1.759 … bounces ; η = 0.02: 1.386 → 1.249 → 1.239 → … → 1.204 (12 steps, every one lower)](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p3-16-gradient-descent.gif)
Why ML cares: Learning-rate warm-up, gradient clipping and adaptive optimizers are all responses to the same fact: the safe step depends on curvature, and curvature differs wildly between directions.
What it cannot do: A gradient only exists once we can differentiate through the whole model. Our model is four boxes in a row, which needs the chain rule.
Try it: Gradient descent, and why it bounces on the companion page
The chain rule, box by box (backpropagation)

Backpropagation multiplies the local derivative of each box, from the loss backwards, reusing each result.

The model is four boxes: h = Ax, z = w·h + b, p = σ(z), and the log-loss. To train A we need four numbers, one per entry. The chain rule says to multiply local derivatives, starting at the loss and walking back.
The last two boxes collapse into one clean number: for sigmoid plus log-loss, ∂L/∂z = p − y = −0.5. The box before is z = w·h + b, whose derivative with respect to h is w, so ∂L/∂h = −0.5·w = (−0.5, 0.5).
The first box is h = Ax. For a vector-to-vector map the derivative is a matrix, the Jacobian, and for h = Ax with respect to x it is A itself. With respect to A, the gradient is an outer product: the column ∂L/∂h times the row xᵀ, giving [[−1.5, −2], [1.5, 2]].
Check it the slow way: nudge each of A's four entries by 10⁻⁶ and rerun the model. The four finite-difference slopes match to six decimals. Backpropagation is the bookkeeping that saves us from running the model once per weight.
![Worked by hand: forward: h = [10, 11], z = 0, p = 0.5, L = 0.693 ; backward: ∂L/∂z = −0.5 ; ∂L/∂h = −0.5 · [1, −1] = [−0.5, 0.5] ; ∂L/∂A = [−0.5, 0.5]ᵀ [3, 4] = [[−1.5, −2], [1.5, 2]] ; ∂L/∂x = Aᵀ [−0.5, 0.5] = [−0.5, 0.5] ; check: finite differences on A = [[−1.5, −2], [1.5, 2]] ✓](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p3-16b-backprop.gif)
Why ML cares: PyTorch and JAX build this backward pass automatically from the forward code. Knowing its shape explains vanishing gradients (many small factors multiplied together) and why activations are stored during the forward pass.
What it cannot do: Gradients say which way is down. They do not say whether a flat spot is a minimum, which is the Hessian's job.
Try it: The chain rule, box by box (backpropagation) on the companion page
The Hessian: reading the shape of a flat spot

The signs of the Hessian's eigenvalues say whether a flat spot is a minimum, a maximum or a saddle.

A bowl, a cap and a saddle all have zero gradient at the centre. The Hessian, the matrix of second derivatives, tells them apart. A common shortcut says: positive determinant means minimum. The cap breaks it. Its Hessian is [[−2, 0], [0, −2]], with determinant 4, the same as the bowl's.
The reliable test reads the eigenvalues. All positive is a minimum, all negative a maximum, mixed signs a saddle. In two dimensions the determinant is the product of the two eigenvalues, so it can only tell you whether their signs agree, not which sign they share.
Our own model shows a second failure. With only the clicking user, H = [[25, 27.5], [27.5, 30.25]] and det H = 0, so the determinant test says nothing. The eigenvalues, 0 and 55.25, explain it: the loss is completely flat in one direction, because one data point cannot pin down two weights. Adding the second user gives det H = 2.25, eigenvalues 0.034 and 65.47: a minimum, but in a valley that is almost flat along its floor.
![Worked by hand: one user: H = 0.25·[[100, 110], [110, 121]] = [[25, 27.5], [27.5, 30.25]] ; det = 756.25 − 756.25 = 0 eigenvalues 0, 55.25 ; two users: H = [[29, 32.5], [32.5, 36.5]] ; det = 1058.5 − 1056.25 = 2.25 eigenvalues 0.034, 65.47](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p3-17-hessian.gif)
Why ML cares: Large networks have far more saddles than poor local minima, and flat directions are everywhere. Second-order optimizers and sharpness-aware training work directly with this curvature.
What it cannot do: Everything here treats p as a number to push around. Part 4 asks what it means.
Try it: The Hessian on the companion page
Where this leaves us
The one number to remember is 2/λmax. The gradient tells you which way to step; the largest curvature tells you how far you can step without overshooting.
Part 4 turns to what p means. A probability of 0.5 is a statement about the long run, the loss is an expected value, and the log-loss is a cross-entropy, which is also why the 0.693 keeps appearing.
Part 4: Why Is Your Loss Function an Expected Value?
probability, conditioning, expected value, the law of large numbers, entropy, cross-entropy and KL divergence.

The number 0.693 has appeared in every part of this series. It was the loss of each user in part 1's model, the starting height of the loss surface in part 3 (twice over), and it will show up here as a cross-entropy. That is not a coincidence. It is ln 2, the cost of a model that answers every question with a coin flip.
This part explains what the model's output p means, why the loss is an average, why averaging over a random minibatch is good enough, and why the log-loss is the same thing as cross-entropy.
The tiny model
One last look at the cast: both users get p = 0.5, and the log-loss is −ln p for the user who clicked and −ln(1 − p) for the user who did not. Read p as P(click | x), the probability of a click given what we know about the user. That reading needs the language of probability.
Every number below can be changed and recomputed on the companion page: Math for ML, by Hand, part 4.
What a probability promises

A probability is a statement about the long run, not a promise about a single trial.

Toss a fair coin 10 times. The tempting prediction is exactly 5 heads, and 5 is indeed the single most likely count. Its probability is only 252/1024 = 0.246: of the 1,024 equally likely sequences of heads and tails, 252 have five heads. About three runs in four give some other count.
What P(heads) = 0.5 promises is about many repetitions: over a very large number of tosses, the fraction of heads gets as close to 0.5 as you like. Section 19 makes that precise.
Formally, a probability assigns a number between 0 and 1 to events, which are subsets of the sample space Ω (all possible outcomes). Two rules do the work: the whole space has probability 1, and probabilities of events that cannot happen together add.

Why ML cares: The model's output p = 0.5 is a probability in exactly this sense: among many users who look like x, it predicts half will click. Calibration checks whether that holds on real data.
What it cannot do: One probability on its own ignores what we have observed. Models condition on evidence.
Try it: What a probability promises on the companion page
Conditioning and Bayes' theorem

Conditioning on B throws away every outcome outside B and rescales what is left.

Picture 1,000 emails. 200 are spam. The word "deal" appears in 120 spam emails and in 40 of the 800 legitimate ones. What is the chance an email is spam, given that it contains "deal"?
Keep only the emails that contain the word. 160 remain, and 120 of them are spam: P(spam | deal) = 120/160 = 0.75. That is the whole of conditioning: shrink the world to the evidence, then count.
The tempting slip is to swap the two sides. P(deal | spam) = 120/200 = 0.6 answers a different question, about a different world (only the spam emails). Bayes' theorem converts one into the other using the base rate: 0.6·0.2 / (0.6·0.2 + 0.05·0.8) = 0.75. Stating the problem as counts of emails rather than percentages, as here, is the format Gigerenzer and Hoffrage found makes these answers far easier to get right.

Why ML cares: A classifier's output is a conditional probability, P(click | x). Naive Bayes spam filters use this exact calculation, one word at a time.
What it cannot do: A probability describes one outcome. To score a model we need a single summary of many outcomes and their payoffs.
Try it: Conditioning and Bayes' theorem on the companion page
Expected value and the law of large numbers

The expected value is the long-run average, and the law of large numbers is the guarantee that the average gets there.

A die game: roll 1 or 2 and win $300, roll 3 to 6 and lose $200. Weight each payout by its probability: 300 · 2/6 − 200 · 4/6 = −100/3, about −33.33 per round. The game loses money on average, so you should not play it.
Simulate 10,000 rounds. The running average is −50 after 10 rounds, −55 after 100, −40 after 1,000 and −31 after 10,000, closing in on −33.33. The strong law of large numbers says this happens with probability 1 for independent repeats.
The law is often misread. A player on a losing streak may feel "due" a win. In the simulation, the rounds that came right after three losses in a row (2,853 of them) were won at a rate of 0.351, about the usual 1/3. The average converges because later rounds swamp the early ones, not because the dice correct themselves.
![Worked by hand: E[X] = 300·(2/6) + (−200)·(4/6) = 100 − 133.33 = −100/3 ≈ −33.33 ; running mean (seed 7): 10 → −50, 100 → −55, 1,000 → −40, 10,000 → −31 ; win rate right after 3 losses: 0.351 (vs 1/3)](https://mittalutkarsh.github.io/Mathematics_For_Machine_Learning/gifs/byhand-p4-19-expected-value.gif)
Why ML cares: The training loss is an expected value: the average log-loss over the distribution of users. We never see that distribution, only a sample, so the next section asks whether a sample is good enough.
What it cannot do: The expected value gives one average. Training averages gradients over small random batches, and we need to know how noisy that is.
Try it: Expected value and the law of large numbers on the companion page
Why minibatches work

A minibatch gradient is a sample average, so it is a fair, noisy estimate of the full gradient.

Our two-user loss is a sum of one term per user, and so is its gradient. On real data there are millions of terms. Stochastic gradient descent averages a random batch of them instead.
Take a toy set of 100,000 per-example gradients with average −0.50. Draw 2,000 random batches of each size and look at the batch averages. All three sizes centre on the full average. Their spread shrinks as the batch grows: 0.355 for batches of 8, 0.124 for 64, 0.044 for 512. Each 8-fold increase cuts the spread to about a third, because the spread of an average falls like 1/√m.

Why ML cares: This is why batch size and learning rate are tuned together: a larger batch gives a less noisy gradient and tolerates a larger step.
What it cannot do: Averages tell us how wrong we are on average, but not how to score a predicted distribution against the truth. That is information theory's job.
Try it: Why minibatches work on the companion page
Entropy counts yes/no questions

Entropy is the average number of yes/no questions a distribution leaves you to ask.

I pick a number from 1 to 1,024 and you ask yes/no questions. Halve the range each time and you need log₂ 1024 = 10 questions. That count is the entropy of the uniform distribution: 10 bits.
If I pick unevenly, you can do better on average by asking about the likely answers first. With four classes, a uniform distribution has entropy 2 bits. A peaked one, (0.7, 0.1, 0.1, 0.1), has 1.36 bits; the best question tree for it needs 1.50 questions on average, and no tree can beat the entropy. A certain distribution, (1, 0, 0, 0), has entropy 0: there is nothing to ask.
The uniform distribution has the most entropy, the most uncertainty. A distribution concentrated on one value has none.

Why ML cares: The predicted distribution of a classifier has an entropy. Low entropy means a confident prediction, which is useful for active learning and for flagging uncertain inputs.
What it cannot do: Entropy describes one distribution. Training compares two: the truth and the model's prediction.
Try it: Entropy counts yes/no questions on the companion page
Cross-entropy and KL divergence

Cross-entropy is the cost of describing the truth P with the model Q; KL is the part of it caused by Q being wrong.

For the user who clicked, the truth is one-hot: probability 1 on "clicked". The model says (0.5, 0.5). The cross-entropy is −1 · ln 0.5 = 0.693, which is the log-loss from part 1. Log-loss and cross-entropy are the same formula; this is where the 0.693 comes from.
Cross-entropy splits in two. Take a softer truth, P = (0.2, 0.8), against Q = (0.5, 0.5). H(P) = 0.500 is the uncertainty already in the truth. KL(P‖Q) = 0.193 is the extra cost of using Q instead of P. Together they make CE = 0.693.
Two consequences. First, a perfect prediction gives cross-entropy H(P), not zero; it reaches zero only when the truth is one-hot, as with ordinary labels. Second, KL is not a distance: KL(Q‖P) = 0.223, not 0.193. It is zero only when the two distributions are equal.

Why ML cares: Classification losses, label smoothing (a softer P), knowledge distillation (matching a teacher's Q) and the KL term in a variational autoencoder are all this formula.
What it cannot do: Nothing left to bridge. The closing figure maps every box of the tiny model to the part that explains it.
Try it: Cross-entropy and KL divergence on the companion page
Where this leaves us

Every box in the tiny model now has a name. The input is a vector (part 1), h = Ax is a linear map (part 2), the score is an inner product, the weights move by gradient descent at a step set by curvature (part 3), and the loss is a cross-entropy averaged over data (part 4).
That is the whole roadmap, worked on one model small enough to check by hand. The same pieces, at much larger sizes, are what a modern network is made of.