Artificial Intelligence • Mathematical Foundations • 14 min read

Entropy, Cross-Entropy, and KL Divergence

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:

QuantityQuestion
EntropyHow uncertain is a distribution?
Cross-entropyHow surprising are outcomes from a target distribution under another distribution’s probabilities?
KL divergenceHow 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 XX with possible values x1,…,xnx_1,\ldots,x_n, its probabilities satisfy:

p(xi)≥0,∑i=1np(xi)=1.p(x_i)\ge 0, \qquad \sum_{i=1}^{n} p(x_i)=1.

Consider two models describing the next outcome of a three-way event:

OutcomeDistribution ADistribution B
Red0.800.34
Blue0.100.33
Green0.100.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 xx with probability p(x)p(x) is:

I(x)=−log⁡2p(x).I(x)=-\log_2 p(x).

A common event conveys less surprising information than a rare one:

  • If p(x)=1p(x)=1, then I(x)=0I(x)=0 bits: the event was certain.
  • If p(x)=1/2p(x)=1/2, then I(x)=1I(x)=1 bit.
  • If p(x)=1/8p(x)=1/8, then I(x)=3I(x)=3 bits.

The minus sign makes the result nonnegative for probabilities in (0,1](0,1]. 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 ln⁡\ln 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 pp, it is:

H(p)=−∑i=1np(xi)log⁡p(xi).H(p)=-\sum_{i=1}^{n}p(x_i)\log p(x_i).

The convention 0log⁡0=00\log 0=0 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 XX represent the result of a coin toss.

For a fair coin, p(H)=p(T)=0.5p(H)=p(T)=0.5:

H(X)=−0.5log⁡2(0.5)−0.5log⁡2(0.5)=1 bit.H(X)=-0.5\log_2(0.5)-0.5\log_2(0.5)=1\text{ bit}.

For a biased coin with p(H)=0.9p(H)=0.9 and p(T)=0.1p(T)=0.1:

H(X)=−0.9log⁡2(0.9)−0.1log⁡2(0.1)≈0.469 bits.H(X)=-0.9\log_2(0.9)-0.1\log_2(0.1) \approx 0.469\text{ bits}.

The highly biased coin is more predictable, so its entropy is lower. A coin that always lands heads has zero entropy.

Comparison of outcome probabilities for fair and biased coins, showing that the fair coin has higher entropy
The fair coin has greater uncertainty because its two outcomes are equally likely.

Properties of discrete entropy

For a finite distribution over nn outcomes, entropy has several useful properties:

  • Nonnegative: H(p)≥0H(p)\ge 0.
  • Zero for a certain outcome: if one outcome has probability 1, entropy is zero.
  • Largest for a uniform distribution: entropy is maximized when all nn outcomes have probability 1/n1/n.
  • Maximum value: using base-2 logarithms, H(p)≤log⁡2nH(p)\le\log_2 n 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:

IG=H(Y)−H(Y∣S),IG = H(Y)-H(Y\mid S),

where YY is the target class and SS 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 pp but evaluated using predicted probabilities qq.

For discrete distributions:

H(p,q)=−∑i=1np(xi)log⁡q(xi).H(p,q)=-\sum_{i=1}^{n}p(x_i)\log q(x_i).

Here:

  • pp is the target or reference distribution.
  • qq is the predicted distribution.
  • The sum uses target probabilities as weights.

When qq places low probability on an outcome that is likely under pp, cross-entropy becomes large. It is not symmetric: generally, H(p,q)≠H(q,p)H(p,q)\neq H(q,p).

If p(x)>0p(x)>0 but q(x)=0q(x)=0 for any outcome, cross-entropy is infinite. Numerical implementations avoid computing log⁡0\log 0 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:

p=(0,1,0).p=(0,1,0).

Suppose the model predicts:

q=(0.10,0.70,0.20).q=(0.10,0.70,0.20).

Cross-entropy with natural logarithms is:

H(p,q)=−(0ln⁡0.10+1ln⁡0.70+0ln⁡0.20)=−ln⁡(0.70)≈0.357.H(p,q)=-(0\ln 0.10+1\ln 0.70+0\ln 0.20) =-\ln(0.70)\approx 0.357.

Because the target is one-hot, only the predicted probability of the correct class contributes. Predicting 0.950.95 for that class gives a smaller loss of approximately 0.0510.051; predicting 0.050.05 gives a much larger loss of approximately 2.9962.996.

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 y∈{0,1}y\in\{0,1\} be the correct label and p^\hat p the predicted probability of class 1. Binary cross-entropy for one example is:

L(y,p^)=−[yln⁡(p^)+(1−y)ln⁡(1−p^)].L(y,\hat p)=-\left[y\ln(\hat p)+(1-y)\ln(1-\hat p)\right].

This becomes:

  • −ln⁡(p^)-\ln(\hat p) when the actual label is 1.
  • −ln⁡(1−p^)-\ln(1-\hat p) when the actual label is 0.

A model is penalized most heavily when it assigns high confidence to the wrong outcome.

True labelPredicted probability of class 1Binary cross-entropy (nats)
10.900.105
10.500.693
10.102.303
00.100.105
00.902.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 DKL(p∥q)D_{\mathrm{KL}}(p\|q), measures the difference between a reference probability distribution pp and another distribution qq in terms of expected log-probability ratio:

