Deep Learning · Beginner Lesson
Loss Functions: How a Neural Network Measures Its Mistakes
A neural network cannot improve from the vague message “that answer was wrong.” It needs a number that says how wrong the answer was. A loss function creates that number. This lesson calculates MSE, MAE and cross-entropy by hand, connects each calculation to a graph, and shows which loss belongs to each kind of problem.
What Is a Loss Function?
Imagine a model predicts that a house costs ₹48 lakh, while its actual price is ₹50 lakh. The prediction is not exact, but the difference can be measured. A loss function takes the prediction and the correct answer, compares them using a chosen rule, and returns one penalty number.
Prediction (ŷ)
The answer produced by the model.
Target (y)
The correct answer in the training data.
Loss (L)
A penalty: smaller normally means a better prediction.
During training, the network repeatedly changes its weights to make this penalty smaller. The loss therefore acts like both a marking rule and a learning signal. Change the rule, and you change which mistakes the network treats as important.
First Decide: Are You Predicting a Number or a Class?
There is no universally best loss function. The first decision comes from the kind of answer the model must produce.
Regression
Predict a continuous number
Examples: temperature, delivery time, electricity demand, or house price. MSE, MAE, RMSE and Huber loss measure the distance between two numbers.
Classification
Predict a category
Examples: spam/not spam or cat/dog/rabbit. Cross-entropy measures how much probability the model placed on the correct class.
Begin with One Visible Error
Suppose the actual delivery time is 10 minutes and the model predicts 13 minutes. The dataset supplies 10 as the target; the network produces 13. Subtracting compares them: prediction minus target is 13−10=3 minutes.
signed error
13 − 10 = +3
The plus sign says the prediction was too high.
absolute error
|3| = 3
Distance keeps the size and removes direction.
squared error
3² = 9
Squaring makes larger errors grow more strongly.
A dataset contains many predictions, so MAE and MSE average their per-example penalties. Averaging gives a summary that does not grow merely because the batch contains more examples.
Regression loss 1
Mean Squared Error (MSE)
MSE measures the average squared distance between predictions and targets. “Squared” means that every error is multiplied by itself. This removes negative signs and makes a large error grow much faster than a small one.
Formula
MSE = (1/n) Σᵢ₌₁ⁿ (yᵢ − ŷᵢ)²
n is the number of examples; yᵢ is the target for example i; ŷᵢ is its prediction; Σ means add all the values.
Worked example
A model predicts four values. We will keep the numbers small so every step can be checked.
Targets y = [3, −0.5, 2, 7] and predictions ŷ = [2.5, 0, 2, 8].
Errors y − ŷ = [0.5, −0.5, 0, −1].
Square the errors: [0.25, 0.25, 0, 1].
Average them: MSE = (0.25 + 0.25 + 0 + 1) ÷ 4 = 0.375.
Use MSE when
Large mistakes should receive much more attention and extreme values are genuine.
Be careful when
The data contains bad measurements or rare outliers; squaring can let them dominate.
Example
Forecasting electricity demand where a very large miss is costly.
Regression loss 2
Mean Absolute Error (MAE)
MAE measures the average size of the errors without caring whether a prediction was too high or too low. Absolute-value bars turn −3 and +3 into the same distance, 3. Unlike MSE, MAE does not square a large error.
Formula
MAE = (1/n) Σᵢ₌₁ⁿ |yᵢ − ŷᵢ|
The vertical bars mean absolute value: keep only the distance from zero. Every error contributes in direct proportion to its size.
The same four predictions
Errors are [0.5, −0.5, 0, −1].
Absolute errors are [0.5, 0.5, 0, 1].
Add them: 0.5 + 0.5 + 0 + 1 = 2.
Average them: MAE = 2 ÷ 4 = 0.5.
Use MAE when
You want an interpretable typical error and need less sensitivity to outliers.
Be careful when
Smooth optimization near zero is important; MAE has a sharp corner there.
Example
Predicting delivery time when occasional unusual delays should not control the whole model.
MSE and MAE React Differently to an Outlier
Suppose three predictions have errors [1, 1, 10]. The error of 10 is unusual. Watch what squaring does.
| Loss | Calculation | Result | What happened? |
|---|---|---|---|
| MAE | (1 + 1 + 10) / 3 | 4 | The outlier counts ten times as much as an error of 1. |
| MSE | (1² + 1² + 10²) / 3 | 34 | The outlier contributes 100, so it dominates the average. |
Neither behaviour is automatically right. If the value 10 is a serious but valid failure, MSE’s strong penalty may be useful. If it is sensor noise, MAE or Huber loss may be safer.
RMSE and Huber Loss: Two Useful Regression Alternatives
Root Mean Squared Error
RMSE puts MSE back into the target’s unit
Take the square root after calculating MSE. For the earlier example:
RMSE = √0.375 = 0.612
Use RMSE as an easy-to-read evaluation value when large errors matter. Optimizing RMSE or MSE leads to the same best parameters because square root is increasing.
Huber loss
Quadratic nearby, linear far away
For small errors Huber behaves like a smooth squared loss; for large errors it grows like MAE. With threshold δ = 1 and error e = 3:
L = δ(|e| − ½δ) = 1(3 − 0.5) = 2.5
Use it when most data is clean but some outliers should have limited influence.
Classification loss 1
Binary Cross-Entropy (BCE)
A binary classifier answers a two-choice question such as “spam or not spam.” Before reading its formula, compare three models on an email whose true label is spam, so y=1.
Model A
p = 0.9
loss = −ln(0.9) = 0.105
correct and confident
Model B
p = 0.6
loss = −ln(0.6) = 0.511
correct but uncertain
Model C
p = 0.1
loss = −ln(0.1) = 2.303
confidently wrong
The natural logarithm has a useful shape: as the probability assigned to the true answer approaches zero, −ln(p) rises sharply. Training therefore receives a much stronger correction for a confident wrong prediction than for a confident correct one.
Formula
BCE = −[y ln(p) + (1 − y) ln(1 − p)]
y is the target, either 0 or 1; p is the predicted probability of class 1; ln is the natural logarithm. Only the term belonging to the true label remains.
Worked example: spam email
The email really is spam, so y = 1.
The model predicts an 80% spam probability, so p = 0.8.
BCE = −[1 × ln(0.8) + (1 − 1) × ln(0.2)].
The second term becomes zero, so BCE = −ln(0.8) = 0.223.
Important implementation rule: if the network produces raw scores called logits, prefer a logits-aware library loss such as PyTorch BCEWithLogitsLoss or Keras BinaryCrossentropy(from_logits=True). It combines sigmoid and BCE more safely.
Raw score, probability, decision and loss are four different quantities
logit
z = 1.386
raw model score
sigmoid
p = 0.80
probability of class 1
threshold
0.80 ≥ 0.50
predict class 1
loss when y=1
0.223
training penalty
Classification loss 2
Categorical Cross-Entropy
Use categorical cross-entropy when exactly one class is correct among several choices. Softmax turns the model’s raw class scores into probabilities that add to 1. The loss then focuses on the probability assigned to the correct class.
Formula
CCE = −Σc y_c ln(p_c)
c identifies a class; y_c is 1 for the correct class and 0 for the others; p_c is the predicted probability for that class.
Worked example: cat, dog or rabbit
The true class is cat, written as the one-hot target y = [1, 0, 0].
The model predicts p = [0.70, 0.20, 0.10].
CCE = −[1 ln(0.70) + 0 ln(0.20) + 0 ln(0.10)].
CCE = −ln(0.70) = 0.357.
Sparse categorical cross-entropy performs the same mathematical job, but the target is stored as an integer such as 0 for cat instead of [1, 0, 0]. Choose the API that matches how your labels are encoded.
Model probabilities
Concept versus library input: conceptually, multiclass classification follows logits → softmax probabilities → cross-entropy. In PyTorch, nn.CrossEntropyLoss expects the raw logits and internally combines log-softmax with negative log-likelihood for numerical stability. Do not manually apply softmax before that fused loss. Apply softmax later when you need probabilities for interpretation or inference.
Match the Loss, Output Layer and Target
These three pieces form one contract. A mismatch can produce meaningless learning even when the code runs.
| Problem | Model output supplied to the loss | Target example | Good starting loss |
|---|---|---|---|
| Predict one number | Unrestricted value | ₹52.4 lakh | MSE, MAE or Huber |
| Yes or no | Raw logit for BCEWithLogitsLoss; sigmoid only when the API expects a probability | 0 or 1 | Binary cross-entropy |
| One class among many | Raw class logits for a fused cross-entropy loss | Class 2 or [0,0,1] | Sparse or categorical cross-entropy |
| Several independent labels | One raw logit per label for a logits-aware BCE loss | [1,0,1,0] | Binary cross-entropy per label |
| Pixel mask with rare foreground | Raw pixel logits for logits-aware BCE/CE | Mask | BCE/CE plus Dice or focal loss |
For a person reading predictions, convert logits to probabilities with sigmoid or softmax after the model produces them. For training, follow the selected loss API: fused logits-aware losses should receive logits directly.
Loss and Metric Answer Different Questions
A loss is the numerical objective differentiated during training. A metric is a value people use to interpret performance. They can disagree because they summarize predictions differently.
| Quantity | Used for | What it notices | Example |
|---|---|---|---|
| Cross-entropy loss | Gradient calculation and parameter updates | How much probability reached the true class | 0.51 for p=0.60 when y=1 |
| Accuracy metric | Human-readable evaluation | Whether the final class decision was correct | With threshold 0.50, p=0.60 is correct |
Two correct predictions can have the same accuracy but different cross-entropy because 0.99 and 0.60 express different confidence. Conversely, a lower training loss does not guarantee better real-world performance; always inspect task-appropriate validation metrics and failure cases.
A Practical Choice Guide
Typical numerical prediction
Start with MSE and report MAE too. MSE gives smooth training; MAE tells people the typical error size.
Regression with suspicious outliers
Try MAE or Huber. First investigate whether the outliers are valid rather than hiding a data-quality problem.
Binary or independent multi-label task
Use binary cross-entropy. Use one sigmoid for binary output or one sigmoid for each independent label.
Exactly one class among many
Use categorical cross-entropy for one-hot labels or sparse categorical cross-entropy for integer labels.
Severely imbalanced classification
Try class weights or focal loss, then evaluate precision and recall. Accuracy alone can be deceptive.
Image segmentation
Cross-entropy handles pixels; Dice loss directly rewards overlap. A combination is common when the foreground is small.
Common Loss Functions at a Glance
This original reference chart groups the functions by the kind of mistake they measure. Use it after understanding the detailed examples above—not as a substitute for them.
| Loss | Formula | Best fit | Main caution |
|---|---|---|---|
| MAE | mean |y − ŷ| | Interpretable error; outlier resistance | Sharp point at zero |
| MSE | mean (y − ŷ)² | Make large valid mistakes expensive | Outliers can dominate |
| RMSE | √MSE | Report squared-error performance in target units | Keeps MSE sensitivity |
| Huber | quadratic near 0; linear beyond δ | Smooth training with some outliers | Threshold δ must be selected |
| MAPE | mean |(y − ŷ)/y| × 100 | Relative percentage error | Breaks or explodes near y = 0 |
| Log-cosh | mean log(cosh(ŷ − y)) | Smooth compromise between MSE and MAE | Less immediately interpretable |
| Loss | Core idea | Best fit | Main caution |
|---|---|---|---|
| Binary cross-entropy | −[y ln p + (1−y) ln(1−p)] | Binary and multi-label classification | Match logits/probability setting |
| Categorical cross-entropy | −Σ y_c ln p_c | Exactly one class among many | Use the correct label encoding |
| Hinge | max(0, 1 − ys) | Margin-based classifiers | Scores are not probabilities |
| Focal loss | down-weights easy examples | Severe class imbalance and detection | Extra α and γ need tuning |
| KL divergence | Σ P ln(P/Q) | Match one probability distribution to another | Not symmetric; requires valid distributions |
| Dice loss | 1 − 2 overlap/(predicted + target) | Segmentation with small foreground areas | Can need smoothing for empty masks |
Implement and Check the Calculations
import numpy as np
y = np.array([3.0, -0.5, 2.0, 7.0])
y_hat = np.array([2.5, 0.0, 2.0, 8.0])
mse = np.mean((y - y_hat) ** 2)
mae = np.mean(np.abs(y - y_hat))
rmse = np.sqrt(mse)
true_label = 1
p = 0.8
bce = -(true_label * np.log(p)
+ (1 - true_label) * np.log(1 - p))
print(mse, mae, rmse, bce)
# 0.375 0.5 0.612372... 0.223143...Three checks before training
- Print one target and one raw model output. Confirm their shapes and meanings match.
- Confirm whether the library loss expects raw logits or already-converted probabilities.
- Report a human-readable metric beside the training loss; a small loss number has no universal unit.
Key takeaways
Loss defines the mistake
Training follows the penalty you choose, so the loss must match the real task.
MSE emphasizes large errors
Squaring creates a smooth curve but makes outliers influential.
MAE measures direct distance
It is easy to interpret and less dominated by extreme values.
Cross-entropy evaluates probabilities
It strongly penalizes confident wrong classification and must match the target encoding.