Deep LearningLoss Functions and Classification

How do binary cross-entropy and categorical cross-entropy differ in neural-network classification?

Question 303 of 314 · Updated

On this page

Binary cross-entropy (BCE) and categorical cross-entropy (CCE) are both classification losses derived from the likelihood of the observed labels. The important difference is not simply the number of classes. It is the assumption each loss makes about how labels relate to one another.

  • Binary cross-entropy treats each output as a separate yes/no decision. It is appropriate for binary classification and, especially, multi-label classification where several labels can be true at the same time.
  • Categorical cross-entropy treats the output as one probability distribution over mutually exclusive classes. It is appropriate for single-label multiclass classification, where exactly one class is correct.

Choosing the wrong loss can make the model learn the wrong probability structure even when the training code runs without an error.

1. Start with the label structure#

Imagine a model classifying photographs.

Case A: One animal per photograph

Each photograph contains exactly one of: cat, dog, or horse. The labels are mutually exclusive. If the photograph is a cat, dog and horse must be false.

This is a categorical classification problem. The model should distribute a total probability of 1 across the three classes. Categorical cross-entropy is the natural choice.

Case B: Several objects can appear together

A photograph can contain a cat, a dog, both, or neither. The labels are not mutually exclusive. A cat label being true does not make the dog label false.

This is a multi-label classification problem. Each class needs its own yes/no probability, so binary cross-entropy is the natural choice.

The decision rule is therefore:

> Ask whether the classes compete for one mutually exclusive outcome, or whether each label can independently be present.

Do not choose the loss just by counting the output neurons.

2. Binary cross-entropy (BCE)#

BCE measures the error of a binary probability prediction. For a target (y in {0,1}) and predicted probability (p), its per-example loss is:

[ L_{BCE}=-[ylog(p)+(1-y)log(1-p)] ]

The model applies a sigmoid function to each logit:

LaTeX

If the true label is 1, the loss penalizes a low predicted probability. If the true label is 0, it penalizes a high predicted probability.

A small numerical example#

Suppose an email classifier predicts a 90% probability that an email is spam.

  • If the true label is spam (1), the loss is (-log(0.9)approx0.105).
  • If the true label is not spam (0), the loss is (-log(0.1)approx2.303).

The same prediction is rewarded when it is correct and strongly penalized when it is confidently wrong.

BCE for multiple independent labels#

For a multi-label task with (C) labels, BCE is applied independently to each label:

LaTeX

For example, an image may have targets:

[ y=[1,1,0] ]

meaning cat = present, dog = present, horse = absent. Each output gets its own sigmoid probability. The probabilities do not need to sum to 1. It is valid for both cat and dog to have high probabilities.

In practice, the loss reduction matters. A framework may average over all label elements, sum them, or return the unreduced per-element losses. When comparing experiments, make sure the reduction convention is the same.

3. Categorical cross-entropy (CCE)#

CCE measures the error of a probability distribution over (C) mutually exclusive classes. With a one-hot target vector (y) and predicted class probabilities (p):

[ L_{CCE}=-sum_{c=1}^{C}y_clog() ]

The model normally produces one logit per class and applies softmax:

LaTeX

Softmax makes the class probabilities sum to 1. Increasing one class probability necessarily reduces the probability mass available to the others.

For a one-hot target, only the log probability of the correct class contributes directly to the loss:

[ L_{CCE}=-log(p_{ ext{correct}}) ]

A numerical example#

A three-class model predicts:

[ p=[0.70,0.20,0.10] ]

If the true class is the first class, then:

[ L_{CCE}=-log(0.70)approx0.357 ]

If the model instead predicts only 10% probability for the correct class, its loss becomes (-log(0.10)approx2.303).

Categorical cross-entropy encourages the model to assign probability mass to the correct class while competing classes share the remaining probability mass.

Sparse categorical targets#

A one-hot vector is not always required. For a sample whose class index is 2, a framework can accept the integer class index directly. This is commonly called sparse categorical cross-entropy or class-index cross-entropy.

For example, with 1,000 classes, storing one integer per sample can be more convenient than storing a 1,000-element one-hot vector. The underlying task and softmax probability model are still categorical.

4. Side-by-side comparison#

