Mathematical Foundations

VII.5 · Information Theory

Why does comparison depend on direction?

Inspect signed KL terms, reverse the source and prediction, and connect the divergence to excess cross entropy over source entropy.

Which direction are you comparing?

Explorer: Ordered classes: source P, prediction Q
ClassExact PExact QCE termKL term
10.50.25≈ 0.693147≈ 0.346574
20.250.5≈ 0.173287≈ -0.173287
30.250.25≈ 0.346574≈ 0
Actual signed KL contributions (nats)
  1. Class 1: ≈ 0.346574
  2. Class 2: ≈ -0.173287
  3. Class 3: ≈ 0

Bar length = absolute contribution on a shared scale; sign and infinities appear in the labels.

Direction P || Q. Forward KL ≈ 0.173287; reverse KL ≈ 0.173287 nats. KL is generally asymmetric and is not a metric. Non-negativity follows from the log inequality, not from the plot.

Forward divergence (nats)
0.173287
Reverse divergence (nats)
0.173287
Selected direction: P || Q
0.173287
Selected cross entropy
1.213008
Selected source entropy
1.039721
Finite identity roundoff residual
−2.77556×10⁻¹⁷

= exact rational or mathematical boundary · ≈ approximate binary64 evaluation

P is the fixed target (1/2,1/4,1/4). Edit Q’s nonnegative integer weights; Q is normalized openly. The one-hot option explicitly replaces P by an observed label.

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

Direction P || Q. Forward KL ≈ 0.173287; reverse KL ≈ 0.173287 nats. KL is generally asymmetric and is not a metric. Non-negativity follows from the log inequality, not from the plot.

DKL(P∥Q)=∑ipilog⁡(pi/qi)=H(P,Q)−H(P)D_{\mathrm{KL}}(P\|Q)=\sum_i p_i\log(p_i/q_i)=H(P,Q)-H(P)
pi=0⇒term=0pi>0, qi=0⇒+∞p_i=0\Rightarrow\text{term}=0\qquad p_i>0,\ q_i=0\Rightarrow+\infty

Name the ordered distributions

Fixed P [0.5, 0.25, 0.25]; normalized prediction Q [0.25, 0.5, 0.25]. Selected source P, prediction Q.

∑ipi=∑iqi=1\sum_i p_i=\sum_i q_i=1

Inspect signed KL terms, reverse the source and prediction, and connect the divergence to excess cross entropy over source entropy.

Intuition

A prediction can place mass on an outcome absent from the source without being penalized there in the forward direction. Reversing the comparison changes which outcomes are weighted and which zero probabilities are fatal. Two tables with the same labels can therefore produce very different losses.

Definition

For normalized P and Q on a common finite support, DKL(P∥Q)=∑ipilog⁡(pi/qi)D_{\mathrm{KL}}(P\|Q)=\sum_i p_i\log(p_i/q_i). A p=0 term contributes zero without evaluating a ratio; p>0 and q=0 gives +∞. Natural logs give nats; base-2 logs give bits. KL is generally asymmetric and is not a distance metric.

Mechanics

P is fixed and Q is normalized from the editable weights. Both forward and reverse totals stay visible. Show Q || P deliberately changes the selected source, prediction, signed terms and entropy baseline. The selected identity residual checks finite floating-point evaluations without attempting infinity minus infinity.

Derivation

Expand the log ratio: ∑ipilog⁡(pi/qi)=∑ipilog⁡pi−∑ipilog⁡qi=H(P,Q)−H(P)\sum_i p_i\log(p_i/q_i)=\sum_i p_i\log p_i-\sum_i p_i\log q_i=H(P,Q)-H(P). For non-negativity, assume Q is positive wherever P is positive. The inequality log⁡t≤t−1\log t\le t-1 gives −D=∑pi>0pilog⁡(qi/pi)≤∑pi>0(qi−pi)≤0-D=\sum_{p_i>0}p_i\log(q_i/p_i)\le\sum_{p_i>0}(q_i-p_i)\le0. Equality requires every positive-source ratio qᵢ/pᵢ=1 and no Q mass outside the source support, hence P=Q. If support is mismatched, D=+∞ and the inequality still holds. This derivation is independent of numerical examples.

