Cost Function
A cost function is a formula that turns "how wrong is this model?" into one number. Training a model means finding the parameters that make that number as small as possible.
Your Path Through This Lesson
0 of 5 done
- Turn "how wrong is this line?" into a single number.
- Compute the cost by hand and in NumPy.
- Read the cost bowl and find its minimum.
Why We Need One Number
In the last lesson we said the best line has the smallest residuals "overall". But a computer can't look at a picture and judge which line looks best. It needs a single number to compare: line A scores 46, line B scores 24, so B is better.
That number is the cost, written . Lower cost means a better line.
Building It Step by Step
Start with the errors, , for every example. Then:
- Square each error, so negatives don't cancel positives and big misses count more.
- Add them up across all examples.
- Divide by to get an average, so the cost doesn't grow just because you have more data.
- Divide by 2 as well. This is only a convenience: it cancels the 2 that appears when we take the derivative later.
The result is the mean squared error cost function:
where is the prediction for example , and is the number of examples.
Without the , this is the mean squared error (MSE) you'll see in metric tables. The doesn't change where the minimum is, only how tall the bowl is, so both give the same best line.
Trying Different Lines by Hand
To make it easy to picture, let's keep the intercept fixed at and try different slopes . Our data is still the five students (hours 1 to 5, marks 20, 40, 50, 40, 50), so .
Slope . Predictions are 26, 30, 34, 38, 42.
| error | error² | |||
|---|---|---|---|---|
| 1 | 20 | 26 | 6 | 36 |
| 2 | 40 | 30 | −10 | 100 |
| 3 | 50 | 34 | −16 | 256 |
| 4 | 40 | 38 | −2 | 4 |
| 5 | 50 | 42 | −8 | 64 |
| Sum | 460 |
Do the same for other slopes and you get this:
| Slope | Sum of squared errors | Cost |
|---|---|---|
| 0 | 2220 | 222 |
| 4 | 460 | 46 |
| 6 | 240 | 24 |
| 8 | 460 | 46 |
| 10 | 1120 | 112 |
The cost falls, bottoms out at , then rises again. The lowest cost is exactly the best-fit slope we found with least squares. That's no coincidence: least squares is "minimise this cost".
The Bowl
Plot against and you get a U-shaped curve, a bowl. Every point on the bowl is one possible line. The bottom of the bowl is the best one.
For our data the bowl has a neat formula (with ):
Plug in : . Matches the table.
When both and can change, the picture becomes a 3D bowl: a smooth valley with one lowest point. For linear regression the bowl is always this nice shape, with one single minimum and no false valleys. This shape is called convex, and it's why linear regression is so reliable to train.
Computing the Cost in Code
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([20, 40, 50, 40, 50])
m = len(x)
def cost(theta0, theta1):
y_hat = theta0 + theta1 * x
return np.sum((y_hat - y) ** 2) / (2 * m)
for theta1 in [0, 4, 6, 8, 10]:
print(f"theta1 = {theta1:>2}: J = {cost(22, theta1):.1f}")theta1 = 0: J = 222.0
theta1 = 4: J = 46.0
theta1 = 6: J = 24.0
theta1 = 8: J = 46.0
theta1 = 10: J = 112.0Loss vs Cost
You'll see both words, often used loosely:
| Term | Measures | Example |
|---|---|---|
| Loss | Error on one example | |
| Cost | Average error over the whole dataset |
Don't confuse the cost function with an evaluation metric. The cost function is what the algorithm minimises during training. Metrics like R² or RMSE are what you read afterwards to judge the model. Sometimes they're the same formula, sometimes not. Logistic regression, for example, trains on log loss but is often judged by accuracy.
- Use the
costfunction to try and . Are they equal? Why? - Now keep and change the intercept: try . Where is the minimum?
- Plot the bowl with
np.linspace(0, 12, 100)for and matplotlib.
Training a model means finding the parameters at the bottom of the cost bowl.
Summary
- The cost function turns "how wrong" into one number .
- For linear regression: .
- Plotted against the parameters, it's a convex bowl with one minimum: the best-fit line.
- Next: we can't always solve for the minimum with a formula. Gradient descent walks down the bowl step by step.