DimensionBinary cross-entropyCategorical cross-entropy
Label assumptionIndependent binary labelsMutually exclusive classes
Typical taskBinary or multi-label classificationSingle-label multiclass classification
Output activationSigmoid per outputSoftmax across classes
Probability constraintEach probability is independent; values need not sum to 1All class probabilities sum to 1
Typical target0/1 for each outputClass index or one-hot/probability distribution
Output unitsOne for binary; often one per label for multi-labelUsually one logit per class
Main questionIs each label present?Which one class is correct?
PyTorch APIBCEWithLogitsLossCrossEntropyLoss

There is an important nuance: binary classification can be implemented with either one output and BCE or two class logits and categorical cross-entropy. These are two valid parameterizations of a two-outcome problem. They are not interchangeable with multi-label classification, where several labels may be true simultaneously.

5. How to choose the loss in real projects#

Use BCE when:

  • The task has two outcomes and you use one output logit.
  • A sample can belong to multiple classes simultaneously.
  • Labels are independent presence/absence decisions, such as image tags, product attributes, or several document topics.
  • You need class-specific positive weighting for imbalanced multi-label data.

Use categorical cross-entropy when:

  • Each sample has exactly one correct class from a set of alternatives.
  • The model should express a normalized distribution across those alternatives.
  • You are doing multiclass image classification, intent classification with one intent, or selecting one category from a taxonomy.
  • Your labels are class indices or valid class-probability distributions.

A practical decision tree#

  1. Can two or more labels be true for the same sample?
  • Yes: use independent sigmoid outputs with BCE, unless the task has additional structured constraints.
  • No: continue.
  1. Is the task a single choice among two classes?
  • A single logit with BCE is a common compact implementation.
  • Two logits with softmax and categorical cross-entropy is also valid.
  1. Is the task a single choice among three or more classes?
  • Use one logit per class with softmax-style categorical cross-entropy.

If labels have hierarchy, dependencies, or structured constraints, plain BCE may not capture those relationships. Consider whether the task needs a structured prediction objective rather than assuming the labels are independent.

6. PyTorch implementation#

Binary or multi-label classification#

Use BCEWithLogitsLoss and pass raw logits. It combines sigmoid and binary cross-entropy in a numerically stable operation.

PYTHON
import torch import torch.nn as nn # Multi-label batch: 2 samples, 3 independent labels logits = torch.tensor([ [2.0, 1.0, -1.0], [-0.5, 2.5, 0.2] ]) targets = torch.tensor([ [1.0, 1.0, 0.0], [0.0, 1.0, 1.0] ]) criterion = nn.BCEWithLogitsLoss() loss = criterion(logits, targets) print(loss.item())

The logits and targets have the same shape. Targets are floating-point values in the range 0 to 1. For ordinary hard labels, they are usually 0 or 1.

For imbalanced labels, pos_weight can increase the contribution of positive examples for a particular class. If one label has 100 positive examples and 300 negative examples, a starting positive weight of 3 may be reasonable. It is not a universal optimum: validate precision, recall, calibration, and the deployment decision threshold.

Single-label multiclass classification#

Use CrossEntropyLoss and pass raw logits, not probabilities that have already gone through softmax.

PYTHON
import torch import torch.nn as nn # 2 samples, 3 mutually exclusive classes logits = torch.tensor([ [2.0, 1.0, 0.1], [0.2, 0.3, 2.0] ]) # Correct class index for each sample targets = torch.tensor([0, 2]) criterion = nn.CrossEntropyLoss() loss = criterion(logits, targets) print(loss.item())

The logits have shape [batch_size, num_classes]; class-index targets have shape [batch_size] and integer type. PyTorch also supports probability-distribution targets with the same shape as the logits, but the target rows must be valid distributions.

A common implementation mistake#

Do not write:

PYTHON
probabilities = torch.softmax(logits, dim=1) loss = nn.CrossEntropyLoss()(probabilities, targets)

PyTorch's CrossEntropyLoss expects unnormalized logits and performs the log-softmax operation internally. Passing already-softmaxed probabilities changes the computation and can harm numerical behavior.

Similarly, prefer BCEWithLogitsLoss over applying sigmoid manually and then using BCELoss when training from logits. The combined operation is more numerically stable.

7. What about two-class classification?#

Suppose a model decides whether a transaction is fraudulent.

Option 1 — one logit with BCE

  • Output: one logit (z).
  • Apply sigmoid to obtain the fraud probability.
  • Target: 0 or 1.
  • Loss: BCE.

Option 2 — two logits with categorical cross-entropy

  • Output: two logits, one for legitimate and one for fraudulent.
  • Apply softmax to obtain two probabilities.
  • Target: class index 0 or 1.
  • Loss: categorical cross-entropy.

Both represent a two-outcome decision. With compatible parameterization, their probability models can express the same binary distribution. Choose one implementation and keep the output shape, target encoding, activation, and loss consistent.

Do not create two independent sigmoid outputs for a task where exactly one of the two classes must be true unless you have a deliberate reason to model them as separate labels. Independent sigmoids can assign high probability to both classes or low probability to both, which violates the one-of-two assumption.

8. Imbalanced data, thresholds, and calibration#

The loss function is only one part of a classification system.

For binary or multi-label classification, the default decision threshold of 0.5 is not automatically optimal. If false negatives are expensive, a lower threshold may improve recall; if false positives are expensive, a higher threshold may improve precision. Choose thresholds using validation data and the actual business cost of errors.

BCE supports positive weighting, which can help when positive labels are rare. But weighting changes the optimization objective and can affect probability calibration. Evaluate the resulting probabilities rather than assuming they remain calibrated.

For categorical classification, class weights can increase the contribution of underrepresented classes. You should still inspect per-class precision and recall, confusion matrices, and calibration. A single aggregate accuracy value can conceal poor performance on minority classes.

Do not confuse:

  • Loss weighting: changes how training errors contribute to the objective.
  • Decision threshold: changes how predicted probabilities become class decisions.
  • Sampling strategy: changes which examples appear during training.

They interact, but they solve different problems.

9. Common mistakes and failure modes#

  1. Using CCE for a multi-label dataset. Softmax forces the probabilities to compete and sum to one. A sample with both cat and dog labels cannot be represented correctly as two simultaneously high independent probabilities.
  2. Using BCE for mutually exclusive classes without considering the model structure. Independent sigmoids do not enforce exactly one class. The model can predict none or several.
  3. Applying sigmoid or softmax twice. Use logits with the corresponding logits-aware loss unless the API explicitly expects probabilities.
  4. Mismatching target shapes. BCE targets should match the logits shape. Class-index CCE targets should omit the class dimension and use integer class IDs.
  5. Using the wrong target dtype. PyTorch class-index targets for CrossEntropyLoss should be integer class indices; BCE targets should be floating-point values.
  6. Assuming one-hot labels always mean BCE. One-hot labels for a mutually exclusive multiclass task are a categorical distribution, not a set of independent labels. Use categorical cross-entropy.
  7. Comparing raw loss values across different reductions. BCE may average across batch and label dimensions, while another implementation may sum or average differently. Normalize consistently before comparing.
  8. Ignoring class imbalance. A model can achieve high accuracy by predicting the majority class. Inspect per-class metrics and choose weighting or sampling deliberately.
  9. Treating the loss as the final decision rule. Threshold selection, calibration, and downstream costs still matter.

10. Monitoring and debugging checklist#

When training behaves unexpectedly, inspect these items before changing the architecture:

  • Verify whether labels are mutually exclusive or multi-label in the source data.
  • Inspect a few raw target vectors and confirm their encoding.
  • Check output tensor dimensions and target tensor dimensions.
  • Confirm whether the model returns logits or probabilities.
  • Confirm the chosen loss expects logits or probabilities.
  • For categorical targets, verify class indices are in range and that each sample has one valid target.
  • For multi-label targets, verify every target is in the expected range and each output maps to the intended label.
  • Track per-class precision, recall, F1, and support; do not rely only on aggregate accuracy.
  • Inspect calibration and threshold performance on a held-out validation set.
  • Compare loss values only after aligning reduction, weighting, and label dimensions.

A useful unit test is to feed a confidently correct prediction and a confidently wrong prediction through the loss. The correct prediction should have a small loss; the confidently wrong prediction should have a substantially larger loss.

11. Interview-ready answer#

Binary cross-entropy models each output as an independent binary event using sigmoid probabilities. It is used for binary classification and multi-label problems where multiple labels can be true. Categorical cross-entropy models one probability distribution over mutually exclusive classes using softmax, so it is used when each sample belongs to exactly one class. In PyTorch, use BCEWithLogitsLoss with same-shaped floating-point targets, and CrossEntropyLoss with raw class logits and usually integer class-index targets. For a two-class task, either one-logit BCE or two-logit categorical cross-entropy can work; the key is to match the loss to the label structure.

Key takeaway#

BCE asks “is each label present?” Categorical cross-entropy asks “which one class is correct?” Determine the label relationship first, then align the output layer, target encoding, and loss function. That prevents a common class of silent modeling errors.

Related questions

Explore other topics:Machine LearningLarge Language Models