Edd's Knowledge Base

In machine learning, loss functions (or cost functions) are mathematical formulas used to measure the difference between a model’s predicted output and the actual target values. The model uses this error metric during training to update its weights and improve its accuracy.

The choice of loss function depends primarily on the type of task: Regression or Classification.

1. Regression Loss Functions

Used when the goal is to predict a continuous numerical value (e.g., price, temperature).

  • Mean Squared Error (MSE / L2 Loss):
    • What it is: The average of the squared differences between predicted and actual values.
    • Pros/Cons: It penalizes larger errors more heavily because of the squaring. It is very common but highly sensitive to outliers.
  • Mean Absolute Error (MAE / L1 Loss):
    • What it is: The average of the absolute differences between predicted and actual values.
    • Pros/Cons: Generally more robust to outliers than MSE.
  • Huber Loss:
    • What it is: A combination of MSE and MAE. It acts like MSE when errors are small and like MAE when errors are large.
    • Pros/Cons: Less sensitive to outliers than MSE while remaining differentiable at zero.

2. Classification Loss Functions

Used when the goal is to categorize data points into discrete classes (e.g., spam vs. not spam).

  • Cross-Entropy Loss (Log Loss):
    • What it is: The most common loss function for classification models that output probability values between 0 and 1.
    • Variants: Binary Cross-Entropy for two classes, and Categorical Cross-Entropy for multi-class problems. See 3. Cross-Entropy in Depth below.
  • Hinge Loss:
    • What it is: Designed for “maximum margin” classification, primarily used with Support Vector Machines (SVMs).
    • Pros/Cons: Penalizes predictions that fall on the wrong side of the decision boundary or within the margin.
  • Kullback-Leibler (KL) Divergence:
    • What it is: Measures how one probability distribution differs from a reference probability distribution. Often used in specific neural network architectures.

3. Cross-Entropy in Depth

The Intuition

Cross-entropy compares two probability distributions: the true distribution (the labels) and the predicted distribution (the model’s output). It measures how many “nats” (or bits, with ) of surprise the model experiences when the true outcome occurs.

  • A confident, correct prediction gives a loss near 0.
  • A confident, wrong prediction gives a very large loss, since as .
  • It is tied to KL divergence: . Because the label entropy is constant, minimizing cross-entropy is the same as minimizing KL divergence, which equals maximum likelihood estimation.
Predicted probability of the true classLoss Reading
0.990.010Confident and right
0.900.105Good
0.500.693Coin flip
0.102.303Bad
0.014.605Confident and wrong

Binary Cross-Entropy (BCE / Log Loss)

Used when there are two classes and the model outputs a single probability , usually through a sigmoid .

Since is either 0 or 1, only one term is ever active:

Averaged over a batch of samples:

Worked example (spam detection). Three emails, label 1 = spam:

EmailTrue Predicted Loss
A10.9
B00.2
C10.6

Batch loss: . Email C is the least certain, so it contributes the most.

Where it is used: Logistic Regression, binary classifiers (fraud, churn, disease present or absent), GAN discriminators, and multi-label classification, where each label gets its own sigmoid and its own BCE term (a movie can be both “comedy” and “romance”).

Categorical Cross-Entropy (Multi-Class)

Used when there are mutually exclusive classes. The model outputs raw scores (logits) , which a softmax turns into a probability distribution:

The label is a one-hot vector (1 for the true class, 0 elsewhere), so the sum collapses to a single term:

Averaged over a batch:

Worked example (image classification). Classes: cat, dog, bird. The true class is dog, so . The network outputs logits .

  1. Exponentiate: , sum
  2. Softmax:
  3. Loss:

Had the model instead predicted (confident in cat), the loss would be , nearly 4 times larger.

Gradient: softmax combined with cross-entropy has a very clean gradient with respect to the logits, . For the example above that is : push the dog logit up and the others down. This is a big reason the pair is so common, and why gradients stay healthy even when predictions are badly wrong.

Choosing the Right Variant

TaskOutput layerLossLabel format
Binary (spam or not)1 unit, sigmoidBinary cross-entropy0 or 1
Multi-class, one label per sample units, softmaxCategorical cross-entropyOne-hot, e.g. [0, 1, 0]
Multi-class, integer labels units, softmaxSparse categorical cross-entropyClass index, e.g. 1
Multi-label (several can be true) units, sigmoid eachBinary cross-entropy per classMulti-hot, e.g. [1, 0, 1]

Sparse categorical cross-entropy computes the same value as the one-hot version; it only saves memory by storing the class index.

In Practice

  • Use logits, not probabilities, with the fused loss. In PyTorch, nn.CrossEntropyLoss expects raw logits and applies log-softmax internally; nn.BCEWithLogitsLoss does the same for sigmoid. This is more numerically stable than computing softmax or sigmoid first and then taking the log.
  • Avoid . Libraries clip probabilities to a small epsilon, such as , when you pass in probabilities directly.
  • Class imbalance: pass per-class weights (weight= or pos_weight= in PyTorch), or use focal loss, which down-weights easy examples.
  • Label smoothing: replace the hard one-hot target with something like to reduce overconfidence.
import torch, torch.nn as nn
 
# Multi-class: logits for (cat, dog, bird), true class = dog (index 1)
logits = torch.tensor([[1.0, 2.0, 0.1]])
target = torch.tensor([1])
print(nn.CrossEntropyLoss()(logits, target))   # tensor(0.4170)
 
# Binary: one logit per sample, target is 0.0 or 1.0
logit = torch.tensor([2.1972])                 # sigmoid -> 0.9
print(nn.BCEWithLogitsLoss()(logit, torch.tensor([1.0])))  # tensor(0.1054)

References for Cross-Entropy

4. Other Loss Functions Worth Knowing

The losses above handle plain regression and classification. Many tasks need a loss shaped to the problem: imbalanced classes, similarity rather than labels, sequences without alignment, or generative models.

LossUsed forCore idea
Focal lossObject detection with extreme class imbalanceDown-weight easy examples so hard ones dominate
Dice lossSegmentationOptimize overlap directly, robust to small foreground
IoU / GIoU lossBounding-box regressionOptimize the box overlap, not coordinate distance
Quantile (pinball) lossPredicting a quantile or intervalAsymmetric penalty for over- and under-prediction
Contrastive lossSimilarity learning with pairsPull similar pairs together, push dissimilar apart by a margin
Triplet lossEmbeddings (face recognition, retrieval)Anchor closer to positive than to negative by a margin
InfoNCESelf-supervised and multimodal learningPick the true match out of many negatives
Perceptual lossImage generation and style transferCompare deep features instead of pixels
CTC lossSpeech and handwriting recognitionSum over all alignments of labels to input frames
Adversarial (GAN) lossGenerative modelsA discriminator supplies the training signal
ELBO / KL termVariational autoencodersReconstruction plus a KL regularizer

Focal loss: ignore the easy examples

In a detector, a handful of positions contain objects and thousands are easy background. Plain cross-entropy gives every easy background position a small loss, but thousands of them add up and drown out the few hard cases. Focal loss (Lin et al., 2017) multiplies the cross-entropy by a factor that shrinks for well-classified examples:

Here is the probability the model gives to the true class, and controls the focus. With , which is a typical setting:

Model confidence in true class Weight Effect
0.9 (easy)0.01Loss cut to 1%
0.50.25Cut to 25%
0.1 (hard)0.81Almost unchanged

Setting recovers ordinary cross-entropy. The paper’s point is that this removes most of the accuracy gap between one-stage and two-stage detectors.

Dice and IoU losses: optimize overlap directly

For segmentation, the foreground (a tumor, a road) often covers a small share of the pixels, so an all-background prediction already scores well on pixel accuracy. The Dice coefficient measures overlap between prediction and ground truth , and the loss is one minus it. Using probabilities and labels makes it differentiable:

