Gradient descent: walking downhill
The curve is the loss: how wrong the model is. The ball is the model’s current guess. Each step moves the ball against the slope. Click the plot to drop the ball somewhere new.
Lesson notes and things to try
The idea
The loss measures how wrong a model is. Training means finding the parameter value with the lowest loss. Gradient descent does this one small step at a time: it measures the slope f′(x) and moves the opposite way, because the slope points uphill.
xnew = x − η · f′(x)
The learning rate η sets the step size. The dashed line is the slope at the ball; the curved arrow shows where the next step will land.
Things to try
- Press the four buttons under the learning rate one by one. Too small crawls, just right glides in, bouncy overshoots back and forth, too big flies off the chart.
- Watch the steps get shorter near the bottom even though η stays the same. Ask the class why. (The slope gets flatter.)
- Pick “Two valleys” and press Play. The ball stops in the shallow valley on the right: a local minimum. Click the left half of the plot and run again to reach the deeper one.
- Still on “Two valleys”, press Reset and choose “Bouncy”. The big first jump lands in the deeper valley. Large steps are not always bad.
- “Bumpy” has many small dips, a bit like the loss of a real neural network.
Regression: fit a curve to points
Click to add data points or pick a dataset, then press Train. Gradient descent changes the weights until the curve passes close to the points.
Lesson notes and things to try
The model and the loss
The model draws a curve whose shape is set by its weights:
ŷ = w₀ + w₁x + w₂x² + … + wdxd
The dashed lines are the errors, one per point. The mean squared error (MSE) is the average of the squared error lengths. Gradient descent nudges every weight in the direction that makes the MSE smaller. That is all “training” means here.
MSE = (1/n) Σ (ŷᵢ − yᵢ)²
Things to try
- “Straight line” with degree 1: press Train and watch the line rotate and slide into place. Then press Solve exactly. Gradient descent and the exact formula reach the same answer.
- “Curve” with degree 1: a straight line can’t bend, so the error stays high. This is underfitting. Raise the degree to 2.
- “Few points” with degree 7, then Solve exactly: the curve passes through every point but swings wildly between them. This is overfitting. Now raise λ: large weights are penalised and the curve calms down.
- Push the learning rate to the far right and train. The loss explodes, just like the ball flying off in lesson 1.
Classification: draw a boundary between two groups
Logistic regression learns a boundary between class A and class B. Shading shows how confident the model is. Pick a dataset or click to add points, then press Train.
Lesson notes and things to try
The model and the loss
Logistic regression computes a score from the features, then squashes it into a probability between 0 and 1 with the sigmoid function:
z = w₁x₁ + w₂x₂ + b, p = σ(z) = 1 / (1 + e−z)
p is the chance that a point belongs to class B. The boundary is where p is exactly 50%, which happens when z = 0. Points with a dark outline are currently misclassified.
The loss is cross-entropy. It barely punishes confident correct answers and heavily punishes confident wrong ones, so the model works hardest on the points it gets badly wrong.
Things to try
- “Two groups” with straight-line features: accuracy reaches 100%. Keep training and the shading sharpens as the model grows more confident.
- “Circle”: no straight line can separate a ring from its centre, so accuracy stays low. Switch features to “Curved, degree 2” and train again.
- “XOR” also needs curved features. The product term x₁x₂ does the work.
- “Overlapping”: 100% accuracy is impossible. Add a few points of the wrong class by hand and watch the boundary move toward them.
Loss functions: how we measure “wrong”
The loss decides what the model cares about. Compare the famous regression losses on data with outliers, then see why classifiers use cross-entropy.
Regression losses: MSE, MAE and Huber
Two classes: binary cross-entropy
Many classes: softmax and categorical cross-entropy
The model gives each class a raw score (a logit). Softmax turns the scores into probabilities that add up to 100%. The loss is −ln of the probability given to the true class.
Lesson notes and things to try
The famous losses
With error e = ŷ − y:
MSE = (1/n) Σ e² MAE = (1/n) Σ |e| Huber = ½e² if |e| ≤ δ, else δ(|e| − ½δ)
Binary cross-entropy = −[y ln p + (1 − y) ln(1 − p)] Categorical cross-entropy = −ln ptrue
MSE squares each error, so one big error can outweigh many small ones. That makes it sensitive to outliers. MAE grows in a straight line, so outliers pull no harder than any other point. Huber is squared for small errors and straight for large ones: smooth near the answer, robust far away.
Cross-entropy only looks at the probability the model gave to the true answer. Giving it 0.9 costs 0.105; giving it 0.01 costs 4.6. Squared error on probabilities can never go above 1, so it barely tells “wrong” from “confidently wrong”, and its gradient vanishes exactly when the model is most wrong.
Things to try
- Press Remove outliers: the three lines almost agree. Press Add outliers: the MSE line tilts toward them while MAE and Huber stay with the main trend.
- Click to place a single point far from the others and watch which line moves most.
- Drag Huber’s δ to its maximum: Huber becomes almost MSE. Drag it to the minimum: it behaves like MAE.
- Cross-entropy: with true class B, slide p from 0.9 to 0.1 and read the loss at each stop. Then switch the true class to A.
- Softmax: press Confident and right, then Confident and wrong. Ask the class why the second loss is so large. Then press Unsure: each class gets 33%, and the loss is ln 3 ≈ 1.1.
Overfitting and underfitting: will it work on new data?
Filled dots are the training data the model learns from. Hollow dots are test data it never sees. A good model has low error on both. Change the degree and watch both errors.
Lesson notes and things to try
The idea
We never care about the training data for its own sake: we care about new data. So we hide some data (the test set) and only use it to check the model.
Underfitting: the model is too simple. Training error and test error are both high. Overfitting: the model is so flexible that it fits the noise. Training error is tiny, test error is large, and the gap between them is the warning sign.
Test error = Bias² + Variance + Noise
Bias is the error from a wrong shape (a line for a wave). Variance is how much the fitted curve changes if we collect a different sample. Simple models have high bias; complex models have high variance.
Things to try
- Press Underfit, Good fit and Overfit in turn. Read the training error, test error and gap each time.
- Look at the error chart: training error falls all the way, test error is U-shaped. Click any degree on the chart to jump to it.
- At Overfit, tick “Fits from 6 other samples”. The curves disagree wildly: that is high variance. At Underfit they agree with each other but are all wrong: that is high bias.
- Still at Overfit, raise the number of training points to 80. More data is the strongest cure for overfitting.
- Go back to 14 points and raise λ slowly. Regularization calms the curve; too much λ flattens it into underfitting.
- Set noise to 0: overfitting almost disappears, because there is no noise to memorize.
Optimizers: six ways to walk downhill
Each coloured path is a different optimizer starting from the same point on a loss surface seen from above. Contour lines join points of equal loss; the stronger the colour, the lower the loss. Click anywhere to choose a new start.
Lesson notes and things to try
How they differ
Every optimizer uses the gradient g, the slope in every direction, to choose its next step. They differ in what they remember about earlier gradients. θ stands for the model’s parameters (here, the position on the map).
- Gradient descent
- θ ← θ − η g. Steps straight downhill. Zigzags in narrow valleys and slows to a crawl where the ground is flat.
- Momentum
- v ← βv − η g, θ ← θ + v. A heavy ball that builds up speed. Zigzags cancel out, and the speed can carry it over small hills.
- Nesterov
- Momentum that looks ahead: it measures the gradient at θ + βv, where it is about to land, so it brakes earlier and overshoots less.
- AdaGrad
- G ← G + g², θ ← θ − η g / √G. Every direction gets its own step size. Because G only grows, steps keep shrinking and it can stop too early.
- RMSProp
- s ← ρs + (1 − ρ) g², θ ← θ − η g / √s. Like AdaGrad but with a moving average, so the steps don’t die out.
- Adam
- Momentum and RMSProp combined, plus a correction for the first few steps. The usual default for training neural networks.
Things to try
- Narrow valley: gradient descent zigzags across the steep direction. Set momentum β to 0 and Momentum turns into plain gradient descent.
- Saddle point: gradient descent lingers near the centre, where the slope is almost zero, before escaping. AdaGrad and Adam get out quickly.
- Four valleys: four equally good answers. From the same start, the optimizers split between two different valleys.
- Local vs global minimum: most optimizers stop in the shallow valley. Momentum and Nesterov roll over the hill into the deeper one. Lower β to 0.7 and they get stuck too.
- Raise one optimizer’s learning rate until it flies off the map. Each optimizer has its own safe range.