Skip to main content
LearnMLAcademy
Advanced10 min read

Loss Functions: MSE, MAE and Cross-Entropy

Select optimal loss functions for deep regression, classification, and ranking, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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.

Where the loss function fits during trainingThe model produces a prediction. The loss function compares the prediction with the target. Backpropagation uses the loss to calculate gradients.Modelmakes a predictionPredictionwhat the model saidTargetthe correct answerLoss functionmeasures the mistakeBackpropagationfinds responsibilitygradients guide the next weight update
Figure 1: Loss is the bridge between making a prediction and learning from its error.

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.

1

Targets y = [3, −0.5, 2, 7] and predictions ŷ = [2.5, 0, 2, 8].

2

Errors y − ŷ = [0.5, −0.5, 0, −1].

3

Square the errors: [0.25, 0.25, 0, 1].

4

Average them: MSE = (0.25 + 0.25 + 0 + 1) ÷ 4 = 0.375.

0369-3-2-10123e = −1 → loss = 1prediction error eloss
The highlighted point is the value calculated in the example beside this graph.

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

1

Errors are [0.5, −0.5, 0, −1].

2

Absolute errors are [0.5, 0.5, 0, 1].

3

Add them: 0.5 + 0.5 + 0 + 1 = 2.

4

Average them: MAE = 2 ÷ 4 = 0.5.

Interpretation: the model misses the target by 0.5 units on average. MAE stays in the same unit as the target, so it is easy to explain.
0123-3-2-10123e = −1 → loss = 1prediction error eloss
The highlighted point is the value calculated in the example beside this graph.

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.

LossCalculationResultWhat happened?
MAE(1 + 1 + 10) / 34The outlier counts ten times as much as an error of 1.
MSE(1² + 1² + 10²) / 334The 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.

0123-3-2-10123e = 3 → loss = 2.5prediction error eloss
The highlighted point is the value calculated in the example beside this graph.

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

1

The email really is spam, so y = 1.

2

The model predicts an 80% spam probability, so p = 0.8.

3

BCE = −[1 × ln(0.8) + (1 − 1) × ln(0.2)].

4

The second term becomes zero, so BCE = −ln(0.8) = 0.223.

The prediction is correct and confident, so the loss is small. If p were 0.1, the loss would be −ln(0.1) = 2.303—a much stronger correction.
012340.20.40.60.81p = 0.8 → 0.223predicted probability for the true classloss
The highlighted point is the value calculated in the example beside this graph.

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

The model produces z. Sigmoid converts z to p. A developer or product policy chooses the decision threshold. The dataset supplies y, and the loss compares y with p.

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

1

The true class is cat, written as the one-hot target y = [1, 0, 0].

2

The model predicts p = [0.70, 0.20, 0.10].

3

CCE = −[1 ln(0.70) + 0 ln(0.20) + 0 ln(0.10)].

4

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

Cat (correct)70%
0.7
Dog20%
0.2
Rabbit10%
Only the 0.70 assigned to the correct class enters this one-hot cross-entropy calculation. The three probabilities must sum to 1.

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.

ProblemModel output supplied to the lossTarget exampleGood starting loss
Predict one numberUnrestricted value₹52.4 lakhMSE, MAE or Huber
Yes or noRaw logit for BCEWithLogitsLoss; sigmoid only when the API expects a probability0 or 1Binary cross-entropy
One class among manyRaw class logits for a fused cross-entropy lossClass 2 or [0,0,1]Sparse or categorical cross-entropy
Several independent labelsOne raw logit per label for a logits-aware BCE loss[1,0,1,0]Binary cross-entropy per label
Pixel mask with rare foregroundRaw pixel logits for logits-aware BCE/CEMaskBCE/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.

QuantityUsed forWhat it noticesExample
Cross-entropy lossGradient calculation and parameter updatesHow much probability reached the true class0.51 for p=0.60 when y=1
Accuracy metricHuman-readable evaluationWhether the final class decision was correctWith 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.

Regression loss functions
LossFormulaBest fitMain caution
MAEmean |y − ŷ|Interpretable error; outlier resistanceSharp point at zero
MSEmean (y − ŷ)²Make large valid mistakes expensiveOutliers can dominate
RMSE√MSEReport squared-error performance in target unitsKeeps MSE sensitivity
Huberquadratic near 0; linear beyond δSmooth training with some outliersThreshold δ must be selected
MAPEmean |(y − ŷ)/y| × 100Relative percentage errorBreaks or explodes near y = 0
Log-coshmean log(cosh(ŷ − y))Smooth compromise between MSE and MAELess immediately interpretable
Classification and structured-output losses
LossCore ideaBest fitMain caution
Binary cross-entropy−[y ln p + (1−y) ln(1−p)]Binary and multi-label classificationMatch logits/probability setting
Categorical cross-entropy−Σ y_c ln p_cExactly one class among manyUse the correct label encoding
Hingemax(0, 1 − ys)Margin-based classifiersScores are not probabilities
Focal lossdown-weights easy examplesSevere class imbalance and detectionExtra α and γ need tuning
KL divergenceΣ P ln(P/Q)Match one probability distribution to anotherNot symmetric; requires valid distributions
Dice loss1 − 2 overlap/(predicted + target)Segmentation with small foreground areasCan need smoothing for empty masks

Implement and Check the Calculations

losses.py
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

  1. Print one target and one raw model output. Confirm their shapes and meanings match.
  2. Confirm whether the library loss expects raw logits or already-converted probabilities.
  3. 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.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Loss Functions: MSE, MAE and Cross-Entropy"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5practical selection
Which regression loss is less sensitive to one extreme outlier?
Question 2 of 5numerical/formula
For errors 1 and 3, what is MSE?
Question 3 of 5practical selection
Which setup fits mutually exclusive classes represented by one class index?
Question 4 of 5conceptual
Why do framework cross-entropy functions often expect logits?
Question 5 of 5debugging/diagnostic
Training loss is finite but never changes. What should be checked first?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which regression loss is less sensitive to one extreme outlier?▼

Correct Answer: MAE

MAE grows linearly with error, while MSE squares the error and gives an outlier much greater influence.

2For errors 1 and 3, what is MSE?▼

Correct Answer: 5

MSE=(1²+3²)/2=(1+9)/2=5.

3Which setup fits mutually exclusive classes represented by one class index?▼

Correct Answer: Categorical cross-entropy with class logits

Categorical cross-entropy compares one correct class with a distribution across mutually exclusive classes.

4Why do framework cross-entropy functions often expect logits?▼

Correct Answer: They combine softmax and log operations stably

Combining the operations avoids unstable manual probability and logarithm calculations.

5Training loss is finite but never changes. What should be checked first?▼

Correct Answer: Loss-output-target compatibility and whether parameters receive updates

A mismatched objective or disconnected update path can make a mathematically computed loss useless for learning.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next