It was used as the training objective in V-Net for volumetric medical segmentation, where foreground voxels are strongly outnumbered by background. For boxes, IoU loss is , and GIoU adds a penalty based on the smallest box enclosing both boxes, so it still gives a gradient when the boxes do not overlap.

Quantile (pinball) loss: predicting a range

MSE and MAE predict the mean or median. To predict a quantile (for example the 90th percentile), penalize the two kinds of error differently:

At this is half the absolute error, which gives the median. At under-predicting costs 9 times as much as over-predicting, so the model learns an upper bound. Training two quantiles gives a prediction interval.

Metric learning: contrastive, triplet and InfoNCE

Sometimes there are no class labels, only a notion of “similar”. These losses train an embedding where distance means similarity (Word2Vec is an early example of the idea in NLP).

  • Contrastive loss works on pairs with distance between their embeddings and for similar, for dissimilar:

Similar pairs are pulled together, and dissimilar pairs are pushed apart only until they are away (the margin).

  • Triplet loss uses an anchor , a positive (same identity) and a negative (different identity):

The anchor must be closer to the positive than to the negative by at least , otherwise the loss is zero. FaceNet used it to learn a compact embedding where distance reflects face similarity (128 bytes per face), with online mining of informative triplets, since most random triplets are already satisfied and contribute nothing.

  • InfoNCE (from contrastive predictive coding) treats the problem as classification: given a query , pick its true partner out of candidates,

It is cross-entropy over similarities with a temperature . Larger batches supply more negatives. Variants of this form train many self-supervised and image-text models.

CTC: sequences without alignment

In speech or handwriting recognition the input has many more frames than the output has characters, and nobody labelled which frame belongs to which character. Connectionist temporal classification (CTC) adds a blank symbol and defines the loss as the negative log of the total probability of all alignments that collapse to the correct text (repeats merged, blanks removed). A dynamic-programming recursion computes the sum efficiently.

Perceptual loss: compare features, not pixels

A pixel-wise MSE between two images punishes a tiny shift heavily and favours blurry outputs. A perceptual loss (Johnson et al., 2016) feeds both images through a pretrained network and compares their feature maps, so images that look alike to the network score as close. It is widely used in super-resolution and style transfer.

Adversarial and variational losses

  • GAN loss: a discriminator learns to tell real from generated samples, and the generator is trained to fool it, in the original formulation . The loss is a moving target set by the opponent (Generative Adversarial Networks). The Wasserstein variant replaces it with a distance between distributions that gives smoother gradients.
  • ELBO: a variational autoencoder minimizes a reconstruction loss plus a KL divergence that keeps the latent distribution close to a prior (Variational Autoencoders). This is the KL divergence from section 2 used as a regularizer.

Losses vs. training tricks

Some things that look like losses are really modifications: label smoothing (soften one-hot targets, for example 0.9 and 0.1 instead of 1 and 0), class weights (scale each class’s loss), and regularization terms added to any loss (Regularization). Ranking tasks use pairwise or listwise losses (Learning To Rank).

Sources for this section

  • Lin et al., Focal Loss for Dense Object Detection: the class-imbalance problem and the down-weighting of easy examples.
  • Schroff, Kalenichenko and Philbin, FaceNet: triplets of matching and non-matching face patches, online triplet mining, 128 bytes per face.
  • van den Oord, Li and Vinyals, Representation Learning with Contrastive Predictive Coding: a probabilistic contrastive loss with negative sampling (the abstract does not use the name InfoNCE, which comes from the paper’s body).
  • Milletari, Navab and Ahmadi, V-Net: the Dice-coefficient objective for strongly imbalanced foreground and background.
  • Formulas for quantile, contrastive, CTC, perceptual, GAN and ELBO losses, the focal-loss setting , and the IoU and GIoU remarks are from my own knowledge and were not checked against the papers (Hadsell et al., 2006; Graves et al., 2006; Johnson et al., 2016; Goodfellow et al., 2014).

Source: Synthesized from BuiltIn, DataCamp, and IBM technical documentation.