Worked examples

For P=(1/2,1/4,1/4), Q=(1/4,1/2,1/4), signed bit terms are (1/2,−1/4,0), totaling 1/4 bit; cross entropy 7/4 minus entropy 3/2 agrees. For P=(1,0), Q=(1/2,1/2), forward KL is 1 bit and reverse is infinite. With Bernoulli P=(.1,.9), Q=(.2,.8), R=(.3,.7), D(P∥R)≈.116322D(P\|R)\approx.116322 exceeds D(P∥Q)+D(Q∥R)≈.062423D(P\|Q)+D(Q\|R)\approx.062423 nats, violating the triangle inequality.

Worked example: Which direction are you comparing?

Worked example: Ordered classes: source P, prediction Q
ClassExact PExact QCE termKL term
10.50.25≈ 0.693147≈ 0.346574
20.250.5≈ 0.173287≈ -0.173287
30.250.25≈ 0.346574≈ 0
Actual signed KL contributions (nats)
  1. Class 1: ≈ 0.346574
  2. Class 2: ≈ -0.173287
  3. Class 3: ≈ 0

Bar length = absolute contribution on a shared scale; sign and infinities appear in the labels.

Direction P || Q. Forward KL ≈ 0.173287; reverse KL ≈ 0.173287 nats. KL is generally asymmetric and is not a metric. Non-negativity follows from the log inequality, not from the plot.

Forward divergence (nats)
0.173287
Reverse divergence (nats)
0.173287
Selected direction: P || Q
0.173287
Selected cross entropy
1.213008
Selected source entropy
1.039721
Finite identity roundoff residual
−2.77556×10⁻¹⁷

= exact rational or mathematical boundary · ≈ approximate binary64 evaluation

P is the fixed target (1/2,1/4,1/4). Edit Q’s nonnegative integer weights; Q is normalized openly. The one-hot option explicitly replaces P by an observed label.

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

Direction P || Q. Forward KL ≈ 0.173287; reverse KL ≈ 0.173287 nats. KL is generally asymmetric and is not a metric. Non-negativity follows from the log inequality, not from the plot.

DKL(P∥Q)=∑ipilog⁡(pi/qi)=H(P,Q)−H(P)D_{\mathrm{KL}}(P\|Q)=\sum_i p_i\log(p_i/q_i)=H(P,Q)-H(P)
pi=0⇒term=0pi>0, qi=0⇒+∞p_i=0\Rightarrow\text{term}=0\qquad p_i>0,\ q_i=0\Rightarrow+\infty

Name the ordered distributions

Fixed P [0.5, 0.25, 0.25]; normalized prediction Q [0.25, 0.5, 0.25]. Selected source P, prediction Q.

∑ipi=∑iqi=1\sum_i p_i=\sum_i q_i=1

Replay the named distributions, actual contribution terms and summed loss.

Executable reference code

The pedagogical version keeps exact source masses and branches on support. The NumPy version uses masks before logarithms and ratios. Both files include assertions for the hand-worked examples.

code/python/information_kl.py
"""Exact sources and direction-sensitive KL; preserve signed contribution terms."""
from fractions import Fraction as F
from math import log,inf,fsum
def kl(p,q,unit='nats'):
    p=[F(str(x)) for x in p];q=[F(str(x)) for x in q]
    if not 1<=len(p)<=6 or len(p)!=len(q) or any(x<0 for x in p+q) or sum(p)!=1 or sum(q)!=1 or unit not in ('bits','nats'):raise ValueError('Same support; normalized distributions')
    terms=[]
    for a,b in zip(p,q):
        if not a:terms.append(0.0)
        elif not b:terms.append(inf)
        else:
            ratio=a/b
            terms.append(float(a)*(log(ratio.numerator)-log(ratio.denominator))/(log(2) if unit=='bits' else 1))
    return terms,fsum(terms)
