From Thermodynamics to ML: Entropy, KL and Mutual Info

Entropy, KL divergence and mutual information from first principles, with mode-seeking vs mean-seeking Python demos.

Cover Image for From Thermodynamics to ML: Entropy, KL and Mutual Info

I recently finished Carlo Rovelli's The Order of Time. Rovelli is a physicist working on quantum gravity, and the book argues that the arrow of time we feel so intuitively is not a fundamental feature of the universe. The microscopic laws of physics are reversible. Time feels one-directional because of entropy: in a closed system, disorder overwhelmingly tends to increase, and we experience that statistical tendency as the flow of time.

Entropy also appears whenever a classifier assigns probabilities or a decision tree chooses a split. Boltzmann counts possible microstates, while Shannon measures uncertainty in bits. Minimising cross-entropy gives the same parameter estimate as maximising likelihood. We derive the parallel and use KL divergence and mutual information to compare distributions and shared information.

Quick Win: Entropy of a Coin

Open the notebook and run the first few cells. We'll start with the simplest possible example: the entropy of a biased coin.

Open In Colab

import numpy as np
import matplotlib.pyplot as plt

p = np.linspace(1e-6, 1 - 1e-6, 400)
H = -(p * np.log2(p) + (1 - p) * np.log2(1 - p))

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(p, H, linewidth=2.5)
ax.set_xlabel("Bias p")
ax.set_ylabel("Entropy H(p) [bits]")
plt.show()

Shannon entropy of a Bernoulli coin, peaking at 1 bit when p = 0.5

A fair coin (p=0.5p = 0.5) is maximally uncertain and needs exactly 1 bit per toss to transmit. A heavily biased coin (p=0.99p = 0.99) is almost predictable and needs far less. Entropy is just the average number of bits you need to encode outcomes drawn from a distribution, assuming you use the best possible code.

What Just Happened?

Shannon entropy for a discrete distribution is:

H[x]=−∑ip(xi)log⁡2p(xi)H[x] = -\sum_i p(x_i) \log_2 p(x_i)

The −log⁡2p(xi)-\log_2 p(x_i) term is the information content of outcome xix_i: rare events carry more bits of surprise, common events carry fewer. Entropy averages that surprise over the distribution.

The link to Boltzmann is explicit. Consider N identical objects divided among bins so that bin ii contains nin_i objects. The number of microstates consistent with that macrostate is the multinomial coefficient W=N!/∏ini!W = N!/\prod_i n_i!. Take the log, apply Stirling, and divide by N:

H=lim⁡N→∞1Nln⁡W=−∑ipiln⁡piH = \lim_{N \to \infty} \frac{1}{N} \ln W = -\sum_i p_i \ln p_i

Boltzmann's S=kln⁡WS = k \ln W (carved on his tombstone) and Shannon's H=−∑pln⁡pH = -\sum p \ln p are the same formula up to a constant. Both count the log number of arrangements consistent with what you observe.

The Continuous Version

For a continuous density, entropy becomes an integral:

H[x]=−∫p(x)ln⁡p(x) dxH[x] = -\int p(x) \ln p(x) \, dx

This is called differential entropy. It has one quirk: unlike discrete entropy, it can be negative. For a Gaussian with variance σ2\sigma^2, there is a neat closed form:

H[x]=12(1+ln⁡(2πσ2))H[x] = \frac{1}{2} \left( 1 + \ln(2\pi\sigma^2) \right)

Gaussian differential entropy vs standard deviation, becoming negative for very narrow distributions

Entropy grows with σ\sigma: broader distributions carry more uncertainty. For σ<1/2πe≈0.242\sigma < 1/\sqrt{2\pi e} \approx 0.242 it goes negative, which simply says that a very peaky density concentrates probability so tightly that we know more about xx than we would from a uniform distribution on a unit interval (the baseline).

