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.
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()

A fair coin () is maximally uncertain and needs exactly 1 bit per toss to transmit. A heavily biased coin () 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:
The term is the information content of outcome : 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 contains objects. The number of microstates consistent with that macrostate is the multinomial coefficient . Take the log, apply Stirling, and divide by N:
Boltzmann's (carved on his tombstone) and Shannon's 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:
This is called differential entropy. It has one quirk: unlike discrete entropy, it can be negative. For a Gaussian with variance , there is a neat closed form:

Entropy grows with : broader distributions carry more uncertainty. For it goes negative, which simply says that a very peaky density concentrates probability so tightly that we know more about 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 but you don't know it exactly, so you model it with . Use to design a code for transmitting draws from . 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 divergence is non-negative, and zero only when everywhere (Jensen's inequality makes this a one-line proof). Two properties matter in practice:
- It's a measure of dissimilarity, not a distance. There's no triangle inequality.
- It's not symmetric: .
That asymmetry isn't a nuisance. It's the whole point.
Mode-Seeking vs Mean-Seeking
Suppose is a bimodal mixture of two Gaussians and you fit a single Gaussian to it. Which direction of KL you minimise determines what you get.

The left panel minimises the forward KL, . Because blows up wherever has mass but does not, the optimiser pays a huge penalty if assigns zero density to any region where lives. So 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, . Now the penalty fires wherever has mass but does not. The optimiser happily ignores a whole mode as long as 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 drawn from an unknown and you want to fit a parametric model . You minimise KL with respect to . Using the samples to approximate the expectation under :
The second term has no 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 with a posterior over it.
Mutual Information: Correlation's Bigger Sibling
Consider two random variables and . If they are independent, their joint factorises: . 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:
This is the mutual information. Because it's a KL divergence, it's non-negative, and it's zero exactly when and are independent.
Using the sum and product rules you can rewrite MI in terms of entropies:
Read that aloud: mutual information is the reduction in uncertainty about when you observe . There is a Bayesian reading: if is the prior and is the posterior after observing , then 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.

For a bivariate Gaussian, MI has a pleasant closed form: . At it's zero. As 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 , where 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.

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 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
- Uniform Distribution Calculator: The maximum-entropy distribution on a bounded interval; a direct handle on the entropy bound discussed in this post.
- Bayes' Theorem Calculator: Build intuition for posteriors, the thing mutual information quantifies the informativeness of.
Related Posts
- Maximum Likelihood Estimation in Python from Scratch: MLE is KL minimisation against the data-generating distribution. This post makes that bridge explicit.
- From MLE to Bayesian Inference: Once you see likelihood as a KL, replacing the point estimate with a posterior is a natural next step.
- MCMC Metropolis-Hastings: An Intuitive Guide: Sampling from posteriors that KL-based variational methods struggle with.
- The EM Algorithm: A Coin Toss Guide: EM alternates between tightening a KL bound (E-step) and maximising log-likelihood (M-step).
- AIC and BIC for Model Selection: Both criteria are asymptotic approximations to KL divergence between model and truth.
- Bayesian Networks for Clinical Decision Support: Mutual information is the scoring function behind learning the network structure; this post puts that dependency machinery to work in a real diagnostic graph.






