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.
Symbol by symbol: is the number of examples; numbers them; is the true value of example ; ("y-hat") what the model predicted for it; the big means "add across all examples" and the 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.

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 ( vs ). 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):
Same symbols as MSE, one difference: the vertical bars mean absolute value, that is, "take the number and forget its sign". A gap of and a gap of 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.

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:
Symbol by symbol: is the true answer, 1 if the example belongs to the class and 0 otherwise; ("y-hat") is the probability the model assigns to that class, a number between 0 and 1; 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 , the factor is 0 and the second term vanishes, leaving . If , the first term vanishes and remains. Both readings say the same thing: put high probability on whichever answer is true.
Put numbers on it. If and the model predicts , confident and correct, the loss is , nearly nothing. If it predicts , confident and wrong, the loss is , 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.).
Symbol by symbol: is the number of classes; numbers them; is 1 if is the correct class and 0 otherwise; is the probability the model assigns to class ; is the logarithm, which is 0 when its argument is 1 and dives toward 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.
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
Symbol by symbol: 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; is 0 if the two elements belong to the same class and 1 otherwise; 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 (): the second term cancels out, leaving . You directly minimize the distance between the two embeddings, you pull them as close as possible.
- Different pairs (): the first term cancels out, leaving . You only penalize if the distance is less than the margin . If the two embeddings are already at distance , the 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).
Symbol by symbol: , and are the anchor, the positive and the negative; is the distance from anchor to positive, the distance from anchor to negative; is the margin, a safety gap you impose; and 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 .
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:
Symbol by symbol: is the probability the model gave to the correct answer; ("gamma") is a setting chosen by the engineer, usually 2; and the rest, , 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 is the key. Here's why it works:
- When the model is confident and correct ( close to 1): , so . The factor collapses and so does the loss. Concrete example: if and , the factor equals , the loss is divided by 400 compared to standard cross-entropy.
- When the model is wrong ( close to 0): , so . The loss stays at full strength, like a standard cross-entropy.
- The parameter (typically 2) controls how aggressively this filtering works. gives back exactly ordinary cross-entropy, since any number raised to the power 0 equals 1. The higher 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.
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:
Symbol by symbol: is the embedding of the example under study; that of its positive, an example meant to resemble it; runs over every example in the batch, positives and negatives alike; 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); is the exponential, which makes everything positive and widens gaps; and ("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 (temperature) controls the "selectivity" of the distribution. With a low , the softmax distribution becomes very peaked: only the most similar positive matters. With a high , 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
| Task | Loss to Use | Notes |
|---|---|---|
| Predict a continuous number | MSE, MAE, or Huber | MSE by default, MAE if outliers |
| 2 classes | Binary cross-entropy | With sigmoid activation at output |
| 3+ classes | Categorical cross-entropy | With softmax at output |
| Learn a representation | Contrastive, triplet, InfoNCE | InfoNCE is the newest and most stable |
| Very rare class (extreme imbalance) | Focal loss | Ignores easy cases |
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.
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?