Loss Functions › Classification Losses
Language AI HandbookAll chapters Loss Functions › Classification LossesOne section · Sections in this chapter4 / 17 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Classification tasks require predicting one of discrete classes. The structure of the problem is fundamentally different from regression: instead of predicting a continuous value, the model produces scores (logits) for each class, which are then converted to probabilities.
Negative Log-Likelihood
The foundation of all classification losses is maximum likelihood estimation. We want to find model parameters that maximize the probability of observing the training data. If the model outputs a probability distribution over classes, the likelihood of the true class is . We want this to be high.
Maximizing likelihood is equivalent to minimizing negative log-likelihood:
where:
- : the model's predicted probability for the true class
- : the natural logarithm
The log transformation serves two purposes. First, it converts a product of probabilities (over a dataset) into a sum, which is numerically more stable. Second, the log is a monotone transformation, so maximizing is equivalent to maximizing . Because log of a probability between 0 and 1 is negative, we negate it to get a positive loss.
Negative log-likelihood has an intuitive interpretation: it measures how surprised the model is to see the true label. If the model assigns probability 0.99 to the correct class, the loss is (barely surprised). If the model assigns probability 0.01 to the correct class, the loss is (very surprised). The loss grows without bound as the predicted probability approaches zero, which strongly penalizes confident wrong predictions.
This unbounded growth is intentional. A loss that caps at some maximum value would allow the model to be confidently wrong without incurring a proportional penalty. The logarithmic penalty means there is no "good enough" point where the model can stop improving its confidence in correct predictions, which drives the model toward sharper, more accurate probability estimates.
Cross-Entropy Loss
Cross-entropy loss is the most widely used loss for classification. It combines softmax (to convert logits to probabilities) with negative log-likelihood into a numerically stable combined operation.
Given the model's raw scores (logits) for classes, the softmax function converts them to a probability distribution:
where:
- : the raw score (logit) for class
- : the exponential of the logit, which ensures positivity
- : the normalizing constant, which ensures probabilities sum to 1
- : the predicted probability for class
Cross-entropy loss then applies negative log-likelihood to the true class:
where:
- : a one-hot indicator, equal to 1 for the true class and 0 elsewhere
- : the predicted probability for class
Because is one-hot, this sum collapses to just where is the index of the true class. The sum notation is more general, covering soft labels (non-binary values), but the one-hot version is standard for supervised classification.
Cross-entropy has roots in information theory. It measures the expected number of bits needed to encode events from distribution using a code optimized for distribution . When matches exactly, cross-entropy equals the entropy of , its minimum possible value. During training, minimizing cross-entropy pushes the model's predictions toward the true distribution of the data.
Numerical stability is a critical implementation detail. Computing softmax followed by log involves exponentials that can overflow (for large logits) or underflow (for very negative logits). The standard trick is the log-sum-exp stabilization:
where is subtracted before exponentiation to prevent overflow. PyTorch's F.cross_entropy() implements this automatically when you pass raw logits. Always pass logits directly to F.cross_entropy() rather than computing softmax separately and then applying NLL, because the combined implementation is both more numerically stable and more computationally efficient.
The gradient of cross-entropy with respect to the logits has a clean form that reveals why the loss is so well-suited to gradient descent. For the logit :
This is simply the difference between the predicted probability and the target. For the true class (), the gradient is , which is negative (pushing the logit up) unless . For incorrect classes (), the gradient is , which is positive (pushing the logit down). The optimizer directly reduces the predicted probability of incorrect classes and increases the probability of the correct class. This clean interpretation is one reason cross-entropy is so widely used: the gradients have an immediate intuitive meaning.
Binary Cross-Entropy
Binary classification is a special case where (positive or negative). Rather than using a 2-class softmax, it is standard to use a single output neuron with a sigmoid activation, which directly outputs the probability of the positive class.
Given a model output where is the sigmoid function and is the logit, binary cross-entropy (BCE) is:
where:
- : the true binary label
- : the model's predicted probability of the positive class
- : the loss contribution when (penalizes predicting low probability for a positive example)
- : the loss contribution when (penalizes predicting high probability for a negative example)
The two terms are mutually exclusive: when , the second term vanishes, and when , the first term vanishes. This loss strongly penalizes confident wrong predictions: if the model outputs for a positive example (), the loss is .
The gradient of BCE with respect to the logit (before sigmoid) has a particularly clean form:
where:
- : the sigmoid of the logit
- : the true label
This is the simplest possible gradient: just the prediction error. The sigmoid's derivative cancels with the derivative of the log, producing a numerically stable and interpretable gradient signal.
Binary cross-entropy is also the right loss for multi-label classification, where each example can belong to multiple classes simultaneously. In multi-label settings, you have output neurons, each representing an independent binary prediction. BCE is applied independently to each output, and the total loss is the sum over all binary losses. This is different from multiclass (categorical) classification, where exactly one class is correct and the outputs must sum to 1.
Categorical Cross-Entropy vs. Binary Cross-Entropy
The choice between categorical and binary cross-entropy depends on the problem structure:
- Binary cross-entropy applies when each example belongs to one of two classes or when predicting multiple independent binary attributes simultaneously (multi-label classification).
- Categorical cross-entropy applies when each example belongs to exactly one of classes (multi-class classification).
In multi-label classification, each example can have multiple positive labels (e.g., a news article tagged as both "politics" and "international"). Binary cross-entropy applies independently to each label, computing separate losses and summing them. The key distinction is that the outputs do not need to sum to 1, and each output is trained independently.
Weighted Cross-Entropy
Class imbalance is one of the most pervasive problems in NLP. Named entity recognition datasets might have 95% non-entity tokens. Sentiment datasets might have 80% neutral examples. Toxicity classifiers deal with much more benign text than harmful text. In these settings, an unweighted cross-entropy loss will cause the model to learn to predict the majority class almost all the time, achieving low loss while being useless for the rare classes of interest.
Weighted cross-entropy assigns a higher loss multiplier to underrepresented classes:
where:
- : the weight for class , typically set to the inverse frequency of class in the training set
- : the one-hot target (1 for true class, 0 otherwise)
- : the predicted probability for class
A standard heuristic for setting weights is:
where is the total number of training examples and is the number of examples in class . This ensures that each class contributes equally to the total loss in expectation, regardless of its frequency. In PyTorch, you can pass a weight tensor directly to F.cross_entropy().