Foundations

Loss Functions as the Definition of What a Model Should Get Right

See how squared, absolute, quantile, log and hinge losses each ask a model a different question, with worked numbers for each.

Key takeaways

  • The training objective is usually the average loss over examples, often with an added penalty on the parameters.
  • Squared loss aims at the conditional mean, absolute loss at the conditional median, and quantile loss at a chosen quantile.
  • Log loss rewards honest probabilities and punishes confident wrong answers very heavily.
  • Classification training often uses a smooth stand-in because the plain count of errors gives gradient methods nothing to follow.
  • The metric you report may differ from the loss you train on, and you should check that lowering one improves the other.

A loss function assigns a number to each prediction saying how bad it was, given the true answer. Training adjusts the model to make the average of that number small. So the loss is your working definition of "good", and the model pursues it whether or not it matches what you meant.

Change the loss and you change what the ideal prediction is, even with identical data and an identical model. Picking one is a statement about which mistakes cost what.

One number per prediction

Write the true value as y and the prediction as ŷ. For one example the loss is L(y, ŷ). Over n training examples, the quantity most algorithms minimize is the average:

J(θ) = (1/n) · ∑ L(yᵢ, ŷᵢ)      where ŷᵢ = f(xᵢ; θ)

Here θ stands for the model's parameters. A penalty term such as λ times the sum of squared weights is often added to discourage extreme settings, with λ controlling its strength. This recipe is called empirical risk minimization when the average over the training data stands in for the average over all future cases.

Squared and absolute loss disagree

Suppose five similar cases have outcomes 2, 3, 4, 5 and 36, and your model must give them all one prediction.

Squared loss is (y − ŷ)². The constant that minimizes the total is the mean: 50 / 5 = 10. Absolute loss is |y − ŷ|. The constant that minimizes that total is the median: 4.

Prediction Sum of squared errors Sum of absolute errors
10 (mean) 850 52
4 (median) 1,030 36

Each choice wins under its own loss. Squaring makes the error on the value 36 dominate, so the fit moves toward it. Absolute error charges each unit of miss equally, so one extreme value has limited pull.

Neither is correct in the abstract. If you are budgeting a total, the mean matters, because the mean times the count gives the total. If you want a typical case, the median serves better. If the 36 is a recording error, you should fix the data and not expect a loss function to rescue you.

Huber loss blends the two. For a residual r = y − ŷ it equals ½r² when |r| ≤ δ and δ(|r| − ½δ) beyond that, so it is smooth near zero and grows only linearly for large misses.

Losses with a built-in preference

Sometimes predicting too low hurts more than predicting too high. A shop that runs out of stock loses sales; one with a little extra pays storage. Quantile loss, also called pinball loss, encodes this with a level τ between 0 and 1:

if y ≥ ŷ:  L = τ · (y − ŷ)           prediction too low
if y < ŷ:  L = (1 − τ) · (ŷ − y)     prediction too high

With τ = 0.9, falling 10 units short costs 9, while overshooting by 10 units costs 1. The best constant under this loss is a 90th percentile of the outcomes: a value that the truth exceeds only about one time in ten. At τ = 0.5 you recover the median, with the loss scaled by one half.

Which question does each regression loss ask?
Squared Targets the mean Large misses dominate Smooth everywhere Absolute Targets the median Each unit of miss counts alike Kink at zero Quantile Targets a chosen quantile Under and over cost differently Useful for buffers and ranges Squared Targets the mean Large misses dominate Smooth everywhere Absolute Targets the median Each unit of miss counts alike Kink at zero Quantile Targets a chosen quantile Under and over cost differently Useful for buffers and ranges

Log loss and honest probabilities

For binary classification, let the model output p, its estimated probability that y = 1. Log loss, or binary cross-entropy, is −ln p when y = 1 and −ln(1 − p) when y = 0, using the natural logarithm.

When the true label is 1:

Predicted p Loss
0.9 0.105
0.5 0.693
0.1 2.303
0.01 4.605

The loss grows without limit as p approaches 0 for something that happened. The expected log loss is minimized by reporting the true probability, which makes it a proper scoring rule. This does not guarantee that a trained network's outputs are trustworthy: a flexible model can still be overconfident, so check calibration on held-out data. The connection to likelihood is worked through in deriving cross-entropy loss.

