The cost function: how wrong is the line?
Turn "how good is this line?" into one number, the squared-error cost J(w,b), and see each error as a literal square.

In this lesson you will
- Compute the error of a single prediction, ŷ minus y
- Explain why errors are squared and averaged in the cost J(w,b)
- Read the cost formula and connect it to the picture of squares
- Explain that training means finding the w and b that make J smallest
You can judge a line by eye, but a computer needs a number: one score that is small when the line fits well and large when it fits badly. That score is called the cost function, and it’s the compass that every learning algorithm in this course steers by.
Step 1: the error for one house
Take one training example . The model predicts . The error for that house is how far the prediction is from the truth:
On the chart it’s the vertical gap between the dot and the line. Positive means the model guessed too high; negative means too low.
Step 2: square it
We can’t just add up the errors, because a guess that’s $50k too high and one that’s $50k too low would cancel out and look perfect. So we square each error. That makes every error positive, and it punishes big misses much more than small ones: an error of 2 counts four times as much as an error of 1.
Squaring has a lovely picture: the squared error is literally the area of a square whose side is the gap between the dot and the line.
Step 3: average over all houses
Add up the squares for all houses and divide by to get the average, so the score doesn’t grow just because we collected more data. By convention we divide by instead of ; the extra 2 makes a later formula tidier and doesn’t change which line is best.
Putting it together, the squared-error cost function is:
Read it out loud: “for every example, take the prediction minus the true value, square it, add them all up, and divide by two m.”
Watch the squares
Here are six houses, so every square is visible. Move and and watch the squares grow and shrink; the readout adds up their areas to give . On the right, the curve shows for every possible (with held where it is), and the dot shows where your current line sits on it.
Here are six houses and a line that's clearly too flat. Each vertical gap is one prediction's error.
Try to make the total area as small as you can. You will find there is one best slope: tilt the line less or more and the squares get bigger. That best point is the bottom of the curve on the right.
The goal of training
We now have a precise goal. Out of all possible lines, find the parameters that make the cost as small as possible:
In the next lesson you’ll see what looks like when both and can change, a whole landscape, and after that, how a computer finds its lowest point automatically.
Check yourself
Self-check · 4 questions