DKL(p∥q)=∑i=1np(xi)log⁡p(xi)q(xi).D_{\mathrm{KL}}(p\|q)=\sum_{i=1}^{n}p(x_i)\log\frac{p(x_i)}{q(x_i)}.

It can also be understood as the extra expected code length incurred by using a code designed for qq when the data actually follow pp, under suitable coding assumptions.

KL divergence has three important properties:

  1. It is nonnegative: DKL(p∥q)≥0D_{\mathrm{KL}}(p\|q)\ge0.
  2. It equals zero when the two distributions agree on the relevant support (and, for valid distributions, this means they are the same distribution).
  3. It is not generally symmetric: DKL(p∥q)≠DKL(q∥p)D_{\mathrm{KL}}(p\|q)\neq D_{\mathrm{KL}}(q\|p).

KL divergence is not a mathematical distance metric. In particular, it is asymmetric and does not satisfy the triangle inequality.

If p(x)>0p(x)>0 and q(x)=0q(x)=0 for an outcome, the divergence is infinite.

Worked example

Suppose a reference distribution is:

p=(0.8,0.2)p=(0.8,0.2)

and a model predicts:

q=(0.6,0.4).q=(0.6,0.4).

Using natural logarithms:

DKL(p∥q)=0.8ln⁡0.80.6+0.2ln⁡0.20.4≈0.0915 nats.\begin{aligned} D_{\mathrm{KL}}(p\|q) &=0.8\ln\frac{0.8}{0.6}+0.2\ln\frac{0.2}{0.4}\\ &\approx 0.0915\text{ nats}. \end{aligned}

The divergence is relatively small because the predicted probabilities are not far from the reference probabilities. Reversing the distributions gives a different value:

DKL(q∥p)≈0.1046 nats.D_{\mathrm{KL}}(q\|p)\approx 0.1046\text{ nats}.

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:

H(p,q)=H(p)+DKL(p∥q).\boxed{H(p,q)=H(p)+D_{\mathrm{KL}}(p\|q)}.

Equivalently:

DKL(p∥q)=H(p,q)−H(p).D_{\mathrm{KL}}(p\|q)=H(p,q)-H(p).

A derivation follows from splitting the logarithm of the probability ratio:

DKL(p∥q)=∑ipilog⁡piqi=∑ipilog⁡pi−∑ipilog⁡qi=−H(p)+H(p,q).\begin{aligned} D_{\mathrm{KL}}(p\|q) &=\sum_i p_i\log\frac{p_i}{q_i}\\ &=\sum_i p_i\log p_i-\sum_i p_i\log q_i\\ &=-H(p)+H(p,q). \end{aligned}
Relationship between cross-entropy, entropy, and KL divergence
Cross-entropy combines the target's intrinsic uncertainty with the additional penalty for predicting the wrong distribution.

The identity explains why minimizing cross-entropy with respect to model predictions qq also minimizes DKL(p∥q)D_{\mathrm{KL}}(p\|q) when the target distribution pp is fixed. The entropy term H(p)H(p) does not depend on the model parameters.

QuantityFormulaMain question
Entropy−∑pilog⁡pi-\sum p_i\log p_iHow uncertain is the target distribution?
Cross-entropy−∑pilog⁡qi-\sum p_i\log q_iHow costly are predictions qq when outcomes follow pp?
KL divergence∑pilog⁡(pi/qi)\sum p_i\log(p_i/q_i)How much does qq differ from the reference pp?

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 z1,…,zKz_1,\ldots,z_K to a probability distribution:

qi=ezi∑j=1Kezj.q_i=\frac{e^{z_i}}{\sum_{j=1}^{K}e^{z_j}}.

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 yy and softmax outputs qq, a particularly useful gradient identity is:

∂L∂zi=qi−yi.\frac{\partial L}{\partial z_i}=q_i-y_i.

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:

PPL⁡=eH.\operatorname{PPL}=e^{H}.

For base-2 entropy, the equivalent expression is 2H2^H. 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 pp, minimizing one with respect to qq 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

  1. Which distribution has greater entropy: (0.5,0.5)(0.5,0.5) or (0.99,0.01)(0.99,0.01)? Why?
  2. For a one-hot classification target, what does multiclass cross-entropy simplify to?
  3. What happens to cross-entropy when a model assigns probability zero to the correct class?
  4. Why does minimizing cross-entropy also minimize DKL(p∥q)D_{\mathrm{KL}}(p\|q) when pp is fixed?
  5. Why is DKL(p∥q)D_{\mathrm{KL}}(p\|q) not a standard distance metric?
  6. If two classifiers predict the same label but assign different probabilities, can their cross-entropy losses differ?
Show worked answers
  1. (0.5,0.5)(0.5,0.5) has greater entropy because its outcomes are equally likely and therefore harder to predict.
  2. It becomes the negative log-probability of the correct class, −log⁡qcorrect-\log q_{\text{correct}}.
  3. It becomes infinite mathematically, so implementations need numerically stable handling.
  4. Because H(p,q)=H(p)+DKL(p∥q)H(p,q)=H(p)+D_{\mathrm{KL}}(p\|q) and H(p)H(p) stays constant while changing qq.
  5. It is generally asymmetric and does not satisfy the triangle inequality.
  6. Yes. Cross-entropy depends on the probability assigned to the correct class, not just the final predicted label.

References and further reading

Related articles in

Image preview

Fit