How a machine learns: gradient descent from scratch

Every neural network, every PINN, learns by repeating four moves — guess, measure the error, find the slope, step downhill. Here they are with ten apples, a pencil, and no assumptions.

⏱ 35 minNeeds: derivatives (Chapter 2)2 labs · 3 animations · 1 video
In plain words

You do not know the answer, so you guess. You check how wrong the guess is. You work out which direction makes it less wrong. You move a little in that direction. You repeat until the guess stops improving. That is gradient descent, and "learning" in machine learning means nothing more than this — done for millions of unknown numbers at once.

You will learn
Level 1 · basicThe apple puzzle, the loss, the slope, the minus sign, steps by hand Level 2 · standardLearning rate, two unknowns, fitting a line, a neuron Level 3 · advancedWhy not just solve? Convergence factor, batches, links to numerical analysis
Video (66 s, no sound): the whole chapter in one minute — the apple puzzle, the recipe, the minus sign and the learning rate.

1. The puzzle: what does one apple cost?

You bought 10 apples and paid ₹300. What is the price $p$ of one apple?

Of course $p = 300/10 = 30$. But pretend you cannot divide. You can only guess a price, check it, and improve it. This is exactly the situation of a neural network: it cannot "divide" its way to the answer, because its equations are far too complicated. It can only guess, check and improve.

Apple puzzleMachine-learning word
the unknown price $p$parameter or weight (the number we learn)
the rule "bill = 10 × price"model: $\hat y = 10p$ (the hat means "predicted")
the real bill ₹300data or target $y = 300$
how wrong the bill iserror $\hat y - y$ and loss
improving the guesstraining / learning

2. Measuring how wrong: the loss

Guess $p = 20$. The model predicts a bill of $10 \times 20 = 200$. The real bill was 300. The error is $200 - 300 = -100$: the guess is too cheap by ₹100.

We turn the error into one number that is never negative and is zero only when the guess is perfect. The usual choice is to square it: $$L(p) = (\text{prediction} - \text{target})^2 = (10p - 300)^2 .$$ This is the loss. Why square, and not just take the error?

guess $p$prediction $10p$error $10p - 300$loss $(10p-300)^2$
20200−10010 000
25250−502 500
3030000
35350+502 500
40400+10010 000

Plotted against $p$ the loss is a U-shaped curve (a parabola) with its lowest point at the true price. Learning = finding the bottom of this valley.

3. Which way is downhill? The slope

Standing at a guess $p$ on the loss curve, the derivative $dL/dp$ is the slope of the curve there (Chapter 2). Let us compute it without skipping anything. Write $e = 10p - 300$, so $L = e^2$.

  1. How does $L$ change with $e$? $\;\dfrac{dL}{de} = 2e$.
  2. How does $e$ change with $p$? $\;e = 10p - 300$, so $\dfrac{de}{dp} = 10$.
  3. Chain rule: multiply the two. $\;\dfrac{dL}{dp} = \dfrac{dL}{de}\cdot\dfrac{de}{dp} = 2e \cdot 10 = 20\,(10p - 300).$
  4. At $p = 20$: $\;\dfrac{dL}{dp} = 20 \times (200 - 300) = 20 \times (-100) = -2000.$

The slope is negative: the curve goes down as $p$ increases. So to reduce the loss we should increase $p$ — which is right, since 20 is too cheap. At $p = 40$ the slope is $20 \times 100 = +2000$, positive: the curve goes up as $p$ increases, so we should decrease $p$.

The rule in one line

The sign of the slope points uphill. The size of the slope says how steep it is (far from the bottom it is steep, near the bottom it is almost flat).

4. Why the minus sign?

The gradient-descent update is $$\boxed{\;p_{\text{new}} = p_{\text{old}} - \eta\,\frac{dL}{dp}(p_{\text{old}})\;}$$ where $\eta$ (Greek "eta") is a small positive number called the learning rate. The minus sign is there because the slope points uphill and we want to go downhill:

situationslope $dL/dp$$-\eta \cdot$ slopeeffect on $p$
guess too cheap ($p = 20$)negative ($-2000$)positive ($+4$ with $\eta = 0.002$)$p$ goes up ✓
guess too dear ($p = 40$)positive ($+2000$)negative ($-4$)$p$ goes down ✓
guess exact ($p = 30$)$0$$0$$p$ stays ✓

With a plus sign the guess would move uphill every time: the loss would grow and the price would run away. That is "gradient ascent" — useful for finding a maximum, useless for learning.

