AI
Loss Function in Machine Learning, Explained
What a loss function is, how it guides training, the main types (MSE, MAE, Huber, cross-entropy, hinge) with worked numbers, and how to choose one.
A loss function is a formula that scores how wrong a model's prediction is. It compares the model's output with the correct answer and returns a single number: zero for a perfect prediction, larger for worse ones. During training, the model adjusts its weights to make that number as small as possible. In other words, the loss function defines what "good" means for the model.
Choosing a loss function is choosing what kind of mistakes you care about. Mean squared error punishes big errors heavily. Mean absolute error treats all errors in proportion. Cross-entropy punishes confident wrong answers in classification. Pick the wrong one and a model can score well in training while doing badly at the job you actually need.
This guide explains how a loss function in machine learning works, walks through the main types of loss functions with worked numbers, compares loss with cost and metrics, and shows how to choose one.
Loss Function at a Glance
| Loss function | Task | Formula (per example) | Behaviour |
|---|---|---|---|
| Mean squared error (MSE, L2) | Regression | (y − ŷ)² | Punishes large errors heavily; sensitive to outliers |
| Mean absolute error (MAE, L1) | Regression | absolute value of (y − ŷ) | Proportional to error size; robust to outliers |
| Huber | Regression | Squared for small errors, linear for large ones | A compromise between MSE and MAE |
| Binary cross-entropy (log loss) | Yes/no classification | −[y·ln(p) + (1 − y)·ln(1 − p)] | Heavy penalty for confident wrong answers |
| Categorical cross-entropy | Multi-class classification | −ln(probability of the correct class) | Standard for neural network classifiers and language models |
| Hinge | Classification (support vector machines) | max(0, 1 − y·score) | Zero once a prediction is correct by a margin |
| KL divergence | Comparing probability distributions | Σ p·ln(p/q) | Used in distillation and variational models |
Here y is the true value, ŷ the prediction and p the predicted probability.
How a Loss Function in Machine Learning Works
Training a model is a loop:
- Predict. The model makes predictions on a batch of training examples using its current weights.
- Score. The loss function compares each prediction with the correct answer and the results are averaged into one number for the batch.
- Find the direction. Backpropagation calculates the gradient: how much the loss would change if each weight moved slightly.
- Update. An optimiser, usually a variant of gradient descent such as Adam, nudges every weight a small step in the direction that lowers the loss.
- Repeat over many batches and passes through the data, until the loss stops improving on held-out data.
You can picture the loss as a landscape. Each possible setting of the weights is a location, and the height is the loss. Training walks downhill. The shape of the loss function shapes that landscape: how steep the slopes are, where the valleys sit and how strongly far-off points pull the model.
That's why loss functions need to be differentiable (or nearly so): gradient descent needs a slope to follow. It's also why accuracy itself is rarely used as a training loss. Accuracy jumps in steps as predictions flip between right and wrong, so it gives no useful slope. Models train on a smooth loss such as cross-entropy and are judged on accuracy afterwards. Our guide on how to train an AI model covers the rest of the training process.
Types of Loss Functions for Regression
When the model predicts a number, such as a price, temperature or demand, the common types of loss functions measure the distance between prediction and truth.
A worked example
A model predicts four values. Three are close; one is badly off:
| Example | True value | Prediction | Error | Squared error | Absolute error | Huber (δ = 1) |
|---|---|---|---|---|---|---|
| A | 3.0 | 2.5 | −0.5 | 0.25 | 0.5 | 0.125 |
| B | 5.0 | 5.0 | 0 | 0 | 0 | 0 |
| C | 2.0 | 3.0 | +1.0 | 1.00 | 1.0 | 0.500 |
| D | 8.0 | 4.0 | −4.0 | 16.00 | 4.0 | 3.500 |
| Mean | 4.31 (MSE) | 1.38 (MAE) | 1.03 |
Mean squared error (MSE)
MSE squares each error before averaging. In the example, the single bad prediction (D) contributes 16 of the 17.25 total, about 93% of the loss. Training with MSE will work hard to fix D, even at some cost to the others.
- Use it when: large errors are much worse than small ones, and your data has few true outliers.
- Watch out: a few bad labels or extreme values can dominate training.
- Related: root mean squared error (RMSE) is the square root of MSE (2.08 here), which puts it back in the original units and is common as a reporting metric.
Mean absolute error (MAE)
MAE averages the size of the errors without squaring them. D counts four times as much as an error of 1, not 16 times.
- Use it when: outliers are present and shouldn't dominate, or when every unit of error costs the same.
- Watch out: its slope doesn't shrink near zero, which can make the final stages of training less smooth. Minimising MAE pushes predictions towards the median, while MSE pushes towards the mean.
Huber loss
Huber loss is quadratic for errors smaller than a threshold δ and linear beyond it. Small errors are treated like MSE and large ones like MAE. In the example, D costs 3.5 instead of 16.
- Use it when: you want MSE's smooth behaviour near the target without letting outliers take over.
- Tune: δ sets where "small" ends.
Cross Entropy Loss for Classification
When the model predicts a category, it outputs a probability for each class. Cross entropy loss looks only at the probability the model gave to the correct class, and takes its negative logarithm:
| Probability given to the correct class | Cross-entropy loss (−ln p) |
|---|---|
| 0.99 | 0.01 |
| 0.90 | 0.11 |
| 0.70 | 0.36 |
| 0.50 | 0.69 |
| 0.10 | 2.30 |
| 0.01 | 4.61 |
The shape matters. Moving from 0.7 to 0.9 on a correct answer saves only 0.25. Being confidently wrong is punished hard: putting just 1% on the true class costs 4.61, more than six times the cost of a 50/50 guess. Cross-entropy therefore pushes models to be well calibrated, not just right.
- Binary cross-entropy (also called log loss) handles yes/no outputs, such as spam or not, with one probability per example.
- Categorical cross-entropy handles many classes, usually after a softmax layer that turns raw scores into probabilities that sum to 1.
Language models use the same idea. A large language model is trained with cross-entropy on the next token: at each position, the loss is −ln of the probability it assigned to the token that actually came next. The exponential of the average loss is perplexity, a common measure of how well a language model predicts text.
Hinge loss
Hinge loss, used by support vector machines, is zero when a prediction is on the right side of the decision boundary by at least a margin, and grows linearly otherwise. It cares about getting the margin right, not about probabilities.
Loss vs Cost Function
On loss vs cost function, the terms are often used interchangeably, but a common distinction is:
| Term | Usual meaning |
|---|---|
| Loss function | The error for one example |
| Cost function | The average loss over a batch or whole dataset, sometimes plus regularisation terms |
| Objective function | Whatever training optimises, minimised or maximised; a cost function is one kind |
| Metric | What humans use to judge the model (accuracy, F1, MAE, revenue); may differ from the training loss |
The last row matters most in practice. You can train with cross-entropy and judge with accuracy or F1. You can train with MSE and report MAE because it's easier to explain. The training loss should be something the optimiser can follow; the metric should reflect what you actually care about.
Regularisation: Adding to the Loss
The loss can include terms that don't measure prediction error at all. Regularisation adds a penalty for large weights to discourage overfitting:
- L2 regularisation (weight decay) adds a multiple of the sum of squared weights, which nudges all weights towards smaller values.
- L1 regularisation adds a multiple of the sum of absolute weights, which tends to push some weights exactly to zero, giving sparser models.
The total becomes: cost = average loss + λ × penalty, where λ controls how much simplicity matters compared with fit.
Loss Functions in Deep Learning and Beyond
Modern models often combine or specialise losses:
- Neural network classifiers use cross-entropy almost by default. See our guide to what a neural network is.
- Object detection combines a classification loss for "what is it" with a regression loss for "where is the box".
- Image generation with diffusion models trains with MSE between the predicted and actual noise at each step.
- Embedding and search models use contrastive losses that pull matching pairs together and push others apart.
- Knowledge distillation uses KL divergence so a small student model copies a large teacher's probability distribution.
- Imbalanced classification uses weighted cross-entropy or focal loss to give rare classes more weight.
How to Choose a Loss Function
| Situation | Good starting choice |
|---|---|
| Predicting a number, few outliers | MSE |
| Predicting a number, outliers or heavy tails | MAE or Huber |
| Yes/no classification | Binary cross-entropy |
| Several classes | Categorical cross-entropy |
| Rare positive class (fraud, disease) | Weighted cross-entropy or focal loss |
| Ranking or similarity search | Contrastive or ranking loss |
| Errors cost different amounts in each direction | A custom asymmetric loss |
Then check three things:
- Does lowering the loss improve the metric you care about? If validation loss falls but the business metric doesn't move, the loss is measuring the wrong thing.
- Are outliers or label errors dominating? If a handful of examples drive most of the loss, as D did in the example above, consider a robust loss.
- Is training stable? Very large or exploding loss values can point to a poor loss choice, bad scaling or a learning rate that's too high.
Reading Loss Curves
During training, plot the loss on the training data and on held-out validation data:
- Both falling: the model is learning.
- Training falling, validation rising: overfitting. Stop earlier, add regularisation or get more data.
- Both flat and high: underfitting. The model may be too simple, or the learning rate too low.
- Wild jumps: the learning rate may be too high, or the data contains problem examples.
The absolute loss value means little on its own. Compare it with a simple baseline, such as always predicting the average, to know whether the model has learned anything. Our explainer on what an AI model is shows how the loss fits into the wider picture of training and evaluation.
FAQ
What is a loss function in simple terms?
It's a score of how wrong a model's prediction is. Training adjusts the model's weights to make that score as small as possible.
Why is cross-entropy used instead of accuracy?
Accuracy changes in jumps as predictions flip between right and wrong, so it gives gradient descent no slope to follow. Cross-entropy changes smoothly with the predicted probability and also rewards good calibration.
Can a loss function be negative?
The standard ones (MSE, MAE, cross-entropy) are never negative. Some objectives, such as log-likelihoods that are maximised, can be negative, but they're usually flipped into a loss to minimise.
What is a good loss value?
There's no universal number. It depends on the loss type, the scale of the data and the task. Compare with a simple baseline and watch the trend on validation data.
Is the loss function the same as the error?
Close. The error is the difference between prediction and truth; the loss function turns that difference into the score training minimises, for example by squaring it.