A classifier may predict a 90% probability that an email is spam. Another classifier may predict 55%. Both could assign the same final label, yet they express very different degrees of confidence. To train and evaluate such systems, we need mathematical tools that describe uncertainty, predictive disagreement, and differences between probability distributions.
Three closely related concepts provide these tools: entropy, cross-entropy, and Kullback–Leibler (KL) divergence. They appear in classification losses, probabilistic modeling, language models, knowledge distillation, and other areas of artificial intelligence.
This article assumes familiarity with basic probability distributions from Probability and Bayes’ Theorem, and connects these quantities to optimization in Optimization and Gradient Descent.
Start with two predictions
Imagine two weather models. Model A predicts a 50% chance of rain and 50% chance of no rain. Model B predicts a 95% chance of rain and 5% chance of no rain. Model A is much less certain. Entropy gives us a way to measure that uncertainty within a probability distribution.
Now imagine it actually rains. How should we judge the models’ predictions? A model assigning high probability to the outcome that occurred receives a smaller log loss than one assigning low probability. Cross-entropy captures this idea across outcomes or examples when the target distribution is specified.
Finally, imagine that you have two complete probability distributions, perhaps one produced by a reference model and one produced by a new model. KL divergence measures how much the second distribution differs from the first in a particular directed, information-theoretic sense. Unlike ordinary distance, KL divergence is generally not symmetric.
These three concepts are connected, but they answer different questions:
| Quantity | Question |
|---|---|
| Entropy | How uncertain is a distribution? |
| Cross-entropy | How surprising are outcomes from a target distribution under another distribution’s probabilities? |
| KL divergence | How much does one probability distribution differ from a reference distribution, in the chosen direction? |
The equations later in the article make these ideas precise. The intuition comes first: uncertainty, predictive mismatch, and distributional difference.
Probability distributions and information
A probability distribution assigns probabilities to possible outcomes. For a discrete random variable with possible values , its probabilities satisfy:
Consider two models describing the next outcome of a three-way event:
| Outcome | Distribution A | Distribution B |
|---|---|---|
| Red | 0.80 | 0.34 |
| Blue | 0.10 | 0.33 |
| Green | 0.10 | 0.33 |
Distribution A strongly favors red. Distribution B is almost uniform. Although both are valid distributions, B expresses greater uncertainty about which outcome will occur.
Information theory gives a way to quantify this distinction.
Self-information: how surprising is an event?
The self-information (or surprisal) of an event with probability is:
A common event conveys less surprising information than a rare one:
- If , then bits: the event was certain.
- If , then bit.
- If , then bits.
The minus sign makes the result nonnegative for probabilities in . An event with probability zero has infinite surprisal in the limiting sense, although such an event cannot occur under the stated distribution.
Logarithm base matters: base 2 gives information in bits; the natural logarithm gives nats. In many machine-learning losses, natural logarithms are used. Changing the base rescales these quantities but does not change which prediction is better.
Entropy: average uncertainty
Shannon entropy is the expected self-information of a random variable. For a discrete distribution , it is:
The convention is used, justified by the limit as the probability approaches zero.
Entropy depends on an entire distribution, not just the probability of a single outcome. It measures the average uncertainty associated with drawing an outcome from that distribution.
A worked example: biased and fair coins
Let represent the result of a coin toss.
For a fair coin, :
For a biased coin with and :
The highly biased coin is more predictable, so its entropy is lower. A coin that always lands heads has zero entropy.
Properties of discrete entropy
For a finite distribution over outcomes, entropy has several useful properties:
- Nonnegative: .
- Zero for a certain outcome: if one outcome has probability 1, entropy is zero.
- Largest for a uniform distribution: entropy is maximized when all outcomes have probability .
- Maximum value: using base-2 logarithms, bits.
- Depends on probabilities, not labels: renaming outcomes does not change entropy.
High entropy is not inherently bad. It can represent real uncertainty in a difficult problem. Similarly, a low-entropy model prediction is not necessarily accurate: a model can be confidently wrong.
Entropy in decision trees
Some decision-tree learning algorithms use entropy to evaluate how mixed the class labels are in a node. A split can be preferred when it reduces the weighted average entropy of the child nodes.
The reduction is called information gain:
where is the target class and denotes the information supplied by a split. A split is useful when knowing its outcome reduces uncertainty about the target. Not all decision-tree algorithms use entropy; others use criteria such as Gini impurity.
Cross-entropy: evaluating predictions against a target
Entropy measures uncertainty within one distribution. Cross-entropy measures the average surprise when outcomes are drawn from a target distribution but evaluated using predicted probabilities .
For discrete distributions:
Here:
- is the target or reference distribution.
- is the predicted distribution.
- The sum uses target probabilities as weights.
When places low probability on an outcome that is likely under , cross-entropy becomes large. It is not symmetric: generally, .
If but for any outcome, cross-entropy is infinite. Numerical implementations avoid computing directly and often work with logits using stable mathematical transformations.
Cross-entropy for multiclass classification
In a classification problem with one correct class, the target is commonly represented as a one-hot distribution. If the correct class is class 2 out of three classes:
Suppose the model predicts:
Cross-entropy with natural logarithms is:
Because the target is one-hot, only the predicted probability of the correct class contributes. Predicting for that class gives a smaller loss of approximately ; predicting gives a much larger loss of approximately .
The final predicted label may remain unchanged while the loss changes considerably. This is why cross-entropy can distinguish models that have the same classification accuracy.
Binary cross-entropy
For binary classification, let be the correct label and the predicted probability of class 1. Binary cross-entropy for one example is:
This becomes:
- when the actual label is 1.
- when the actual label is 0.
A model is penalized most heavily when it assigns high confidence to the wrong outcome.
| True label | Predicted probability of class 1 | Binary cross-entropy (nats) |
|---|---|---|
| 1 | 0.90 | 0.105 |
| 1 | 0.50 | 0.693 |
| 1 | 0.10 | 2.303 |
| 0 | 0.10 | 0.105 |
| 0 | 0.90 | 2.303 |
In practice, a training loss is often the mean cross-entropy over a batch of examples. Reduction choices matter: some implementations return a sum, others a mean, so numerical loss values may not be directly comparable without checking the convention.
KL divergence: comparing two distributions
Kullback–Leibler divergence, written , measures the difference between a reference probability distribution and another distribution in terms of expected log-probability ratio:
It can also be understood as the extra expected code length incurred by using a code designed for when the data actually follow , under suitable coding assumptions.
KL divergence has three important properties:
- It is nonnegative: .
- It equals zero when the two distributions agree on the relevant support (and, for valid distributions, this means they are the same distribution).
- It is not generally symmetric: .
KL divergence is not a mathematical distance metric. In particular, it is asymmetric and does not satisfy the triangle inequality.
If and for an outcome, the divergence is infinite.
Worked example
Suppose a reference distribution is:
and a model predicts:
Using natural logarithms:
The divergence is relatively small because the predicted probabilities are not far from the reference probabilities. Reversing the distributions gives a different value:
This difference illustrates why the order of the arguments must be explicit.
How entropy, cross-entropy, and KL divergence connect
These quantities are not three unrelated formulas. With the same logarithm base and suitable support assumptions, they satisfy:
Equivalently:
A derivation follows from splitting the logarithm of the probability ratio:
The identity explains why minimizing cross-entropy with respect to model predictions also minimizes when the target distribution is fixed. The entropy term does not depend on the model parameters.
| Quantity | Formula | Main question |
|---|---|---|
| Entropy | How uncertain is the target distribution? | |
| Cross-entropy | How costly are predictions when outcomes follow ? | |
| KL divergence | How much does differ from the reference ? |
Terminology caution: In some ML discussions, cross-entropy loss refers to an average negative log-likelihood computed from labeled examples. That usage is closely related to the theoretical cross-entropy of distributions, but a finite dataset provides only an empirical estimate of population behavior.
Why cross-entropy is used for training classifiers
A classifier can produce logits, which are unnormalized numerical scores for each class. The softmax function converts logits to a probability distribution:
Cross-entropy then penalizes predicted probabilities that disagree with the labels. The parameters of the classifier are adjusted to reduce this loss using optimization algorithms such as gradient descent.
For a one-hot target and softmax outputs , a particularly useful gradient identity is:
This relationship helps explain the widespread pairing of softmax outputs and cross-entropy objectives. In real frameworks, numerically stable cross-entropy functions usually accept logits directly; applying softmax manually before a logits-based loss is often incorrect.
Training for a lower cross-entropy loss does not automatically guarantee good real-world performance or well-calibrated probabilities. Data quality, train/test separation, distribution shifts, model design, and evaluation all matter.
A NumPy example
The following runnable example calculates entropy, cross-entropy, and KL divergence for finite discrete distributions with strictly positive probabilities.
import numpy as np
def entropy(p):
p = np.asarray(p, dtype=float)
return -np.sum(p * np.log(p))
def cross_entropy(p, q):
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
return -np.sum(p * np.log(q))
def kl_divergence(p, q):
p = np.asarray(p, dtype=float)
q = np.asarray(q, dtype=float)
return np.sum(p * np.log(p / q))
p = np.array([0.8, 0.2])
q = np.array([0.6, 0.4])
print(f"Entropy H(p): {entropy(p):.4f}")
print(f"Cross-entropy H(p,q): {cross_entropy(p, q):.4f}")
print(f"KL divergence D_KL(p||q): {kl_divergence(p, q):.4f}")
print(f"Check identity: {cross_entropy(p, q) - entropy(p):.4f}")
Expected output (in nats):
Entropy H(p): 0.5004
Cross-entropy H(p,q): 0.5919
KL divergence D_KL(p||q): 0.0915
Check identity: 0.0915
For production applications, the functions above need additional checks for normalization, zero probabilities, and numerical stability. Libraries such as PyTorch and SciPy provide tested implementations suitable for broader use.
Applications in artificial intelligence
Classification and neural networks
Cross-entropy is a common training objective for binary and multiclass classifiers, including neural networks. It rewards higher probability for correct labels and strongly penalizes confident mistakes.
Language modeling
A language model assigns probabilities to possible next tokens. During next-token training, negative log-likelihood measures how much probability the model assigns to the actual token. Average token-level cross-entropy is therefore a central training measurement.
Perplexity is closely related. When cross-entropy uses natural logarithms and is averaged over tokens, perplexity is:
For base-2 entropy, the equivalent expression is . Perplexity is sensitive to tokenization and evaluation setup, so results from different tokenizers are not automatically comparable.
Knowledge distillation
A smaller student model can be trained to imitate a larger teacher model by comparing their output probability distributions. KL divergence is one common way to quantify the disagreement. The precise direction of KL divergence, use of softened probabilities, and temperature scaling depend on the training method.
Variational inference and generative modeling
KL divergence occurs in probabilistic modeling, especially when an approximate distribution is compared with a reference distribution. Variational autoencoders (VAEs), for instance, commonly include a KL term that regularizes an approximate latent distribution toward a chosen prior.
Decision trees and feature selection
Entropy and information gain can help assess whether a decision-tree split reduces uncertainty about labels. Information theory also underlies mutual information measures used in feature selection.
Common misconceptions
“Entropy measures how inaccurate a model is.” Not generally. Entropy measures uncertainty in a distribution. It does not require true labels or a prediction error.
“Cross-entropy and KL divergence are always identical.” No. They differ by the entropy of the target distribution. For a fixed target , minimizing one with respect to also minimizes the other, but their numerical values need not match.
“KL divergence is a distance.” No. It is asymmetric and need not obey the triangle inequality.
“Low entropy means the model is correct.” No. A prediction can have low entropy because it is very confident, even when wrong.
“A probability of zero is harmless in the logarithm.” No. If a predicted distribution assigns probability zero to an outcome with positive target probability, the relevant cross-entropy and KL divergence are infinite.
“Cross-entropy only applies to neural networks.” No. It is an information-theoretic quantity that can be used with any suitable probabilistic prediction method.
Practice questions
- Which distribution has greater entropy: or ? Why?
- For a one-hot classification target, what does multiclass cross-entropy simplify to?
- What happens to cross-entropy when a model assigns probability zero to the correct class?
- Why does minimizing cross-entropy also minimize when is fixed?
- Why is not a standard distance metric?
- If two classifiers predict the same label but assign different probabilities, can their cross-entropy losses differ?
Show worked answers
- has greater entropy because its outcomes are equally likely and therefore harder to predict.
- It becomes the negative log-probability of the correct class, .
- It becomes infinite mathematically, so implementations need numerically stable handling.
- Because and stays constant while changing .
- It is generally asymmetric and does not satisfy the triangle inequality.
- Yes. Cross-entropy depends on the probability assigned to the correct class, not just the final predicted label.
Related concepts
- Probability and Bayes’ Theorem introduces probability distributions and conditional probability.
- Descriptive and Inferential Statistics explains how data samples support estimation and evaluation.
- Optimization and Gradient Descent explains how machine-learning algorithms minimize loss functions.
- Linear and Logistic Regression applies probabilistic prediction to classical supervised learning.
- Model Training, Overfitting, and Generalization connects loss minimization to out-of-sample performance.
- Training Neural Networks: Loss, Optimizers, and Regularization develops neural-network training techniques.
- Transformers and Attention Mechanisms provides background for modern language models.
- AI Knowledge Map places this topic within the complete PlainCS curriculum.
References and further reading
- Elements of Information Theory, Wiley — foundational treatment of entropy, coding, and relative entropy.
- Deep Learning, Chapter 3: Probability and Information Theory — information-theoretic concepts in machine learning.
- Google Machine Learning Crash Course — classification and loss-function fundamentals.
- PyTorch CrossEntropyLoss documentation — cross-entropy loss and logits in practical deep learning.
- SciPy entropy documentation — computational entropy and relative entropy.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.