AI State of the Art
Fundamentals/Machine Learning: The Basics/30 min
Section 12

Loss Functions: Cross-Entropy, MSE, Contrastive Loss

Listen as a podcast β†’

Introduction: The Loss is Your Objective

The loss function (or cost function) is the single number that tells your model "how wrong you are." A high loss means the model is doing poorly, a low loss means it's doing good work. This is the number the optimizer tries to minimize at each training step.

This choice is crucial because the loss literally defines what the model learns to optimize. Two different losses on the same data and the same architecture will produce two models with completely different behaviors.

Take a concrete example. A loss that counts every error at face value produces a "balanced" model that extreme cases do not throw off. A loss that amplifies large errors produces a model obsessed with the hard cases, even at the cost of some accuracy on the easy ones. Same data, same architecture, opposite behaviours.

So the question to ask of any loss is always the same: what does it punish, and how hard? That is the thread of this page.

MSE: For Predicting Numbers

Mean Squared Error (MSE) is for regression, that is, for predicting a number.

What it punishes: the gap from the truth, amplified by squaring. Being twice as wrong costs four times as much.

MSE=1nβˆ‘i=1n(y^iβˆ’yi)2\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (\hat{y}_i - y_i)^2

Symbol by symbol: nn is the number of examples; ii numbers them; yiy_i is the true value of example ii; y^i\hat{y}_i ("y-hat") what the model predicted for it; the big βˆ‘\sum means "add across all examples" and the 1n\frac{1}{n} turns that sum into an average. In one sentence: gap between prediction and truth, squared, then averaged over every example.

Example: you're predicting the price of a house.

  • House 1: you say $400k, it's $400k. Error = 0. Contribution to MSE = 0.
  • House 2: you say $500k, it's $450k. Error = $50k. Contribution = ($50k)^2 = 2.5 billion.
  • House 3: you say $405k, it's $400k. Error = $5k. Contribution = ($5k)^2 = 25 million.