The Gaussian is special for another reason. If you fix the mean and variance and ask which distribution maximises differential entropy subject to those constraints, the answer is the Gaussian. This is the maximum-entropy principle: among all distributions compatible with what you know, pick the least committal one.

Going Deeper: KL Divergence and the Likelihood Connection

Imagine you have a true distribution p(x)p(x) but you don't know it exactly, so you model it with q(x)q(x). Use qq to design a code for transmitting draws from pp. You still need to send the outcomes, but because your code was optimised for the wrong distribution, you pay an average penalty in extra bits. That penalty is the Kullback-Leibler divergence:

KL(p∥q)=−∫p(x)ln⁡q(x)p(x) dx\mathrm{KL}(p \| q) = -\int p(x) \ln \frac{q(x)}{p(x)} \, dx

KL divergence is non-negative, and zero only when p=qp = q everywhere (Jensen's inequality makes this a one-line proof). Two properties matter in practice:

  1. It's a measure of dissimilarity, not a distance. There's no triangle inequality.
  2. It's not symmetric: KL(p∥q)≠KL(q∥p)\mathrm{KL}(p \| q) \ne \mathrm{KL}(q \| p).

That asymmetry isn't a nuisance. It's the whole point.

Mode-Seeking vs Mean-Seeking

Suppose pp is a bimodal mixture of two Gaussians and you fit a single Gaussian qq to it. Which direction of KL you minimise determines what you get.

Forward vs reverse KL on a bimodal target: q spreads to cover both modes vs collapses to one mode

The left panel minimises the forward KL, KL(p∥q)\mathrm{KL}(p \| q). Because pln⁡(1/q)p \ln(1/q) blows up wherever pp has mass but qq does not, the optimiser pays a huge penalty if qq assigns zero density to any region where pp lives. So qq spreads out and covers both modes, at the cost of putting mass in the empty valley between them. This is often called mean-seeking or zero-avoiding.

The right panel minimises the reverse KL, KL(q∥p)\mathrm{KL}(q \| p). Now the penalty fires wherever qq has mass but pp does not. The optimiser happily ignores a whole mode as long as qq stays inside one of them. It collapses onto a single mode. This is mode-seeking or zero-forcing.

This is not a toy distinction. Variational inference minimises reverse KL, which is why VI approximations routinely collapse onto one mode of a multimodal posterior. Expectation propagation uses forward KL and has the opposite bias. When you choose a method, you're choosing which failure mode you can live with.

KL Divergence Is Just Negative Log-Likelihood

The deepest application of KL in ML is hiding in plain sight. Suppose you have samples x1,…,xNx_1, \dots, x_N drawn from an unknown pp and you want to fit a parametric model q(x∣θ)q(x \mid \boldsymbol{\theta}). You minimise KL with respect to θ\boldsymbol{\theta}. Using the samples to approximate the expectation under pp:

KL(p∥q)≈1N∑n=1N{−ln⁡q(xn∣θ)+ln⁡p(xn)}\mathrm{KL}(p \| q) \approx \frac{1}{N} \sum_{n=1}^{N} \left\{ -\ln q(x_n \mid \boldsymbol{\theta}) + \ln p(x_n) \right\}

The second term has no θ\boldsymbol{\theta} in it, so it's a constant. The first term is the negative log-likelihood. Minimising KL and maximising likelihood are the same thing. Every time you train a classifier with cross-entropy loss, you are estimating which distribution in your model family has the smallest KL divergence to the data-generating distribution. This connection is why maximum likelihood estimation shows up everywhere, and why the jump from MLE to Bayesian inference is conceptually small: you're just replacing a point estimate of θ\boldsymbol{\theta} with a posterior over it.

Mutual Information: Correlation's Bigger Sibling

Consider two random variables xx and yy. If they are independent, their joint factorises: p(x,y)=p(x)p(y)p(x, y) = p(x) p(y). If they are not independent, you can measure how far from independent they are by taking the KL divergence between the joint and the product of marginals:

I[x,y]≡KL(p(x,y)∥p(x)p(y))I[x, y] \equiv \mathrm{KL}(p(x,y) \| p(x)p(y))

This is the mutual information. Because it's a KL divergence, it's non-negative, and it's zero exactly when xx and yy are independent.

Using the sum and product rules you can rewrite MI in terms of entropies:

I[x,y]=H[x]−H[x∣y]=H[y]−H[y∣x]I[x, y] = H[x] - H[x \mid y] = H[y] - H[y \mid x]

Read that aloud: mutual information is the reduction in uncertainty about xx when you observe yy. There is a Bayesian reading: if p(x)p(x) is the prior and p(x∣y)p(x \mid y) is the posterior after observing yy, then I[x,y]I[x, y] tells you how informative that observation was.

People often reach for Pearson correlation to measure dependence between variables. Correlation only sees linear relationships. Mutual information sees any statistical dependence: curves, clusters, multimodality, anything.

Mutual information between two Gaussian variables grows without bound as correlation approaches 1

For a bivariate Gaussian, MI has a pleasant closed form: I=−12ln⁡(1−ρ2)I = -\frac{1}{2} \ln(1 - \rho^2). At ρ=0\rho = 0 it's zero. As ∣ρ∣→1|\rho| \to 1 it diverges. The scatter cloud visibly tightens from circular to pencil-thin while the MI bar grows. For non-Gaussian variables you get no such shortcut, which is why MI is notoriously hard to estimate in practice: it requires estimating the joint density, and every decent estimator has tuning knobs that change the answer.

MI is the basis for several big ideas in ML. The information bottleneck framework argues that deep networks learn representations by maximising $I[T; Y]$ while minimising I[T;X]I[T; X], where TT is a hidden layer. Feature selection based on MI picks the variables that share the most information with the target. InfoNCE, the loss function behind contrastive self-supervised learning, is a mutual information estimator.

A Minimal Application: Information Gain in Decision Trees

The ID3 and C4.5 algorithms pick tree splits by maximising information gain, which is just MI between the feature and the label, or equivalently the drop in weighted entropy across the resulting partitions.

Four-cluster toy problem: greedy axis-aligned splits progressively reduce weighted leaf entropy to zero

I built a four-cluster toy problem where the classes form an XOR pattern: no single axis-aligned split can separate them, but three will. The GIF shows a greedy tree growing one split at a time, and the bar chart on the right tracks the weighted entropy of the leaves. It starts at 1 bit (maximum uncertainty over two classes) and falls to zero once every leaf is pure. That falling bar is information gain in action.

The same principle underlies text classification with Naive Bayes (TF-IDF can be viewed as an MI-weighted feature transform) and the information criteria AIC and BIC, which balance fit against the KL divergence introduced by adding more parameters.

Foundations

The path through information theory is the one I've followed here. Start from the discrete case, derive entropy from the multinomial by Stirling's approximation, take the Δ→0\Delta \to 0 limit to get differential entropy, show that the Gaussian maximises entropy subject to a variance constraint, and then introduce KL divergence as the excess code length from using the wrong distribution. Jensen's inequality gives non-negativity in a single line. The KL approximation from samples nails the connection to maximum likelihood. Mutual information enters as KL between the joint and the product of marginals and is rewritten as a reduction in conditional entropy.

Two side notes from the history are worth recalling. Boltzmann's story is a quiet tragedy: his statistical explanation of the second law was dismissed for decades, and he committed suicide before Perrin's experiments on colloidal suspensions vindicated him. And von Neumann suggested the word entropy to Shannon because "nobody knows what entropy really is, so in any discussion you will always have an advantage". Both men were, it seems, advising from experience.

If you want to go further, Cover and Thomas's Elements of Information Theory is the standard reference, and MacKay's Information Theory, Inference, and Learning Algorithms is available free online and is the best textbook ever written about this material.

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions