x = 1y = 2x = 2y = 401234wguess = w × xw0lossslope1w, lr = 0.0, 0.12for step in range(4):3 g = grad(w)4 w = w - lr * g
Lavender valley: the loss for every value of wTeal block: the model, holding w, the loss and the slopeBlue ball: the current w · gold arrow: the downhill slope · dots: earlier stepsAt the back: two training examples, the training loop in Python, and the model, which remembers its weight w, the loss and the slope. In front, the loss valley: the height of its top is the loss for each w, lowest at w = 2. The ball is the current w and the gold arrow is the slope under it. Each gradient step hops downhill by the learning rate times the slope, so the steps shrink near the bottom; a tiny rate creeps and a large one bounces. For this data the loss is 2.5 × (w − 2)² and its slope is 5 × (w − 2), so with a learning rate of 0.1 each step halves the distance to w = 2. Real losses are rarely this tidy.

The loss valley

  1. The model guesses y from x using one number, its weight w: guess = w × x. Two training examples: x = 1 should give 2, and x = 2 should give 4. Training must find a good w. We start at w = 0.

Walking downhill

Step size and scale

What happens

;; step 1/9 · setup
model      guess = w * x
data       x = 1 -> y = 2
           x = 2 -> y = 4
start      w = 0   (guesses 0 and 0: both wrong)
goal       find the w with the smallest loss

For this data the loss is 2.5 × (w − 2)² and its slope is 5 × (w − 2), so with a learning rate of 0.1 each step halves the distance to w = 2. Real losses are rarely this tidy. A real loss surface can have many dips. Gradient descent only walks downhill from where it starts, so it can stop in a dip that is not the lowest one.