Illustration of linear regression and mean squared error
Every blue dot is a house, the dashed line is what the model predicts. The vertical red arrow is the gap between the real price (Y) and the predicted one (Y'). MSE adds up all those gaps, after squaring each of them.Source : Encord

Why the Square?

The square disproportionately penalizes large errors. An error of 10 contributes 100 times more to the loss than an error of 1 (102=10010^2 = 100 vs 12=11^2 = 1). This is a double-edged property.

It's an advantage when large errors are catastrophic. If you're predicting a house price, an error of $100k is far more serious than an error of $5k, and the square reflects this reality by penalizing it 400 times more.

It is a disadvantage when your data contains outliers, extreme cases, often data-entry mistakes. A single $10 million apartment in your dataset will completely dominate the MSE and force the model to sacrifice its accuracy on all other examples just to reduce that single extreme error.

Variant: MAE

Mean Absolute Error (MAE):

MAE=1nβˆ‘i=1n∣y^iβˆ’yi∣\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |\hat{y}_i - y_i|

Same symbols as MSE, one difference: the vertical bars βˆ£β‹…βˆ£|\cdot| mean absolute value, that is, "take the number and forget its sign". A gap of βˆ’3-3 and a gap of +3+3 therefore count the same, which squaring also did, but here without amplifying.

What it punishes: the gap from the truth, as it stands. No square, so no amplification: an error of 10 is worth only 10 times an error of 1, not 100 times. That makes it far more robust to outliers, whose influence stays proportional to their gap instead of exploding.

When to choose it: when you suspect your data holds wrong or extreme values and you do not want the model devoting itself to them. Conversely, choose MSE when the large errors really are the serious ones.

In practice there is also the Huber loss (or Smooth L1), which combines the best of both: it behaves like MSE for small errors (a smooth slope near zero, hence stable learning) and like MAE for large ones (no explosion from a single extreme case). An excellent default when you are unsure about the distribution of your errors.

Illustration of the MAE loss function
The same picture, except the red segments now count at face value, with no squaring. The lone dot far below the green line weighs only in proportion to its distance, so it no longer dominates the whole measurement.Source : Amir Sefidian

Cross-Entropy: For Classification

Binary Cross-Entropy (2 classes)

For classifying between 2 categories (spam vs not spam, cat vs not cat).

Binary Cross-Entropy (BCE) reads:

BCE=βˆ’[yβ‹…log⁑(y^)+(1βˆ’y)β‹…log⁑(1βˆ’y^)]\text{BCE} = -\left[ y \cdot \log(\hat{y}) + (1 - y) \cdot \log(1 - \hat{y}) \right]

Symbol by symbol: yy is the true answer, 1 if the example belongs to the class and 0 otherwise; y^\hat{y} ("y-hat") is the probability the model assigns to that class, a number between 0 and 1; log⁑\log is the logarithm, which is 0 when its argument is 1 and dives toward minus infinity as the argument approaches 0, hence the minus sign in front of the brackets, which makes the loss positive. The sigmoid mentioned below is simply the function that squashes any number into the range 0 to 1, so the model's output can be read as a probability.

In one sentence: look at the probability the model gave to the correct answer, and the penalty explodes as that probability nears zero.

The two terms never operate at once, and that is the whole point of the construction. If y=1y = 1, the factor (1βˆ’y)(1 - y) is 0 and the second term vanishes, leaving βˆ’log⁑(y^)-\log(\hat{y}). If y=0y = 0, the first term vanishes and βˆ’log⁑(1βˆ’y^)-\log(1 - \hat{y}) remains. Both readings say the same thing: put high probability on whichever answer is true.

Put numbers on it. If y=1y = 1 and the model predicts y^=0.99\hat{y} = 0.99, confident and correct, the loss is βˆ’log⁑(0.99)=0.01-\log(0.99) = 0.01, nearly nothing. If it predicts y^=0.01\hat{y} = 0.01, confident and wrong, the loss is βˆ’log⁑(0.01)=4.6-\log(0.01) = 4.6, some 460 times more.

What it punishes: not the misclassification itself, but misplaced confidence. Being wrong while hesitating costs little; being wrong while certain costs enormously.

Why not MSE for classification? Because the sigmoid is almost flat at both ends: when it outputs 0.01, its input has to move a great deal to shift the output at all. Under MSE, the gradient the model receives is proportional to that slope. So a model predicting 0.01 when the truth is 1 sits very far from the target and yet gets almost no correction. It stays stuck.

Cross-entropy cancels that effect exactly: the logarithm reacts all the more violently the smaller the probability, and this precisely offsets the flattening of the sigmoid. The gradient stays strong right where it is needed most. Which is what we want: hit hardest the model that is confident AND wrong.

Categorical Cross-Entropy (3+ classes)

The natural extension of BCE for 3 or more classes (dog, cat, bird, etc.).

L=βˆ’βˆ‘c=1Cycβ‹…log⁑(y^c)\mathcal{L} = -\sum_{c=1}^{C} y_c \cdot \log(\hat{y}_c)

Symbol by symbol: CC is the number of classes; cc numbers them; ycy_c is 1 if cc is the correct class and 0 otherwise; y^c\hat{y}_c is the probability the model assigns to class cc; log⁑\log is the logarithm, which is 0 when its argument is 1 and dives toward βˆ’βˆž-\infty as the argument approaches 0, hence the leading minus sign, which makes the loss positive. In one sentence: only the probability given to the right answer is examined, and the penalty explodes as that probability nears zero.

Two words worth pinning down here. A logit is the raw score the model emits for a class: any number, on no fixed scale. Softmax is the function converting those raw scores into probabilities: it makes them all positive and forces their sum to be exactly 1.

The model produces a raw score (logit) for each class. A softmax converts these scores into probabilities that sum to 1. The loss only penalizes the probability assigned to the correct class: if the true class is "cat" and the model assigns it 95% probability, the loss is low. If it only assigns 5%, the loss is huge.

Stable Implementation

In practice you never apply softmax and then the logarithm as two separate steps. Every library offers a function doing both at once, named something like cross_entropy_with_logits or log_softmax. It is mathematically identical but numerically far safer: you avoid taking the logarithm of a number so small the computer has rounded it to zero.

Contrastive Loss: Learning Similarity

Sometimes you don't want the model to predict a class or a value. You want it to learn a representation space: similar things end up close together, different things end up far apart. This is the foundation of recognition and similarity search systems.

Use cases:

  • Face recognition: embeddings of two photos of the same face should be close, even if lighting conditions change
  • Image similarity search: the query and relevant results should be close in the space
  • Text embeddings: two sentences that mean the same thing should be close
L=(1βˆ’y)β‹…d2+yβ‹…max⁑(0,mβˆ’d)2\mathcal{L} = (1 - y) \cdot d^2 + y \cdot \max(0, m - d)^2

Symbol by symbol: dd is the Euclidean distance, ordinary straight-line distance, between the two examples' embeddings, that is, between the lists of numbers by which the model represents them; yy is 0 if the two elements belong to the same class and 1 otherwise; mm is the margin, the minimum distance you want to enforce between two elements of different classes; and the exponent 2 squares those quantities, for the same reason as in MSE, to punish large gaps harder.

The formula is asymmetric, and that's intentional:

  • Similar pairs (y=0y = 0): the second term cancels out, leaving d2d^2. You directly minimize the distance between the two embeddings, you pull them as close as possible.
  • Different pairs (y=1y = 1): the first term cancels out, leaving max⁑(0,mβˆ’d)2\max(0, m - d)^2. You only penalize if the distance dd is less than the margin mm. If the two embeddings are already at distance d>md > m, the max⁑\max gives 0 and the loss is zero, they're considered "far enough" and you stop pushing. No need to push them infinitely far apart, they just need to be distinct enough.

Triplet Loss: Training with Triplets

Variation: take 3 examples: the anchor, a positive (same class), and a negative (different class).

L=max⁑(0,Β d(a,p)βˆ’d(a,n)+m)\mathcal{L} = \max\left(0,\ d(a, p) - d(a, n) + m\right)

Symbol by symbol: aa, pp and nn are the anchor, the positive and the negative; d(a,p)d(a, p) is the distance from anchor to positive, d(a,n)d(a, n) the distance from anchor to negative; mm is the margin, a safety gap you impose; and max⁑(0,β‹…)\max(0, \cdot) means "keep this number if it is positive, otherwise count zero".

In one sentence: the loss only switches on if the positive is not closer to the anchor than the negative is, by at least the margin mm.

What it punishes: not an absolute distance, but a ranking. Where the three points sit in the space does not matter; what matters is that the right one comes before the wrong one. As soon as that holds with the desired margin, the loss drops to zero and the model stops pushing.

The Challenge

The choice of triplets is crucial. Triplets that are too easy (negative so far away it's easily detected) teach nothing.

The good triplets are the hard negatives: negative examples that look very similar to the positive but don't belong to the same class. These are the ones that force the model to refine its representations.

Focal Loss: When a Class is Rare

Classic problem: detecting objects in an image. You cut the image into tens of thousands of regions, and virtually none contains anything. A dumb model answering "nothing" everywhere therefore scores near-perfect accuracy, and is useless.

Focal Loss for Dense Object Detection (Lin et al., 2017)

Focal loss (named for focus: it concentrates attention) reduces the importance of cases that are already classified correctly:

L=βˆ’(1βˆ’y^)Ξ³β‹…log⁑(y^)\mathcal{L} = -(1 - \hat{y})^\gamma \cdot \log(\hat{y})

Symbol by symbol: y^\hat{y} is the probability the model gave to the correct answer; Ξ³\gamma ("gamma") is a setting chosen by the engineer, usually 2; and the rest, βˆ’log⁑(y^)-\log(\hat{y}), is exactly the cross-entropy seen above. In one sentence: take cross-entropy and multiply it by a coefficient that makes it vanish as soon as the model is already right.

The modulation factor (1βˆ’y^)Ξ³(1 - \hat{y})^\gamma is the key. Here's why it works:

  • When the model is confident and correct (y^\hat{y} close to 1): (1βˆ’y^)β‰ˆ0(1 - \hat{y}) \approx 0, so (1βˆ’y^)Ξ³β‰ˆ0(1 - \hat{y})^\gamma \approx 0. The factor collapses and so does the loss. Concrete example: if y^=0.95\hat{y} = 0.95 and Ξ³=2\gamma = 2, the factor equals (0.05)2=0.0025(0.05)^2 = 0.0025, the loss is divided by 400 compared to standard cross-entropy.
  • When the model is wrong (y^\hat{y} close to 0): (1βˆ’y^)β‰ˆ1(1 - \hat{y}) \approx 1, so (1βˆ’y^)Ξ³β‰ˆ1(1 - \hat{y})^\gamma \approx 1. The loss stays at full strength, like a standard cross-entropy.
  • The parameter Ξ³\gamma (typically 2) controls how aggressively this filtering works. Ξ³=0\gamma = 0 gives back exactly ordinary cross-entropy, since any number raised to the power 0 equals 1. The higher Ξ³\gamma gets, the more aggressively the model ignores easy cases to focus on hard ones.

Result: instead of drowning the learning signal under millions of trivial cases, the model concentrates its effort on the hard cases, the ones where it's actually wrong. It's like a teacher who stops asking questions the student already knows the answer to and focuses on their weak points.

Used Beyond Detection

Anywhere you have a massive class imbalance: fraud detection (99.9% legitimate), rare disease diagnosis, anomaly detection. Focal loss helps the model avoid becoming "lazy."

InfoNCE: Modern Contrastive Learning

Models like CLIP (Contrastive Language-Image Pre-training, which pairs images with captions) and SimCLR (Simple framework for Contrastive Learning of visual Representations) use a loss called InfoNCE, from Noise Contrastive Estimation, the "noise" here being the wrong candidates.

It's a cross-entropy applied to similarities between representations:

L=βˆ’log⁑exp⁑(sim(zi,zp)/Ο„)βˆ‘jexp⁑(sim(zi,zj)/Ο„)\mathcal{L} = -\log \frac{\exp(\text{sim}(z_i, z_p) / \tau)}{\sum_{j} \exp(\text{sim}(z_i, z_j) / \tau)}

Symbol by symbol: ziz_i is the embedding of the example under study; zpz_p that of its positive, an example meant to resemble it; zjz_j runs over every example in the batch, positives and negatives alike; sim\text{sim} is a similarity measure, usually cosine similarity (the angle between the two lists of numbers, equal to 1 when they point the same way; see norms and distances); exp⁑\exp is the exponential, which makes everything positive and widens gaps; and Ο„\tau ("tau") is the temperature. The ratio of numerator to denominator is exactly a probability: the probability of picking the right partner out of all candidates in the batch.

The parameter Ο„\tau (temperature) controls the "selectivity" of the distribution. With a low Ο„\tau, the softmax distribution becomes very peaked: only the most similar positive matters. With a high Ο„\tau, the distribution is smoother and the model learns more gently.

The intuition is simple: it's a cross-entropy where the "classes" are the positive and negative pairs. The model learns to maximize similarity with the positive while minimizing similarity with all negatives in the batch simultaneously. Compared to triplet loss, InfoNCE is more stable because it uses all negatives in the batch in a single pass, giving a richer and less noisy learning signal.

Summary Table

TaskLoss to UseNotes
Predict a continuous numberMSE, MAE, or HuberMSE by default, MAE if outliers
2 classesBinary cross-entropyWith sigmoid activation at output
3+ classesCategorical cross-entropyWith softmax at output
Learn a representationContrastive, triplet, InfoNCEInfoNCE is the newest and most stable
Very rare class (extreme imbalance)Focal lossIgnores easy cases
The Loss Choice Can Outperform the Architecture

A good loss allows even simple networks to compete with complex ones. A bad loss destroys the best network. This is an active area of research, especially in self-supervised learning.

Why This Matters

The loss function is the objective you formally declare to the model. It's literally the only signal it receives to improve. A bad loss choice, and the model optimizes the wrong thing: it performs well in training, but fails in production because it never learned what actually matters. Taking the time to choose the right loss for your task is often more decisive than searching for a better architecture.

Check your understanding0 / 5

1. Your house-price dataset contains one $10 million apartment, probably a data-entry mistake. Why is that a problem if you train with MSE?

2. What does cross-entropy actually punish in classification?

3. Why is MSE not used to train a classifier whose output goes through a sigmoid?

4. In object detection, virtually every region of an image contains nothing, so a model that answers Β« nothing Β» everywhere scores near-perfect accuracy. How does focal loss handle that imbalance?

5. What does the triplet loss punish?