Linear regression
About this lesson
Linear regression predicts a number with a straight line: fare = w × km + b. Training finds the two numbers w and b from examples. Watch one full round of the training loop on four taxi rides, number by number: predict, measure the errors, average their squares into the loss, follow the gradient downhill and update. Then repeat it 1000 times until the line settles, and use it to price a ride it has never seen.
Four taxi rides
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.
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
Read the lesson step by step
Four taxi rides
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.
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 fareA straight-line guess
Linear regression predicts with a straight line: fare = w × km + b. The weight w sets the slope, dollars per km. The bias b lifts the line, like a starting fee. Training starts from a guess: w = 1, b = 0.
model: fare = w * km + b w weight: slope, dollars per km b bias: where the line crosses 0 km first guess w = 1.0, b = 0.0 training will only ever change these two numbersPredict, then compare
With w = 1, b = 0 the line predicts $1, $2, $3, $4 for the four rides. The real fares were $3, $4, $8, $9. Each error is prediction minus real fare: −2, −2, −5, −5.
pred = w * x + b err = pred - y 1 km pred 1 real 3 err −2 2 km pred 2 real 4 err −2 3 km pred 3 real 8 err −5 4 km pred 4 real 9 err −5 the dashed gaps on the chart are the errorsOne number: the loss
To score the whole line, square each error and average: (4 + 4 + 25 + 25) ÷ 4 = 14.5. This is the loss, the mean squared error. Squaring makes every error positive and punishes big misses most.
loss = np.mean(err**2) errors −2, −2, −5, −5 squared 4, 4, 25, 25 mean (4 + 4 + 25 + 25) / 4 = 14.5 lower is better; 0 would mean every dot is on the lineWhich way is downhill?
The gradient tells how the loss changes if we nudge each number up a little. For w it is −20.5; for b, −7. Negative means the loss falls when that number goes up, so both should grow.
dw = 2 * np.mean(err * x) = 2 * mean(−2×1, −2×2, −5×3, −5×4) = −20.5 db = 2 * np.mean(err) = 2 * mean(−2, −2, −5, −5) = −7 negative: raising w or b lowers the lossTake a small step
Gradient descent steps each number against its gradient, scaled by the learning rate, 0.05. w becomes 1 − 0.05 × (−20.5) = 2.025; b becomes 0.35. The line swings toward the dots: the loss drops from 14.5 to 0.83.
w -= lr * dw 1 - 0.05 * (−20.5) = 2.025 b -= lr * db 0 - 0.05 * (−7) = 0.35 loss 14.5 -> 0.83 lr = 0.05 is the learning rate: the step sizeRepeat: the training loop
That was one round of the training loop: predict, measure the loss, find the gradient, update. Repeat it 1000 times. The steps get smaller as the line gets closer, because the gradient shrinks.
round w b loss 0 1.000 0.000 14.500 1 2.025 0.350 0.833 2 2.194 0.409 0.461 5 2.226 0.424 0.451 20 2.221 0.439 0.451 100 2.206 0.482 0.450 1000 2.200 0.500 0.450The best straight line
Training settles at w = 2.2 and b = 0.5: $2.20 per km plus a $0.50 start. The loss stops at 0.45, not 0: no straight line passes through all four dots. The least-squares formula gives this same line.
trained w = 2.2000 b = 0.5000 least squares w = 11 / 5 = 2.2 b = 6 - 2.2 * 2.5 = 0.5 loss = 0.45, the smallest any straight line getsPredict a new ride
Now use the model on a ride it has never seen: 5 km. It predicts 2.2 × 5 + 0.5 = $11.50. Training learned just two numbers, w and b; predicting is the line's formula.
fare = w * km + b = 2.2 * 5 + 0.5 = $11.50 the new ride lands on the line, past the data
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A model says fare = 2 × km + 1. What does it predict for a 3 km ride?
Multiply by the weight, then add the bias: 2 × 3 + 1 = 7. The weight is the slope (dollars per km) and the bias is the fare at 0 km.
02A line's errors on three examples are 1, −1 and 2. What is its mean squared error?
Square each error (1, 1, 4), add them (6) and divide by the number of examples (3): 6 ÷ 3 = 2. Squaring stops a negative error cancelling a positive one.
03The gradient of the loss for w is −20 and the learning rate is 0.05. What does one gradient-descent update do to w?
The update is w −= learning rate × gradient: w − 0.05 × (−20) = w + 1. A negative gradient means the loss falls as w rises, so w goes up.
04Why does training stop with a loss of 0.45 and not 0 on the four taxi rides?
The least-squares formula gives the same line (w = 2.2, b = 0.5) and its loss is 0.45. The rides do not lie exactly on one line, so some error always remains.
05What happens if the learning rate is much too large?
Too big a step jumps past the lowest point to the other side, further up. For these rides any rate above about 0.12 makes the loss explode; too small a rate works but needs many more rounds.
Glossary
- Linear regression
- A model that predicts a number with a straight line, y = w × x + b (with more features, one weight per feature plus a bias).
- Weight (w)
- The number a feature is multiplied by; for one feature, the slope of the line (here, dollars per km).
- Bias (b)
- The number added at the end; where the line crosses x = 0 (here, a starting fee).
- Error
- A prediction minus the real value (the label) for one example.
- Loss (mean squared error)
- One number for how wrong the model is: the average of the squared errors. Lower is better.
- Gradient
- How fast the loss changes as each weight or bias goes up; its sign says which way is downhill.
- Learning rate
- How big a step each update takes against the gradient. Too big overshoots; too small is slow.
- Gradient descent / training loop
- Repeating predict, loss, gradient, update until the loss stops falling.
Notes and sources
- 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).
- Some texts (CS229 among them) halve the squared error, or sum instead of averaging. That only scales the gradient; the best line is the same.
- 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.
- 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 Python program in the lesson is real: run it (with numpy installed) and it prints "2.2 0.5 0.45" then "11.5".
- Stanford CS229 Machine Learning, lecture notes (A. Ng, T. Ma), part I: linear regression, LMS (gradient descent) and the normal equations
- Goodfellow, Bengio & Courville, Deep Learning (2016), section 5.1.4: linear regression
- Goodfellow, Bengio & Courville, Deep Learning (2016), section 4.3: gradient-based optimization
- Google Machine Learning Crash Course: linear regression, loss, gradient descent and hyperparameters
- James, Witten, Hastie & Tibshirani, An Introduction to Statistical Learning, 2nd ed. (2021), chapter 3: linear regression
- scikit-learn user guide: ordinary least squares
- NumPy reference: numpy.mean
Quiz Unlocks after the last step.