Animation: with the minus sign the guess slides down to the bottom of the loss curve; with a plus sign it climbs up the side and runs away.
Watch: same start, same learning rate. Minus (green) slides into the valley; plus (red) climbs out of it.
Why it always works for small steps

Taylor's theorem (Chapter 2) says that for a small move $\Delta p$, $L(p + \Delta p) \approx L(p) + L'(p)\,\Delta p$. Choose $\Delta p = -\eta L'(p)$. Then $$L(p - \eta L'(p)) \approx L(p) - \eta\,\big(L'(p)\big)^2 \;\le\; L(p),$$ because a square is never negative. So, for a small enough $\eta$, every step lowers the loss unless the slope is already zero — i.e. unless we are at the bottom.

5. Four steps by hand

Start at $p_0 = 20$ with learning rate $\eta = 0.002$. The slope is $L'(p) = 20(10p - 300) = 200\,(p - 30)$.

stepguess $p$bill $10p$errorlossslope $200(p-30)$new $p = p - 0.002\times$slope
020200−10010 000−200020 + 4 = 24
124240−603 600−120024 + 2.4 = 26.4
226.4264−361 296−72026.4 + 1.44 = 27.84
327.84278.4−21.6466.56−43227.84 + 0.864 = 28.704
428.704287.04−12.96167.96−259.228.704 + 0.5184 = 29.2224

Look at the distance to the answer: $10 \to 6 \to 3.6 \to 2.16 \to 1.296 \to 0.7776$. Each step multiplies it by $0.6$. After 20 steps the distance is $10 \times 0.6^{20} \approx 0.0004$: the machine has "learned" that an apple costs ₹30.

Animation: ten apples, a guessed price, bars comparing the predicted and actual bill, and a ball sliding down the loss curve towards 30, from a cheap start and then from an expensive start.
Watch: starting too cheap (₹8) and then too dear (₹52). The orange line is the slope; the minus sign always pushes the guess towards ₹30.
Lab · learn the price of an applepress Step and read the table
The arrow shows where the update moves the guess. Try: η = 0.005 (it lands on 30 in one step — see section 6), η = 0.009 (zig-zag), η = 0.0105 (explodes), and the "+" rule (runs away). Change the number of apples and notice that the safe learning rate changes too.

6. The learning rate: how big a step?

In the apple problem everything can be computed exactly. With $n$ apples and true price $p^*$, the loss is $L = (np - np^*)^2 = n^2(p - p^*)^2$ and the slope is $2n^2(p - p^*)$. One step gives $$p_{\text{new}} - p^* = (p - p^*) - \eta\cdot 2n^2(p - p^*) = \big(1 - 2\eta n^2\big)(p - p^*).$$ So the distance to the answer is multiplied by the factor $1 - 2\eta n^2$ every step. With $n = 10$, $\eta = 0.002$: factor $1 - 0.4 = 0.6$, as in the table.

Animation: four copies of the loss curve; with a tiny learning rate the guess creeps, with a good one it arrives, with a large one it zig-zags, with a larger one it flies off.
Watch: too small → slow; just right → fast; too large → zig-zag; larger still → divergence.
Notice

The safe learning rate depends on the problem ($n^2$ here — the curvature of the loss). In a network, different weights see different curvatures, so no single $\eta$ is ideal for all of them. That is exactly why adaptive methods such as Adam (Adaptive Moment Estimation) scale the step for each weight separately.

7. Two unknowns: apples and bananas

Two shopping baskets:

Unknowns: apple price $a$ and banana price $b$ (two weights). Loss: the average of the squared errors of both baskets, $$L(a,b) = \tfrac12\Big[(3a + 2b - 130)^2 + (a + 4b - 110)^2\Big].$$ Now there are two slopes, one per unknown — the partial derivatives (Chapter 2): $$\frac{\partial L}{\partial a} = 3(3a+2b-130) + (a+4b-110),\qquad \frac{\partial L}{\partial b} = 2(3a+2b-130) + 4(a+4b-110).$$ Together they form the gradient $\nabla L = (\partial L/\partial a,\ \partial L/\partial b)$, an arrow pointing uphill on the loss surface. Gradient descent updates both prices at once: $$a \leftarrow a - \eta\,\frac{\partial L}{\partial a},\qquad b \leftarrow b - \eta\,\frac{\partial L}{\partial b}.$$

Lab · two prices at onceclick the map to choose a start
Colours show the loss (blue low, red high). The orange arrow is $-\nabla L$, the downhill direction; the path converges to $(30, 20)$. Check: $3\cdot30 + 2\cdot20 = 130$ ✓, $30 + 4\cdot20 = 110$ ✓. The valley is long and narrow, so with larger $\eta$ the path zig-zags — the same effect you saw in one dimension.

8. From prices to weights: fitting a straight line

Now real data: $N$ points $(x_i, y_i)$, say hours studied and marks obtained. Model: a straight line $\hat y = w x + b$ with two unknowns, the slope $w$ and intercept $b$ — the two "prices". Loss: mean squared error $$L(w,b) = \frac1N\sum_{i=1}^{N}\big(w x_i + b - y_i\big)^2 .$$ Slopes (chain rule, exactly as in section 3, applied to each term): $$\frac{\partial L}{\partial w} = \frac2N\sum_i (w x_i + b - y_i)\,x_i,\qquad \frac{\partial L}{\partial b} = \frac2N\sum_i (w x_i + b - y_i).$$ Updates: $w \leftarrow w - \eta\,\partial L/\partial w$, $b \leftarrow b - \eta\,\partial L/\partial b$. Same four moves.

Tiny example with numbers

Data: $(1, 3)$ and $(2, 5)$ (the true line is $y = 2x + 1$). Start at $w = 0$, $b = 0$, $\eta = 0.1$. Predictions $0, 0$; errors $-3, -5$. $\partial L/\partial w = \tfrac22[(-3)(1) + (-5)(2)] = -13$, $\;\partial L/\partial b = \tfrac22[-3 - 5] = -8$. Update: $w = 0 - 0.1(-13) = 1.3$, $b = 0 - 0.1(-8) = 0.8$. New predictions $2.1$ and $3.4$ — already much closer to $3$ and $5$. Keep going and $(w,b) \to (2, 1)$.

9. From a line to a neuron to a network

A neuron is a line followed by a bend: $\hat y = \sigma(wx + b)$ (Chapter 12). The loss and the update are the same; only the slope gets one more factor from the chain rule: $$\frac{\partial L}{\partial w} = \frac2N\sum_i\big(\hat y_i - y_i\big)\,\sigma'(wx_i+b)\,x_i .$$ A network is thousands of neurons, so thousands or millions of weights, each with its own slope. Writing those slopes by hand is impossible. They are computed automatically and efficiently by backpropagation — the subject of Chapter 14.

The one recipe behind all of machine learning
  1. Predict with the current weights (the forward pass).
  2. Measure the loss.
  3. Slope: compute the gradient of the loss with respect to every weight (backpropagation).
  4. Step: every weight $\leftarrow$ weight $- \eta \times$ its slope.
  5. Repeat until the loss stops decreasing.

10. Why not just solve the equation?

For the apples, $10p = 300$ gives $p = 30$ instantly. For the line, setting both partial derivatives to zero gives two linear "normal equations" that can be solved directly. So why bother with steps?

For numerical analysts

Gradient descent on a least-squares loss $\tfrac12\|Ax - b\|^2$ is the Richardson (Landweber) iteration $x \leftarrow x - \eta A^{\mathsf T}(Ax - b)$. It converges for $0 < \eta < 2/\lambda_{\max}(A^{\mathsf T}A)$, at a rate governed by the condition number — the same story as the apple factor $1 - 2\eta n^2$. See Chapter 11, section 3.

11. One example at a time: batch, mini-batch, stochastic

With a million data points, computing the exact average slope at every step is expensive. Instead:

variantslope computed frompros / cons
(Full) batch gradient descentall $N$ examplesexact slope, expensive per step
Stochastic gradient descent (SGD)one random examplevery cheap, very noisy
Mini-batch SGDa random handful (e.g. 32 or 256)the usual compromise; fits GPUs well

One epoch = one pass through all the data. In PINNs the "data" are often collocation points, and a fresh random batch of collocation points can be drawn at every step.

n, bill = 10, 300          # 10 apples cost 300
p, eta = 20.0, 0.002       # first guess and learning rate
for step in range(12):
    error = n * p - bill               # prediction minus target
    loss = error ** 2
    slope = 2 * error * n              # chain rule: dL/dp
    print(f"step {step:2d}: p = {p:8.4f}  loss = {loss:10.3f}  slope = {slope:9.2f}")
    p = p - eta * slope                # step AGAINST the slope
print("learned price:", round(p, 4))
Key takeaways

Further reading