Linear Regression and Gradient Descent, Step by Step
Linear regression is often the first model people meet when they study machine learning, and for good reason. It is small enough to understand completely, yet it uses the same idea that trains much bigger models: make a guess, measure how wrong it is, and nudge the numbers to be a little less wrong. That nudging is called gradient descent.
The model: a straight line
Suppose you have made-up data about a game: how many hours someone practiced (x) and how many points they scored (y).
| Hours practiced (x) | Points scored (y) |
|---|---|
| 1 | 3 |
| 2 | 5 |
| 3 | 6 |
| 4 | 9 |
| 5 | 10 |
| 6 | 13 |
The points go up roughly in a straight line, so a sensible model is
y = w x + b
Here w is the weight (the slope: how many extra points each extra hour is worth) and b is the bias (the intercept: where the line crosses the y axis). These two numbers are the model's parameters. "Learning" means finding values of w and b that make the line fit the points well.
The task is called regression because the answer is a number (points), not a category such as "cat" or "dog". When the answer is a category, the task is called classification.
Measuring the error
To improve a line, you need a single number that says how bad it is. For each point, the line makes a prediction, w x + b, and the error is the prediction minus the true y. Some errors are positive and some negative, so we square them (which makes them all positive and punishes big misses more), add them up and divide by the number of points. That is the mean squared error, or MSE:
MSE = the average of (w x + b minus y) squared, over all the points
A perfect line would have an MSE of 0. Real data is noisy, so the goal is the smallest MSE you can get, not zero.
Gradient descent: walking downhill
Imagine every possible pair of (w, b) as a spot on a hilly landscape, where the height is the MSE. You are standing somewhere on the hill in thick fog, and you want to reach the lowest valley. You cannot see the valley, but you can feel which way the ground slopes under your feet. So you take a small step downhill, feel the slope again, and repeat.
The "slope under your feet" is the gradient: for each parameter, it says whether making that parameter a little bigger would raise or lower the error, and how steeply. For MSE on a straight line the gradients have simple formulas:
- gradient for w = the average of 2 x (error) x x
- gradient for b = the average of 2 x (error)
Each step then moves the parameters a little way against the gradient:
w = w minus learning rate x gradient for w
b = b minus learning rate x gradient for b
The learning rate sets the size of each step. It is a setting you choose, not something the model learns.
A short Python program
Examples use Python 3.10 or later and only the standard library. This program starts with w and b at 0, then runs 2,000 passes of gradient descent over the six points above, printing the progress now and then.
# Made-up data: hours of practice (x) and points scored in a game (y)
xs = [1, 2, 3, 4, 5, 6]
ys = [3, 5, 6, 9, 10, 13]
w = 0.0 # slope: starts as a guess
b = 0.0 # intercept: starts as a guess
learning_rate = 0.02
n = len(xs)
def mean_squared_error(w, b):
total = 0.0
for x, y in zip(xs, ys):
error = (w * x + b) - y
total += error ** 2
return total / n
for epoch in range(1, 2001):
grad_w = 0.0
grad_b = 0.0
for x, y in zip(xs, ys):
error = (w * x + b) - y
grad_w += 2 * error * x / n
grad_b += 2 * error / n
w -= learning_rate * grad_w
b -= learning_rate * grad_b
if epoch in (1, 10, 100, 500, 1000, 2000):
print(f"epoch {epoch:4d}: w = {w:.3f}, b = {b:.3f}, error = {mean_squared_error(w, b):.3f}")
print(f"Prediction for 7 hours: {w * 7 + b:.1f} points")
Running it with Python 3.12 printed:
epoch 1: w = 1.300, b = 0.307, error = 9.314
epoch 10: w = 2.028, b = 0.503, error = 0.238
epoch 100: w = 1.987, b = 0.678, error = 0.220
epoch 500: w = 1.945, b = 0.857, error = 0.213
epoch 1000: w = 1.943, b = 0.866, error = 0.213
epoch 2000: w = 1.943, b = 0.867, error = 0.213
Prediction for 7 hours: 14.5 points
A few things to notice:
- After one step the line is already far better than the starting guess (w = 0, b = 0 predicts 0 points for everyone).
- After about 500 passes the numbers barely change. The model has reached the bottom of the valley: w is about 1.943 and b about 0.867, so each hour of practice is worth just under 2 points in this made-up data.
- The error never reaches 0, because the points do not lie exactly on one line. That is normal.
zip(xs, ys)walks through the two lists together, giving one (x, y) pair at a time.w -= learning_rate * grad_wis short forw = w - learning_rate * grad_w.
For a straight line there is also a formula that gives the exact answer in one go (called least squares), and it gives the same w and b here. Gradient descent matters because it also works for models where no such formula exists, including neural networks with thousands or millions of parameters.
Too big a step, too small a step
The learning rate is a balancing act. This second program trains the same line for only 20 passes with three different learning rates and prints the final error.
xs = [1, 2, 3, 4, 5, 6]
ys = [3, 5, 6, 9, 10, 13]
n = len(xs)
def train(learning_rate, epochs):
w, b = 0.0, 0.0
for _ in range(epochs):
grad_w = sum(2 * ((w * x + b) - y) * x / n for x, y in zip(xs, ys))
grad_b = sum(2 * ((w * x + b) - y) / n for x, y in zip(xs, ys))
w -= learning_rate * grad_w
b -= learning_rate * grad_b
error = sum(((w * x + b) - y) ** 2 for x, y in zip(xs, ys)) / n
return error
for rate in (0.001, 0.02, 0.08):
print(f"learning rate {rate}: error after 20 epochs = {train(rate, 20):.3f}")
Output:
learning rate 0.001: error after 20 epochs = 19.260
learning rate 0.02: error after 20 epochs = 0.235
learning rate 0.08: error after 20 epochs = 3470510528.941
- Too small (0.001): every step is tiny, so after 20 passes the model has hardly moved. It would get there eventually, just slowly.
- About right (0.02): the error is already close to its lowest value.
- Too big (0.08): each step jumps right over the valley and lands higher up the other side, then jumps further the next time. The error explodes instead of shrinking. This is called overshooting or diverging.
The "right" learning rate depends on the data and the model, so people try a few values and watch the error. If it goes up or jumps around, the step is too big; if it falls painfully slowly, the step may be too small. (Scaling the inputs so they are not huge numbers also helps a lot.)
Epochs: one pass over the data
Each time the program goes through all six points and updates w and b once, it completes one epoch. Here the whole dataset is one batch, so one epoch is exactly one update, and 2,000 epochs means 2,000 updates. With bigger datasets people usually split each epoch into smaller batches and update after each one. The guide to epochs, batches and training time explains how those numbers add up, and the Training Time Estimator does the arithmetic once you have measured how many examples per second your computer handles.
Where linear regression fits, and where it does not
Linear regression is a strong first choice when the answer is a number, the relationship is roughly a straight line, and you need to explain the model (the weight literally says "this much more y for each extra x"). That is why the ML Algorithm Selector lists Linear Regression first for a regression task where you need to explain the result. Like every suggestion from that tool, it is a starting point: train a few models and compare them on your own data.
It struggles when the pattern curves, when there are big outliers (one strange point can drag the line, because squaring makes big errors count a lot), or when the answer is a category. It can also be fooled into reading too much into small data, which is the problem covered in overfitting and underfitting, although a two-parameter line is more likely to be too simple than too complex.
Real projects add more inputs (for example y = w1 x1 + w2 x2 + b, with one weight per feature), and usually use a library such as scikit-learn rather than hand-written loops. The idea underneath stays the same: a prediction, an error, and small steps downhill.