012345$0$3$6$9$12kmfare$11.501 km$32 km$43 km$84 km$9fare = w·km + bwb1for step in range(1000):2 pred = w * x + b3 err = pred - y4 loss = np.mean(err**2)5 dw = 2 * np.mean(err * x)6 db = 2 * np.mean(err)7 w -= lr * dw8 b -= lr * dblossdL/dwdL/db5 km?$11.50
Chart: dots are the rides, the teal line is the model, dashed gaps are the errors, squares are the squared errorsTeal block: the model, holding w (slope) and b (bias)Gold chips: the gradient nudging w and b; mint chip: a new rideAt the back, a chart of four taxi rides (km across, fare up) and the model's straight line, fare = w × km + b. In the middle, the training data, the model with its two numbers w and b, and a new ride. In front, the training loop in Python and three readouts: the loss and the gradients for w and b. One round of training: predict, measure the errors, square and average them (the loss), find which way lowers the loss (the gradient), and nudge w and b a small step that way. Repeated, the line settles on w = 2.2, b = 0.5. For a straight line the best w and b can also be computed directly (least squares). Gradient descent is shown because the same loop trains models that have no such formula, including neural networks.

The data and the line

  1. The training data: four taxi rides. For each we know the distance in km, the feature, and the fare in dollars, the label. On the chart, longer rides cost more, roughly along a straight line. We want a rule that predicts fares.

One round of training

The training loop

What happens

;; step 1/9 · data
ride   km (feature x)   fare (label y)
  1      1                $3.00
  2      2                $4.00
  3      3                $8.00
  4      4                $9.00

goal: a rule that turns km into a fare

The four rides are invented for the lesson, small enough to check by hand. Real fares also depend on time and traffic; with more features the model becomes w1·x1 + w2·x2 + ... + b (multiple linear regression). The learning rate matters: for these rides, any rate above about 0.12 makes the steps overshoot and the loss explode; a much smaller one works but needs far more rounds.