if __name__=='__main__':
    assert kl([1,0],['1/2','1/2'],'bits')[1]==1
    assert kl(['1/2','1/2'],[1,0],'bits')[1]==inf
    assert kl(['1/2','1/2'],['1/2','1/2'])[1]==0
    print(kl(['1/2','1/4','1/4'],['1/4','1/2','1/4']))
code/python/information_kl_numpy.py
"""NumPy KL without ever evaluating zero divided by zero."""
import numpy as np
def kl(p,q,unit='nats'):
    p=np.asarray(p,dtype=float);q=np.asarray(q,dtype=float)
    if p.ndim!=1 or not 1<=p.size<=6 or p.shape!=q.shape or not np.all(np.isfinite(p)) or not np.all(np.isfinite(q)) or np.any(p<0) or np.any(q<0) or abs(p.sum()-1)>1e-12 or abs(q.sum()-1)>1e-12 or unit not in ('bits','nats'):raise ValueError('Normalized finite distributions')
    terms=np.zeros_like(p);positive=p>0
    with np.errstate(divide='ignore'):terms[positive]=p[positive]*(np.log(p[positive])-np.log(q[positive]))/(np.log(2) if unit=='bits' else 1)
    return terms,float(terms.sum())
if __name__=='__main__':
    assert kl([1,0],[.5,.5],'bits')[1]==1
    assert kl([.5,.5],[1,0])[1]==np.inf
    assert kl([.5,.5],[.5,.5])[1]==0
    print(kl([.5,.25,.25],[.25,.5,.25]))

Explore

Compare the canonical forward and reverse values, then choose Unequal forward / reverse and change individual Q weights. Use Zero predicted true-class mass and inspect which direction becomes infinite. Finally choose Q equals P and verify zero divergence without zeroing the entropy.

Common mistakes and counterexamples

Individual KL terms can be negative; the complete normalized sum is nonnegative. KL is not an entropy and is not a metric: it lacks symmetry and the triangle inequality. Zero/zero must be skipped before division. Comparing reversed arguments requires reversing the entropy baseline as well.

Numerical considerations

Exact rational masses and support decisions are preserved. Positive rational ratios are formed exactly before their approximate logarithm is taken. For an independent numerical comparison of finite cases, use 100-digit Decimal log differences and separately total CE−H. Finite results and identity residuals use a 2e−12 scaled absolute/relative budget. Tiny signed rounding residuals are not a mathematical violation of non-negativity; no sampled plot is a proof.

Engineering and ML connections

Expected prediction log loss is minimized by predicting P itself: cross entropy equals H(P) plus nonnegative KL. This connects probabilistic training loss with information mismatch. Direction remains essential in inference and model approximation; a symmetric-looking picture cannot make it a distance.

Continue from the preceding information-theory mechanism.

Exercises

Compute actual terms and distinguish direction, support and observation from expectation.

calculation

Excess log loss

Suppose H(P,Q)=5/2 bits and H(P)=3/2 bits. Find D(P||Q).

calculation

Equality

Find D(P||P) for P=(1/2,1/4,1/4).

prediction

Direction changes support

P=(1,0), Q=(1/2,1/2). Which ordered pair gives forward and reverse KL in bits?

Choose one answer

explanation

Signed terms

Can an individual pᵢlog(pᵢ/qᵢ) term be negative?

Choose one answer

construction

Metric counterexample

Why should a caller not treat KL as a distance metric?

Choose one answer

Summary and checkpoints

A prediction can place mass on an outcome absent from the source without being penalized there in the forward direction. Reversing the comparison changes which outcomes are weighted and which zero probabilities are fatal. Two tables with the same labels can therefore produce very different losses. Always name the source and prediction before interpreting a loss.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available