Gradient LabStart the lesson

Lessons › Chapter 3: Regression and optimization

Loss functions

We have a line and its residuals. To compare two lines we need one number that sums up how wrong a line is. That number is the loss.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

How wrong is it?

Leo has several attempts at the line. Maya wants a single number to compare them fairly.

Concept

Start from the residuals

We have a line and its residuals. To compare two lines we need one number that sums up how wrong a line is. That number is the loss.

Build

Square each error

Square every residual. Picture it literally: each error becomes a square tile whose area is error². Squaring removes the minus signs and makes big misses count extra.

Key idea

Average into one number

Pour all the squares into one tower and divide by the count. That is the mean squared error. For our best line, MSE = 0.093. Small tower, good line.

Build

A worse line, a bigger loss

Swap in our first guess. The residuals grow, the squares grow, and the tower shoots up: MSE = 0.54. The loss tells us, in one number, that this line is worse.

Insight

Outliers get punished

One house is wildly overpriced. Its square dwarfs the rest: MSE = 0.80, while the mean absolute error (no squaring) is only 0.61. MSE is sensitive to outliers. MAE is more forgiving.

Choosing a loss is choosing what kind of mistake you care about most.

Real life

In real life: “Arriving in 25 minutes”

Delivery and ride apps predict arrival times. Every early or late arrival is an error. The loss rolls all those misses into one number, and the team’s job is to push that number down week after week.

Quick check: A model’s errors are 1 and 3. What is the MSE?

(1² + 3²) / 2 = (1 + 9) / 2 = 5.

Pseudocode

mean_squared_error(y, guess):
    misses = y − guess
    return average(misses²)      # square, then average

mean_absolute_error(y, guess):
    return average(|misses|)     # no squaring

loss = mean_squared_error(prices, line)    # one number

Key terms

loss
One number that says how wrong the model is. Lower is better.
mean squared error
A loss: square each miss, then take the average.

Build it: Gradient descent from scratch (30 min, runs in your browser)

See the project

Build it: House price predictor (30 min, runs in your browser)

See the project

In the news

Recent models and papers that build on this idea: