TL;DR
A loss function is a rule that takes one prediction and the true answer and returns a single non-negative number. A small number means the model was close, and a large number means it was far off. Training means adjusting the model's settings until the average loss over the data is as small as it can get.
Picking a loss is picking what "wrong" means. Choosing the loss is a modelling decision, not a formality.
Where you'll see it: in the objective that a neural network minimises during training, in the least-squares line fitted to a scatter plot, and in the classification loss behind language models.
Intuition
A score for being wrong
Suppose you guess how many minutes a bus will take. It arrives in 12 minutes and you guessed 9, so you were three minutes off. Next time you guess 15 and it arrives in 12, so you were again three off. Both guesses are equally wrong in minutes, but a loss function is the rule you choose to turn "off by three" into a number. You could count the minutes, square them, or only count the big misses. Each choice says something different about how bad an error is.
A model is a machine with knobs, called weights or parameters. Turning a knob changes the predictions, but a person cannot tell by looking whether the new knobs are better. A loss function gives one number that can be compared between any two settings. Training is then a simple instruction: turn the knobs in whichever direction lowers that number. The method for deciding which direction is gradient descent, which uses the Gradient of the loss.
flowchart LR A["Input x"] --> B["Model with weights"] B --> C["Prediction"] C --> D["Loss: how wrong"] E["True answer"] --> D D --> F["Gradient step lowers the loss"] F --> B
The shape of the loss curve decides how the model reacts to errors. The plot below shows two common choices as a function of the error, the truth minus the prediction.
- squared error
- absolute error
The math
Definition
A loss function is a function that takes the true value and a prediction and returns a non-negative real number. For the losses below, it is zero when the prediction is exact.
Here is the answer we want, and (read "y hat") is what the model says. The loss is always at least zero, so it can be read as a cost of being wrong.
From one example to the whole dataset
A model has parameters (the knobs). Given training pairs , the average loss, usually called the cost or the objective, is
Training searches for the settings that make small:
The average is an expected value over the data: the loss of each example, weighted equally. This is why measures how well the model does on average, not on one lucky or unlucky example.
Three common losses
Write the residual as , the signed error.
- Squared error: . Averaged over the data this is the mean squared error. It is used for predicting numbers.
- Absolute error: . It treats an error of 2 as exactly twice as bad as an error of 1.
- Cross-entropy: for a classifier that outputs a probability for the true class , . It is the cross-entropy loss and is applied to the output of a Softmax.
The derivatives differ too, and this matters for training. The derivative of squared error with respect to the prediction is , so it pushes harder the bigger the error and weakly when the error is small. The derivative of absolute error is , so it pushes with the same strength no matter how close the prediction already is.
Where squared error comes from
Suppose the targets are the true function plus Gaussian noise:
Then the probability density of one observation is , the Gaussian density centred on the prediction. Taking the negative logarithm gives
The second term does not depend on , and is a constant too. So minimising the summed squared error is the same as maximum likelihood under Gaussian noise. This is a strong reason to use squared error, but it is a reason tied to a noise assumption. It is not a law that squared error is always right.
Worked examples
The true value is and the model predicts .
- Residual: .
- Squared loss: .
- Absolute loss: .
Now the model overshoots and predicts .
- Residual: .
- Squared loss: . Absolute loss: .
Interpretation: squared error says the first mistake, off by 3, is more than twice as bad as the second, off by 2 (9 against 4). Absolute error says it is only one and a half times as bad (3 against 2). Squared error is the harsher judge of big misses.
Four houses have true prices, in units of 100,000, of . The model predicts .
- Residuals : .
- Squared losses: . Sum , mean .
- Absolute losses: . Sum , mean .
- The last house contributes of the squared total , about 76%. Under absolute error it contributes of , about 57%.
Interpretation: the squared loss is dominated by the single house that was badly wrong. A model trained on it will spend most of its effort fixing that one point. The absolute loss spreads its attention more evenly.
A photo shows a cat, so the true class is cat. Cross-entropy is , where is the probability the model gave to cat.
- The model says . Loss: .
- The model says . Loss: .
Interpretation: the loss drops as the model gives more probability to the right answer. The confident wrong answer costs about ten times as much as the mostly right one. The loss pushes hardest on the cases the model gets most wrong.
Tradeoffs and failure modes
Every loss makes a claim about what counts as a good fit. Use the one that matches your data and your goal.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Some targets are wild outliers, such as a sensor that logs 9999 by mistake | Squared error lets one bad point drag the whole fit | Absolute error, or the Huber loss, which is squared near zero and linear far away |
| Predicting a class from a probability output | Squared error on probabilities learns slowly when the model is confidently wrong | Cross-entropy |
| You care about the fraction of correct answers | Accuracy is flat: small changes in the weights often change no prediction, so there is no slope to follow | Optimise cross-entropy as a smooth stand-in for accuracy |
| The noise clearly is not constant, or not symmetric | Squared error assumes the same spread everywhere | Transform the target, or use a loss matched to the noise |
Two failure modes come up over and over. First, the loss is measured on training data, so a low training loss says little until you check held-out data. A model can drive its training loss to near zero by memorising, and the validation loss then rises. Second, optimising a loss is not the same as achieving the goal. A loss can go down while the metric you actually report stays put, so watch both.
History
Fitting a line by minimising errors is much older than machine learning. Least squares was published by Adrien-Marie Legendre in 1805. Carl Friedrich Gauss said he had used it since 1795 and published it in 1809, and he connected it to the normal law of errors. In the 1750s Roger Boscovich was already fitting lines by minimising absolute errors, so both losses are old.
The idea of a loss as the thing a decision should minimise was formalised in statistics by Abraham Wald in 1950, in his work on statistical decision functions. Peter Huber's 1964 paper on robust estimation gave a practical loss that resists outliers, which is still used. Cross-entropy comes from information theory, where Claude Shannon defined entropy in 1948. It became the standard classification loss as logistic regression and then deep neural networks were trained by gradient descent. The phrase "loss function" is now used across machine learning, and "cost" and "objective" mean much the same thing.
Check yourself
QuestionIn one sentence, what does a loss function output for a single prediction, and which direction is better?Show answer
It outputs a single non-negative number that measures how wrong the prediction is for that example. Lower is better: zero means a perfect prediction for the common losses, and larger values mean bigger mistakes.
QuestionThe true value is 5 and the prediction is 2. What are the squared loss and the absolute loss?Show answer
The residual is . The squared loss is and the absolute loss is .
QuestionWhy does the average squared loss react more to one very large error than the average absolute loss does?Show answer
The squared loss grows with the square of the error, so an error of 10 costs 100 while an error of 1 costs 1. The absolute loss grows only linearly, so the same error of 10 costs 10 against 1. A single large error therefore dominates the squared average much more, and the fit bends toward it.
QuestionA classifier gives the true class probability 0.5. What is its cross-entropy loss, and what would it be if the probability were 0.9?Show answer
The loss is . At probability 0.9 it is . More probability on the right answer means a smaller loss.
QuestionYou are predicting delivery times, and a logging bug has recorded a few deliveries as 500 hours. Which loss would you choose and why?Show answer
Use absolute error or the Huber loss. Squared error would let those few corrupted values pull the fitted model far from the typical delivery, because their squared errors are enormous. Absolute error gives each bad point only a linear penalty, so the fit stays close to the typical case.