Deep Learning Loss Functions: Match MSE, Binary Cross-Entropy, and Categorical Cross-Entropy to the Task
Choose a loss from the meaning of the target, not from memory. Work through MSE, binary cross-entropy and categorical cross-entropy, then audit the shapes, encodings and reductions that can quietly train the wrong objective.
KnowledgeGate Team
Exam prep & CS education

A model can run and its loss can fall even when the target encoding, final-layer shape and loss function do not describe the same task. Some mismatches crash, but others broadcast tensors or reinterpret classes and return a plausible scalar for the wrong objective. The safe method is to decide from the task first, then audit the calculation: regression with MSE, one yes-or-no label with binary cross-entropy, and one-of-three classification with categorical cross-entropy. The checked answers will be MSE=0.375, mean BCE=0.2899, and CCE=0.3567 when the true-class probability is 0.7.
Deep learning loss functions begin with the meaning of the target
A loss function is the scalar training objective from targets and model outputs. It can produce per-example losses, then apply a batch mean or sum. Optimisation follows its gradient, while accuracy or mean absolute error may be reported without being trained.
Use this order: identify a continuous or categorical target; decide whether categorical labels are mutually exclusive or independent; choose the output and shape; match the target encoding; select the loss. Do not start from a memorised name.
The core matches are a continuous value with a linear output and MSE, one binary event with one sigmoid probability and BCE, and one class among K with a K-way softmax and categorical cross-entropy. Approaches to AI: Four Approaches and a Worked Example provides broader AI context.
Mean squared error fits a continuous regression target
For B scalar targets, mean squared error is MSE=(1/B) sum_i (y_i-yhat_i)^2. It suits a continuous quantity such as temperature, demand or travel time because errors have a numerical scale. Squaring removes the sign and penalises a large miss more strongly.
Take targets y=[3.0,-1.0,2.0,0.0] and predictions yhat=[2.5,-0.5,2.0,1.0]:
Residuals:
y-yhat=[0.5,-0.5,0.0,-1.0].Squared errors:
[0.25,0.25,0.00,1.00].Sum:
0.25+0.25+0.00+1.00=1.50.Mean:
MSE=1.50/4=0.375.
The matching tensors are predictions (B,1) from one linear output and floating-point targets (B,1). MSE is not a default for class IDs. Labels 0, 1 and 2 can name classes without establishing meaningful numerical distances.
Binary cross-entropy fits one yes-or-no target
For a predicted probability p and target y in {0,1}, binary cross-entropy is L=-[y ln(p)+(1-y)ln(1-p)], where ln is the natural logarithm. The selected probability is p when the event occurs and 1-p when it does not. Batch BCE here is the mean of the per-example losses.
In Probability Distributions for Machine Learning: Match Bernoulli, Binomial, Normal and Poisson to Data, the same 0.8 and 0.3 predictions begin a four-item Bernoulli likelihood. The two-item calculation below isolates both BCE label branches and their mean reduction; the distribution treatment owns the Bernoulli, Binomial, Poisson and Normal assumptions.
For y=[1,0] and probabilities p=[0.8,0.3]:
Positive example:
L1=-ln(0.8)=0.2231.Negative example:
L2=-ln(1-0.3)=-ln(0.7)=0.3567.Mean:
(0.2231+0.3567)/2=0.2899.
A wrong, confident positive prediction costs more. If y=1 and p=0.2, then L=-ln(0.2)=1.6094.
Use one binary raw logit (B,1) and floating targets (B,1) containing 0 or 1. If the library expects logits, use its stable BCE-with-logits loss without applying sigmoid first. If it expects probabilities, apply sigmoid exactly once.
Categorical cross-entropy fits one class among many
Suppose K=3 mutually exclusive classes are cat, dog and bird. Softmax converts three raw logits into probabilities summing to 1. For a one-hot target, categorical cross-entropy is L=-sum_k y_k ln(p_k), where ln is the natural logarithm. Only the true class has target value 1, so this is its negative log probability.
Let the true class be dog, with target y=[0,1,0] and predicted probabilities p=[0.1,0.7,0.2]:
L=-(0 ln(0.1)+1 ln(0.7)+0 ln(0.2))=-ln(0.7)=0.3567.
For the same target and confidently wrong probabilities p=[0.05,0.15,0.80], the loss is -ln(0.15)=1.8971.
Standard categorical cross-entropy takes one-hot targets (B,K). Sparse categorical cross-entropy takes one integer class index per example (B,). With zero-based indexing, sparse target 1 and one-hot target [0,1,0] both mean dog and must give the same loss for the same logits.