Several classes and softmax

With K classes, a model usually produces one raw score per class and passes them through the softmax function, which exponentiates each score and divides by the total so the results are positive and sum to 1. Cross-entropy loss is then −ln of the value assigned to the true class.

Say three classes receive values 0.7, 0.2 and 0.1. If the first class is correct, the loss is −ln 0.7, about 0.357. If the third is correct, it is −ln 0.1, about 2.303.

Only the true class's value appears in the formula, yet the others matter, because raising any of them lowers it. As with the binary case, these outputs look like probabilities without being guaranteed to behave like them.

For tasks where each example can carry several tags at once, softmax is the wrong shape, since it forces the classes to compete. Use a separate sigmoid and binary log loss for each tag.

Why classifiers train on stand-ins

What you often care about is the zero-one loss: 1 for a wrong label, 0 for a right one. Its average is the error rate. As a training target it is awkward. Nudging a parameter usually changes no labels, so the gradient is zero almost everywhere, and where a label flips the loss jumps.

A surrogate loss is a better-behaved substitute that still falls as classifications improve. Log loss is one. Another is the hinge loss used by support vector machines. With the label written as y ∈ {−1, +1} and the model's raw score as s, it is max(0, 1 − y·s). A correct example with y·s at least 1 costs nothing. A correct but hesitant one, with y·s = 0.4, costs 0.6. A wrong one with y·s = −2 costs 3.

Hinge loss cares about a margin of safety and ignores examples that are comfortably right. Its raw scores are not probabilities.

What the gradient feels

Gradient-based training only sees the loss through its slope, which shows how strongly each example pulls on the model.

Loss Slope with respect to the prediction Pull from a very large miss
Squared, (ŷ − y)² 2(ŷ − y) Grows with the miss
Absolute +1 or −1 Same as a small miss
Huber with threshold δ ŷ − y inside, ±δ outside Capped at δ

This explains behavior you will see in practice. With squared loss, a handful of corrupted targets can dominate each update. With absolute loss, the pull does not fade as you approach the target, so the optimizer may jitter around it unless the step size shrinks.

For log loss on a sigmoid output, the slope with respect to the raw score is simply p − y. A confident wrong answer, with p near 1 and y = 0, gives a slope near 1, so it still gets corrected firmly. Pairing a sigmoid with squared loss instead multiplies the slope by p(1 − p), which is nearly zero for that same confident mistake, and learning can stall there.

When mistakes have unequal prices

In fraud screening, missing a fraud and bothering an honest customer are different harms. You can express this in two places.

You can weight the loss, multiplying the terms for one class by a larger factor during training. Or you can train for good probabilities and then choose a decision threshold. If a false alarm costs C_FP, a miss costs C_FN, correct decisions cost nothing and the probabilities are accurate, you should flag a case when p exceeds C_FP / (C_FP + C_FN). With costs of 1 and 9, that threshold is 0.1.

The second route keeps the model reusable when prices change. Either way, someone has to state the costs, and that conversation belongs to the people who bear them. Cost-sensitive classification goes further.

Training loss and reporting metric

A metric is the score you use to judge the finished model, such as accuracy, F1 or revenue at stake. It need not be differentiable. The loss has to be something your optimizer can work with.

Check the link between them rather than assuming it. Validation log loss can rise while accuracy holds steady, which suggests growing overconfidence on the cases that are wrong. A regression model with better squared error can be worse on percentage error if small targets matter to you.

Practical habits help:

  • Write the loss down in words: what a prediction of this kind costs when it misses in each direction.
  • Look at the examples with the largest losses, which are often data errors.
  • Keep the sign and averaging conventions straight when comparing libraries, since some average over examples and others sum.
  • Report the baseline's loss next to the model's, so the number has a scale.

If no standard loss captures the goal, you can write your own, provided you test its gradient and confirm that it cannot be gamed by a degenerate prediction. The model will find a shortcut if the loss allows one.

Common questions

Can a loss be negative?

The standard losses here cannot. Some objectives, such as negative log-density for continuous variables, can go below zero. What matters for optimization is which direction counts as better.

Is a lower loss always a better model?

On the same data and with the same loss definition, lower held-out loss is better by that definition. Whether it is better for your users depends on how well the definition matched their costs.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 42 articles in Foundations →

Latest news on this topic