Skip to content

Loss Function

A formula that turns a model's mistakes into one number. Training means making that number as small as possible.

Also cost function · objective function · error function

Fig. / How it works
LOSS: THE TOTAL AREA OF THE SQUARES
Domain 01
Foundations
Role · kind
TrainingConcept
Level
Beginner

It is the score in a game of darts, except lower is better. The further your darts land from the bullseye, the more points you lose.

Where it fits

Not shown: 4 more that build on it. See the full list below.

+All relationships as a list

See it on the full map

How it works

A model makes a prediction; reality gives the true answer. The loss measures how far apart they are. Average it over all training examples and you get one number that summarizes how badly the model is doing right now.

Two losses cover most cases:

  • Mean squared error (MSE) for numbers. Square each miss and average. Big misses dominate.
  • Cross-entropy (log loss) for classes. Look at the probability the model gave to the correct class. If it said 0.99, the loss is tiny; if it said 0.01, the loss is huge.

Because the loss is a smooth function of the model’s parameters, we can ask “which way should each knob turn to make it smaller?” That question is answered by gradient descent.

The math

Mean squared error over nn examples:

MSE=1n∑i=1n(yi−y^i)2\text{MSE} = \frac{1}{n}\sum_{i=1}^{n} (y_i - \hat{y}_i)^2

Binary cross-entropy, where p^i\hat{p}_i is the predicted probability of class 1:

BCE=−1n∑i=1n[yilog⁡p^i+(1−yi)log⁡(1−p^i)]\text{BCE} = -\frac{1}{n}\sum_{i=1}^{n} \Big[y_i \log \hat{p}_i + (1 - y_i)\log(1 - \hat{p}_i)\Big]

Everyday use cases

  • Case 01

    House prices

    Mean squared error punishes a 50,000 miss far more than ten 5,000 misses.

  • Case 02

    Spam filters

    Cross-entropy punishes a filter that is confidently wrong much more than one that is unsure.

Strengths, weaknesses and when to use it

Strengths

  • Gives training a single, precise goal.
  • Swapping the loss changes model behavior without changing the model.

Weaknesses

  • The loss you can optimize is often only a proxy for what you really care about (customer happiness, fairness).

When to use itAlways. Every trained model has one; the question is which.

Check yourself

  1. Q01

    What does a training algorithm try to do with the loss?

    Show answer

    B: Minimize it

  2. Q02

    Why is squared error sensitive to outliers?

    Show answer

    B: Squaring makes large errors much larger than small ones

Go deeper