Loss-function decision table aligns outputs, labels and shapes
The number of output units does not choose the loss by itself. Label semantics decide whether outputs compete or remain independent.
Task | Example target | Model output | Target tensor | Loss |
|---|---|---|---|---|
scalar regression |
| one linear value, | float, | MSE |
binary event |
| one raw logit, | 0/1 float, | BCE with logits |
one of three classes |
| three raw logits, | integer index | categorical cross-entropy |
three independent tags |
| three independent logits, | three 0/1 values, | BCE per label |
If cat, dog and bird are one required choice, they compete through softmax and categorical cross-entropy. Tags such as indoor, person and night may all be true together, so each raw logit gets an independent sigmoid and BCE term. The Skill Development Courses collects the wider applied AI and skill-development courses if you want a broader study route.

Loss-function mistakes can train without crashing
Silent mismatches can return a reasonable-looking scalar for the wrong comparisons.
Mistake | What the model actually computes | Repair |
|---|---|---|
Predictions | Broadcasting may create | Assert equal intended shapes |
Sigmoid probabilities passed to BCE with logits | The function treats probabilities as raw logits | Supply raw logits |
Softmax plus BCE for one mutually exclusive class | Classes are treated as independent events | Use categorical cross-entropy |
One-hot labels with a sparse loss, or integer labels with a one-hot loss | The target violates the loss's encoding contract | Match the documented target form |
MSE on class IDs invents ordinal distance. With cat=0, dog=1 and bird=2, predicting cat for bird gets penalty (2-0)^2=4, while dog gets (2-1)^2=1. The names have no metric spacing. Manual ln(0) is unstable, so use a fused logits-based loss. Sum reduction scales with batch size, so declare it before comparing losses.
Run a four-step wiring test:
Inspect one batch's shapes and dtypes.
Calculate two or three examples by hand.
Test one correct high-confidence prediction and one wrong high-confidence prediction.
Overfit a tiny batch and confirm that the loss can approach its expected floor.
Exams and interviews test the task-to-loss match
Four prompts test the boundary. Tomorrow's temperature as one real number maps to MSE. Whether one transaction is fraudulent maps to BCE. Exactly one defect type from three classes maps to categorical cross-entropy. Any subset of [indoor,person,night] maps to BCE across three independent outputs.
For y=[1,0] and probabilities p=[0.8,0.3], select 0.8 for the positive item and 1-0.3=0.7 for the negative item. Their negative natural logarithms recover mean BCE 0.2899. Reject (32,1) predictions against (32,) targets even though both hold 32 values, because aligned axes determine comparisons.
Stable questions ask you to choose a loss, distinguish sparse from one-hot targets, separate mutually exclusive from multilabel outputs, calculate MSE or cross-entropy, spot a logits-probabilities mismatch, or audit broadcasting. Artificial Neural Networks MCQs: 10 Solved Questions provides adjacent retrieval practice.
Deep learning loss functions: the short version and next step
Keep this recall chain:
Continuous scalar target means linear output plus MSE.
One binary event means one raw logit plus BCE.
One class among
KmeansKlogits plus categorical cross-entropy.Multiple independent labels mean
Klogits plus BCE per label.Target shape and encoding must match the loss contract exactly.
Checked results: MSE=0.375, mean BCE=0.2899, and CCE=0.3567. Recover each before coding. AI & ML for Placements | Generative AI Placement Course is the fuller course route if you want the broader AI syllabus next. Build a two-example batch, print logits, targets and shapes, then verify the library loss by hand.
Keep learning
Python Functions Deep Dive: *args, **kwargs, the Mutable Default Trap and LEGB Scope
Trace the shared-list default, unpack extra arguments, and follow Python's LEGB lookup so familiar function snippets stop producing surprising output.
Probability Distributions for Machine Learning: Match Bernoulli, Binomial, Normal and Poisson to Data
Learn a reusable way to match binary outcomes, grouped successes, event counts and continuous residuals to a defensible probability model.
MongoDB Aggregation Pipeline: `$match` to `$group` with a Worked Example
Build one MongoDB aggregation pipeline step by step. Follow five fictional orders through filtering, array expansion, grouping, projection, and deterministic sorting.
Regular Expressions in Python: A Runnable Tutorial from First Match to Log Parser
Learn Python regex by running small examples, reading exact match spans and building a structured parser for three log records.





