24.4 The Exponential Family
Linear regression, logistic regression, and softmax regression each minimize a different loss function. Yet when we differentiate those losses with respect to the model weights, all three yield the exact same training rule: the input multiplied by the difference between the prediction and the observation. When three seemingly separate derivations converge on one formula, there is usually a single structure underneath. The catalogue of Section 24.3, where each distribution's mean and variance seemed to require its own clever algebraic trick, points to the same suspicion.
Consider the coin that runs through this chapter, which landed heads 9 times in 13 flips. The natural estimate of its bias is . If we fit a logistic-regression model with only a bias term to those same 13 flips, it arrives at by an indirect route: its final layer computes the log-odds , and a sigmoid maps that number back to . Why take this detour through the log-odds instead of working directly with the probability?
One idea explains both puzzles. Nearly every distribution in our catalogue can be written in a single canonical form, where the parameters enter only through the exponential of a linear combination of a few data statistics. Distributions with this structure form the exponential family, and for a coin, the parameter sitting in the exponent is precisely the log-odds. Remarkably, four central properties follow from this form alone: the mean and variance are simply the first two derivatives of a single function; maximum likelihood becomes a convex optimization problem whose gradient is always prediction minus observation; the softmax emerges automatically when we model class labels; and a prior of the same form updates by adding counts.
For deep learning, the second property is the central result, and the first is what proves it (Section 24.4.3.2 and Section 24.4.3.3). Together, they tell us which loss function to pair with a new kind of label, such as a count, and when a maximum-likelihood fit has no finite solution at all, as happens when a coin lands heads on every single flip. Two parts of this section can be skipped on a first reading: the maximum-entropy derivation (Section 24.4.2), which explains where the exponential form comes from, and the alternative derivations of the softmax from noisy choices and statistical physics.
24.4.1 One Form for Many Distributions#
Let us start with the simplest distribution in our catalogue, a single coin flip, and rewrite it until the log-odds appears on its own. That small bit of algebra will show us what the general form has to look like.
24.4.1.1 The Bernoulli in Exponential Form#
A coin with bias lands heads () with probability and tails () with probability . In the previous section we wrote both cases in one expression, . To see how the outcome and the parameter interact, take the logarithm and group the terms that contain :
Notice how cleanly the two roles separate: the outcome enters only through multiplied by the log-odds , while the second term depends on alone. Let us give the log-odds a name, , and rewrite the second term in terms of . Solving for yields , so and . Exponentiating both sides gives
The coin's probability is now the exponential of a linear function of , minus a term that does not depend on at all. That second term is simply the normalizer: the two unnormalized weights are and , and they sum to .
Three ingredients from this expression will reappear throughout the section. The statistic is the part of the outcome that matters. The natural parameter multiplies it; for the Bernoulli distribution, this is the log-odds, also known as the logit. Finally, the log-partition function is the logarithm of the normalizer, a function you may recognize as the softplus. Reading our earlier substitution in reverse,
The sigmoid of logistic regression is therefore nothing more than the map from the coin's natural parameter back to its mean. Nobody had to invent it.
For our running coin example, the empirical bias corresponds to the natural parameter
and the sigmoid takes it right back: . Shortly, we will see why is the maximum-likelihood value of the log-odds, and what the curvature of the loss around tells us about how uncertain that estimate is.
24.4.1.2 Definition and Members#
Our rewriting of the Bernoulli had three moving parts: a statistic of the data, a parameter that multiplies it, and a normalizer. Generalizing to several statistics at once, while allowing a fixed, parameter-free weight on each outcome, gives a single template that captures most of our catalogue.
A family of distributions is an exponential family if its probability mass or density function can be written as
In this form, the data and the parameters interact only through the inner product . The base measure assigns a fixed weight to each outcome independently of the parameters, and the region where defines the support of the distribution. The natural parameters are the adjustable parameters, and the sufficient statistics are the features of the data they multiply. The log-partition function is the logarithm of the normalizing constant,
with an integral for continuous densities and a sum for discrete . In plain terms, is whatever constant makes (24.4.1) integrate or sum to one, and the valid natural parameters are those for which is finite. The Bernoulli distribution is the special case , , and .
Why are the features called sufficient? Because they hold everything the data can tell us about . For independent observations, the joint likelihood factors as
The parameters touch the data only through the sum . Any two datasets that share the same sum produce likelihoods differing only by a constant factor independent of , so they yield the same parameter estimates. For a coin, this sum is simply the total number of heads. Any permutation of the 13 flips has the same probability under every bias, so once we know that 9 flips came up heads, the order in which they appeared adds nothing further about the coin.
Matching pieces against (24.4.1) quickly identifies the other members of the family. For a Poisson distribution with rate , the probability of events is , so we read off , , , and . A Gaussian with unknown mean and variance needs two statistics. Expanding the square in its exponent and collecting the terms in and gives
so and . Notice that the second natural parameter must be strictly negative: when , the factor supplies the Gaussian's rapid tail decay, whereas for the normalizing integral for diverges. Table 24.4.1 collects these and several other common members.
| distribution | ||||
|---|---|---|---|---|
| Bernoulli() | ||||
| Binomial() | ||||
| Poisson() | ||||
| Categorical, one-hot | logits | |||
| Exponential() | for | |||
| Laplace() |
The categorical row expresses class probabilities through the logits, giving rise to the softmax, whose origins we explore in Section 24.4.4. Two further members live in higher dimensions: the multivariate Gaussian, with sufficient statistics and and natural parameters and , and the multinomial with a fixed number of draws. Keep in mind that the split among , , and is not unique. The one redundancy that will matter later sits in the categorical row: because the entries of a one-hot vector always sum to one, one of the logits is redundant (Section 24.4.3.2).
24.4.1.3 Distributions Outside the Family#
Not every distribution fits inside (24.4.1), and the two classic exceptions fail for illuminatingly different reasons.
First, consider the uniform distribution , whose density is on and zero outside. Here the support itself moves with the parameter . By contrast, every exponential family has a fixed support, the set where , because the exponential factor never vanishes. A moving support changes estimation fundamentally. Suppose we observe three draws: , , and . The likelihood is whenever and whenever (a smaller could never have generated ), so the maximum-likelihood estimate is the sample maximum, .
Inside an exponential family, as we will prove shortly, maximum likelihood always equates the model's mean of the sufficient statistic to its sample average. Applying that recipe here sets the mean equal to , yielding , a value under which the observed draw is impossible. Because the uniform likelihood depends on the data through their maximum rather than a sum, the machinery of this section does not apply. Exercise 7 in Section 24.6 compares how these two estimators behave as the sample size grows.
Heavy-tailed distributions fall outside the family for a second reason. The Student- distribution arises by taking a Gaussian whose precision is itself random; averaging over that precision replaces the rapidly decaying tails with polynomial ones (Exercise 4 derives its density). With unit scale and degrees of freedom, the likelihood of observations is a product of factors , which cannot be compressed into any fixed number of sums of the data. In fact, a classical theorem of Pitman, Koopman, and Darmois states that among regular families with fixed support, only exponential families possess a sufficient statistic of fixed dimension (Darmois, 1935; Koopman, 1936; Pitman, 1936).
As a practical consequence, the convexity of the negative log-likelihood, which we will prove holds for every exponential family, can break down outside it. For a Student- distribution, when the data fall into two well-separated clusters, the negative log-likelihood for the location develops a separate local minimum near each cluster.
24.4.2 Maximum Entropy#
So far, the exponential form has appeared simply by rewriting familiar distributions. A deeper question asks where this form comes from in the first place. Suppose all we know about a random quantity is the average value of a few of its statistics. Which distribution should we choose? Remarkably, the distribution that assumes nothing beyond those averages is always a member of the exponential family.
24.4.2.1 Entropy and a Loaded Die#
To make "assumes nothing beyond the averages" precise, we need a way to measure how spread out, or uncommitted, a distribution is. For a distribution on a finite set, the entropy is
measured in nats, with the convention . Each term weights the surprise of outcome by its probability, so entropy is simply the average surprise. A fair six-sided die assigns every face a surprise of , giving an entropy of nats. A die that always lands on six holds no surprises at all and has entropy . Among all distributions on outcomes, the uniform distribution achieves the largest possible entropy, , a fact we will prove in a moment.
E. T. Jaynes framed the problem with a concrete puzzle (Jaynes, 1957). Suppose someone tells you that a six-sided die averages rather than , and nothing else. Many distributions on have mean . Putting probability on and on is one of them, yet it boldly asserts that , , , and can never occur, a claim with no support in what we were told. Its entropy is only .
Jaynes's principle of maximum entropy selects, among all distributions matching the known averages, the one with the largest entropy, the least committal choice consistent with our knowledge. Let us state the answer before proving it. The unique maximizer is an exponential tilt of the uniform distribution,
with tuned so that the mean equals . The distribution concentrated on threes and sixes surrendered of the fair die's nats to hit this mean. Before running the code below, pause and guess how much entropy the exponential tilt has to give up. Because the mean of the tilt increases monotonically with , simple bisection finds the exact value of .
k = np.arange(1, 7)
def tilt(eta): # p_k proportional to exp(eta k)
w = np.exp(eta * k)
return w / w.sum()
lo, hi = -5.0, 5.0
for _ in range(50): # bisection: the mean increases with eta
eta = (lo + hi) / 2
lo, hi = (eta, hi) if (tilt(eta) * k).sum() < 4.5 else (lo, eta)
p = tilt(eta)
print('eta =', round(eta, 3), ' p =', p.round(3))
print('H =', round(-(p * np.log(p)).sum(), 3), ' log 6 =', round(np.log(6), 3))
eta = 0.371 p = [0.054 0.079 0.114 0.165 0.24 0.347]
H = 1.614 log 6 = 1.792
The resulting distribution is geometric across the faces: each face is times as likely as the face below it. Its entropy is nats, giving up only nats compared with the fair die, and setting recovers the fair die. Figure 24.4.1 compares the exponential tilts for three different required means.
Maximum-entropy distributions of a die whose average roll is fixed at , , and (black triangles). Each is an exponential tilt of the uniform distribution; as the required mean rises, the tilt grows and the entropy falls.
Notice that this tilt already has the exponential-family form (24.4.1), with on the six faces, statistic , and natural parameter . Fixing the mean of a statistic and maximizing entropy led us straight to the exponential of a multiple of that statistic. That is no coincidence of the die.
24.4.2.2 The Maximum-Entropy Proposition#
To state the general theorem, we need one small extension of entropy, because some outcome spaces carry natural baseline weights. For a distribution and a base measure , the entropy relative to is
for discrete outcomes, with an integral in place of the sum for continuous densities. Setting recovers the ordinary entropy defined above.
The proof compares any candidate distribution directly against a member of the exponential family. Given two distributions and on the same space, with wherever , the Kullback--Leibler divergence of from is summed over outcomes with , or the corresponding integral for densities (Cover and Thomas, 1999). Section 25.1 studies entropy and this divergence in depth. All we need here is one elementary fact, proved by a single tangent line: because the logarithm is concave, for every , with equality only at (Figure 24.4.2).
The tangent-line bound . The concave logarithm (blue) lies below its tangent at (orange) for every and touches it only there.
Lemma (Gibbs' inequality). The Kullback--Leibler divergence is never negative,
with equality if and only if .
Proof. Apply the tangent-line bound with and sum over all outcomes with :
Equality in the first inequality requires wherever . That forces , leaving with no remaining probability mass outside the support of , so everywhere.
Proposition (maximum entropy). Let be a member of an exponential family, and let be any distribution (with a density, in the continuous case) that vanishes wherever vanishes, has a finite mean statistic , and matches on that mean: . Then , with equality if and only if .
Proof. Split the logarithm in by inserting : . The first term yields by Gibbs' inequality, which applies because wherever . The second term is linear in the sufficient statistic, , so enters only through its mean of :
The middle equality uses the mean constraint, and the last repeats the same calculation with in place of . Combining the two terms gives , with equality only when .
The key step is the second one: because is linear in , the cross term depends on solely through , which the constraint holds fixed. In plain words, whenever a member of the exponential family satisfies the mean constraints, it is the unique distribution of largest entropy among all distributions that satisfy them. Remarkably, no Lagrange multipliers are needed, and the proof certifies a global maximum rather than merely a stationary point.
For the loaded die, the tilt with belongs to the family with and and has mean , so it is the unique maximizer. Three familiar distributions follow immediately as corollaries:
- No constraint (): every is admissible, and the maximizer is , provided has a finite sum. On a finite set with , this is the uniform distribution with entropy ; the fair die is the case .
- Mean and variance on : with and constant , the maximizer is the Gaussian. Because a constant shifts by a fixed constant, the Gaussian has the largest entropy among all densities with a prescribed mean and variance.
- Mean on the counts with : taking makes the maximizer of with mean the Poisson distribution with rate , whereas taking yields the geometric distribution with . The base measure decides which distribution emerges, as Exercise 2 explores.
Be careful not to drop the hypothesis that some member of the family meets the constraints. Suppose we fix only the mean on all of , with . The candidate density is not integrable on for any , so no member exists. Nor does any maximizer exist at all: the Gaussian has mean and entropy , which grows without bound as .
24.4.3 The Log-Partition Function#
In the catalogue of Section 24.3, every mean and variance seemed to demand its own trick: for the Bernoulli, a sum of independent flips for the binomial, an index shift in the series for the Poisson, and integration by parts for the Gaussian. Inside the exponential family, all of those calculations collapse into one operation: differentiating the log-partition function . The first derivative gives the mean, the second gives the variance, and the very same function governs maximum likelihood.
24.4.3.1 The Moment Property#
Recall that is the logarithm of an integral or sum of exponentials . Differentiating such a logarithm pulls down a factor of , weighted by the probability of , which is simply the expectation of .
Proposition (mean of the sufficient statistics). For an exponential-family distribution (24.4.1),
Proof. Differentiate (24.4.2) under the integral sign. This interchange is justified in the interior of the set of natural parameters where (Folland, 1999); that set is convex (by Hölder's inequality), and we take in its interior from here on. Writing , the chain rule gives , where
Dividing by brings the factor inside the integral, completing the density (24.4.1):
Differentiating a second time, under the same interchange, produces the covariance matrix of the sufficient statistics:
In short, the slope of is the mean of , and its curvature is the covariance of . Because every covariance matrix is positive semidefinite ( for all ; Section 21.3.2.2), the log-partition function is always convex.
Let us check this on two familiar examples. For the coin, gives , the Bernoulli mean, and , its variance. At , these evaluate to and . For the Poisson distribution, is its own derivative, so at () both and equal . Since moments are just derivatives, automatic differentiation computes them directly for any we can write in code. Let us verify both cases.
def derivatives(A, eta):
"""First and second derivative of the scalar function A at eta."""
eta = torch.tensor(eta, dtype=torch.float64, requires_grad=True)
(dA,) = torch.autograd.grad(A(eta), eta, create_graph=True)
(d2A,) = torch.autograd.grad(dA, eta)
return dA.item(), d2A.item()
cases = [('Bernoulli', torch.nn.functional.softplus, math.log(9 / 4), 9 / 13, 36 / 169),
('Poisson', torch.exp, math.log(4), 4, 4)]
for name, A, eta, mean, var in cases:
dA, d2A = derivatives(A, eta)
print(f"{name:9s} A' = {dA:.4f} (mean {mean:.4f}) A'' = {d2A:.4f} (variance {var:.4f})")Bernoulli A' = 0.6923 (mean 0.6923) A'' = 0.2130 (variance 0.2130)
Poisson A' = 4.0000 (mean 4.0000) A'' = 4.0000 (variance 4.0000)
Both derivatives match the analytical mean and variance to all four printed digits. Notice how the Poisson's famous equality of mean and variance, which required a power-series calculation in the catalogue, now reduces to a single line: for .
24.4.3.2 Maximum Likelihood as Moment Matching#
The moment property turns maximum likelihood into a remarkably clean condition on expectations: the fitted model must reproduce the sample average of the sufficient statistics. Given independent observations , taking the negative logarithm of the product likelihood from (24.4.1) gives
Here the data enter solely through the sum . Because is convex and the second term is linear in , the negative log-likelihood is convex in . Setting its gradient to zero and applying the moment property (24.4.4) yields
Maximum likelihood therefore sets the model's expected sufficient statistic equal to its observed sample average, a principle called moment matching. And because the objective is convex, any solution to this equation is automatically a global minimizer.
Let us see what this gives for our coin with 9 heads in 13 flips. Its negative log-likelihood is . The derivative vanishes precisely where , which gives . At this minimum, the loss equals
which is 13 times the entropy of a coin with bias , . At the optimum, the average loss per flip equals the entropy of the fitted coin.
This identity holds for every exponential family with : the average negative log-likelihood at is , while the entropy of the fitted distribution is . Because , the two numbers coincide.
The second derivative of the loss at the minimum is . Large curvature means the loss climbs steeply away from , pinning down the log-odds tightly. Thirteen flips leave plenty of wiggle room: moving by away from raises the loss by only about half a nat. Section 24.6 identifies this curvature as the Fisher information and turns it into an error bar. Figure 24.4.3 illustrates both the tangent of at and the shape of the negative log-likelihood.
Left: the Bernoulli log-partition function with its asymptotes and its tangent at , whose slope is the mean . Right: the negative log-likelihood for heads in 13 flips, with its minimum at , and for heads, which decreases for every and has no finite minimizer.
There is an important caveat: the moment-matching equation has a solution only if is a mean that some member of the family can actually attain. For a Bernoulli coin, the attainable means are for real , namely the open interval . If all 13 flips come up heads, then lies on the boundary and is not attainable. The negative log-likelihood becomes , which drops monotonically for every : it equals at , at , and at . It approaches without ever reaching it, so no finite minimizer exists; the fitted probability approaches as .
Logistic regression hits the exact same wall whenever a hyperplane separates the two classes in the training set: the loss keeps decreasing as the weights scale up, driving them toward infinity. Adding a prior on the parameters (which we introduce at the end of this section) or using weight decay restores a finite optimum; Exercise 4 in Section 24.6 works out the details.
When a minimizer does exist, it is unique whenever the negative log-likelihood is strictly convex. That holds if is positive definite, meaning no nontrivial linear combination of the sufficient statistics is constant across the support. Such a parameterization is called minimal. The categorical distribution parameterized by all logits is not minimal: the one-hot coordinates always sum to one, so adding the same constant to every logit leaves all probabilities unchanged. As a result, its negative log-likelihood is flat along the direction , and its minimizers form a line rather than a point. Deep learning libraries keep all logits anyway and exploit this shift invariance to subtract the largest logit before exponentiating for numerical stability (Section 3.3.5).
24.4.3.3 Generalized Linear Models#
Supervised learning models predict a conditional distribution over a label given an input . A generalized linear model chooses that distribution from an exponential family (24.4.1) and lets the input enter through a linear map (folding any bias term into a constant feature). The cleanest choice sets this linear map directly equal to the natural parameter, , a pairing known as the canonical link. Writing for the model's predicted mean of the sufficient statistic, the negative log-likelihood of a single example is . By the moment property (24.4.4), its gradient with respect to is simply . Applying the chain rule through immediately gives
Whatever the exponential family, the gradient is always the input multiplied by the prediction error: predicted mean minus observed statistic. With the moment property in hand, the mystery from the opening of this section resolves in two lines. Moreover, the loss is convex in , since it composes the convex function with a linear function of and adds a linear term. Note that this tidy gradient belongs specifically to the canonical link: the probit model in Section 24.4.4 feeds the same linear score into a Gaussian CDF instead, and its gradient picks up an extra factor that varies with the prediction. Four familiar models arise simply by swapping the exponential family:
| label | family | mean | model | |
|---|---|---|---|---|
| real number | Gaussian, variance 1 | linear regression | ||
| yes or no | Bernoulli | logistic regression | ||
| one of classes | categorical | one-hot | softmax regression | |
| count | Poisson | Poisson regression |
To see the rule on a less familiar label, consider a Poisson model for count data. If the model predicts a mean of for an input and the observed count is , then the gradient of the loss with respect to is . A gradient descent step therefore increases and pushes the predicted mean upward toward .
In the first row, fixing the Gaussian variance at puts the quadratic term into the base measure , so the negative log-likelihood reduces to the squared loss of Section 2.1 up to an additive constant. A deep neural network keeps this final layer intact (a linear map into natural parameters followed by the family's negative log-likelihood), while replacing the raw input with learned representations. Although the overall loss is no longer convex in the network weights, its gradient with respect to the natural parameters at the output layer remains prediction minus observation (Bishop, 2006).
24.4.4 Origins of the Softmax#
Throughout the main text, classifiers convert a vector of logits into class probabilities using the softmax,
We just saw this map emerge from the categorical row of our exponential-family tables. It has obvious desirable properties: each probability increases with its own logit, and all probabilities are positive and sum to one. Yet many other maps share those properties; normalizing instead of , for instance, also produces positive probabilities that preserve the ranking of the logits. What sets the softmax apart is that logit differences are log-odds: . Remarkably, three independent arguments from three different fields all converge on this exact formula: a model of noisy human choices, the Boltzmann distribution of statistical physics, and the exponential family. The third is the shortest and is the only one the rest of this section relies on.
24.4.4.1 Noisy Choices and Gumbel Noise#
The first argument models how discrete labels are generated in the first place. Imagine a decision maker, such as a shopper choosing a product or an annotator labeling an image, who assigns each option an underlying score but makes occasional errors. A natural way to model noisy selection is to add independent random noise to every score and pick the option with the highest perturbed score:
Under this model, the probability of class is the chance that option wins the noisy contest, so its formula is determined by the distribution of the noise. Gaussian noise is the first thing most people try. With two options and , option 1 wins whenever . Because the difference is itself Gaussian with variance , the winning probability is
where denotes the standard Gaussian CDF (and its density). This is the probit model: the choice probability depends only on the score gap, measured in units of the noise scale.
Unfortunately, the probit model loses its closed form as soon as there are more than two options. The probability that option beats all rivals becomes an integral of a product of Gaussian CDFs, which has no elementary formula and would have to be integrated numerically, along with its gradient, for every training example at every step.
Switching from Gaussian to Gumbel noise eliminates that integral completely. The standard Gumbel distribution has the CDF . It arises naturally in extreme-value theory as the limiting distribution of the suitably shifted and scaled maximum of many independent draws from an exponentially decaying tail, such as a Gaussian or exponential distribution (Gumbel, 1954), and McFadden (1974) introduced it to model economic choice.
Proposition (Gumbel noise gives the softmax). If are independent standard Gumbel random variables, then the noisy argmax follows the softmax distribution,
Proof. Let . Each perturbed score has CDF . Conditioned on option achieving a score of , independence implies that all other options fall below with probability . Multiplying by the density of , integrating over , and substituting yields
The calculation succeeds because a product of Gumbel CDFs is still a Gumbel CDF. Across all options, the maximum score satisfies , meaning the winning score is simply a standard Gumbel variable shifted by the log-sum-exp . Viewed this way, log-sum-exp acts as a smooth maximum of the logits, and its gradient, the softmax, gives the probability that each option achieves that maximum. Exercise 1 offers a second proof of the same identity using competing exponential waiting times.
Read in reverse, the proposition doubles as a sampling algorithm: to draw a category from , add independent standard Gumbel noise to each logit and take the argmax. This is the widely used Gumbel-max trick.
For the remainder of Section 24.4.4, we follow the main text and use to denote a temperature rather than a sufficient statistic. Because for any , scaling the Gumbel noise by samples from : noisier decisions correspond to higher temperatures. Let us test the Gumbel-max trick directly by drawing choices over four logits at and and comparing the empirical win rates against the exact softmax probabilities.
z = np.array([2.0, 1.0, 0.1, -1.0]) # four logits
softmax = lambda v: np.exp(v) / np.exp(v).sum()
rng = np.random.default_rng()
n = 100_000
for T in (1.0, 2.0): # noise scale = temperature
winners = np.argmax(z + T * rng.gumbel(size=(n, 4)), axis=1)
freq = np.bincount(winners, minlength=4) / n
print(f'T = {T:.0f}: argmax frequencies {freq.round(3)}')
print(f' softmax(z / T) {softmax(z / T).round(3)}'
f' max diff {np.abs(freq - softmax(z / T)).max():.3f}')T = 1: argmax frequencies [0.638 0.234 0.095 0.033]
softmax(z / T) [0.638 0.235 0.095 0.032] max diff 0.001
T = 2: argmax frequencies [0.451 0.274 0.173 0.102]
softmax(z / T) [0.451 0.274 0.174 0.101] max diff 0.002
The empirical frequencies agree with to within a few thousandths, right at the Monte Carlo noise floor for draws. Doubling the noise scale flattens the win rates in the exact same way as halving the logits.
With two options, the difference of two independent standard Gumbel random variables follows the logistic distribution, whose CDF is , so this logit model yields . Because the sigmoid closely tracks a rescaled Gaussian CDF ( for all ), fitted probit and logit models produce nearly identical probabilities on ordinary examples. Where they diverge is in the tails: on a confidently mislabeled outlier, the logit loss grows only linearly in the score difference, whereas the probit loss grows quadratically, allowing outliers to pull a probit fit much harder (Exercise 4).
24.4.4.2 Temperature and the Boltzmann Distribution#
The second argument comes from statistical physics, where the exact same exponential law governs energy states. A physical system in thermal equilibrium at temperature , such as a molecule in a gas, occupies a state of energy with probability
where is Boltzmann's constant. Lower-energy states are more probable, and the temperature controls how sharply probability concentrates on them. Boltzmann discovered this distribution for gas molecules, and Gibbs (1902) built statistical mechanics upon it. If we measure temperature in energy units (setting ) and identify energies with negative logits (), the Boltzmann law becomes . In this language, a logit is a negative energy, and the most likely class is simply the lowest-energy state.
Our maximum-entropy proposition derives the same formula without invoking physics at all. A physicist fixes the mean energy and assumes nothing else; in classification, the analogous constraint fixes the average logit . Take the classes as outcomes with and treat the logit as the statistic. Among all distributions on the classes achieving a prescribed average logit (strictly between the smallest and largest entries of ), the maximum-entropy distribution is . Whenever the target average exceeds the unweighted mean of the logits, , and setting recovers . As cools from down to , the average logit rises smoothly from the mean of the logits to their maximum. For the logits in our simulation, the standard softmax () achieves an average logit of , sitting between the unweighted mean and the maximum .
24.4.4.3 The Categorical as an Exponential Family#
The third argument is the one we already uncovered earlier in this section. Encoding a class label as a one-hot vector , the categorical distribution is with log-partition function , an exponential family whose natural parameters are the logits. By the moment property, its mean is . Its negative log-likelihood is automatically convex in , and by (24.4.6), its gradient is simply .
All three arguments arrive at the same function, yet each illuminates a different facet of it: noisy choices give us an exact sampler, the Boltzmann distribution explains temperature scaling, and the exponential family hands us a convex loss and its effortless gradient.
24.4.5 Conjugate Priors#
Maximum likelihood compresses 9 heads in 13 flips into a single number, . A point estimate alone cannot tell us how confident to be in it: 9 heads in 13 flips and 900 heads in 1300 flips produce the exact same ratio. Representing our knowledge as a probability distribution over the coin's bias captures that uncertainty directly, and ideally it should absorb each new flip through a simple update rather than starting from scratch.
From here on, we treat the bias itself as an unknown random quantity and denote it by , matching the notation of the upcoming sections. A distribution over before seeing the data is a prior. Bayes' rule multiplies the prior by the likelihood and normalizes the result, , producing the posterior. A prior is conjugate to a likelihood when the posterior belongs to the very same family of distributions as the prior, so that observing data merely updates its parameters.
24.4.5.1 The Beta Prior on a Coin#
A prior on a coin's bias must be a density supported on . Viewed as a function of , the likelihood of heads in flips is , so a prior with the same algebraic form combines with it simply by adding exponents. Its normalizing constant uses the Gamma function from Section 24.3, which generalizes the factorial via and . The Beta distribution with parameters has the density
where the normalizer equals . The mean follows effortlessly from this normalizer, since multiplying the density by simply increments by one:
where we used and to cancel the Gamma factors. Applying the same trick twice yields the variance; writing for the mean,
Larger values of concentrate the density more tightly around its mean, while gives the flat uniform density on .
Now suppose we observe heads in flips. Multiplying the prior by the likelihood adds the exponents directly,
which, once normalized, is again a Beta density with parameters shifted by the observed counts:
This update has a clean pseudo-count interpretation: and act as prior counts of heads and tails, and seeing heads and tails simply adds them to the tally. The posterior mean,
is the fraction of heads after folding in those pseudo-counts. It sits between the prior mean and the maximum-likelihood estimate , converging to as grows large.
Be careful about one subtle distinction: how many flips the prior is worth depends on which summary you compute. When both posterior parameters exceed , the posterior mode is , so the prior contributes heads and tails to the mode. To keep the convention clear once and for all: and are the pseudo-counts of the posterior mean, whereas and are those of the posterior mode. Under the uniform prior , the mean includes one imagined head and one imagined tail, while the mode includes none.
Returning to our chapter's coin with the uniform prior, 9 heads in 13 flips update to . Its posterior mean is , a classic formula known as Laplace's rule of succession, (Laplace, 1814). Its mode coincides with the maximum-likelihood estimate, and its standard deviation is .
If we instead see 90 heads in 130 flips, the posterior sharpens to , with mean and standard deviation . Collecting ten times as many flips shrinks the standard deviation by a factor of : posterior uncertainty narrows at the rate, the same scaling we will see for standard errors in Section 24.5.
What probability should we assign to the next flip landing heads? Given , that probability is ; averaging over our posterior beliefs yields . For our coin, that predictive probability is : Laplace's rule directly gives the probability of the next head.
Conjugacy saved us from computing the normalizing integral in Bayes' rule. What if our prior is not conjugate? In one dimension, we can simply evaluate the product of prior and likelihood on a fine grid of values and normalize the sum. Consider a Gaussian prior on the natural parameter, , the same kind of prior that Section 24.8 places on logistic-regression weights. It expresses a belief that the coin is probably near fair, and it is not conjugate to the Bernoulli likelihood: by a change of variables, its density in is , where is the standard Gaussian density, which is not a Beta density. Let us compute the posterior under both priors on the same grid and compare their summaries.
x, n = 9, 13 # 9 heads in 13 flips
theta = np.linspace(0, 1, 100_001)[1:-1] # interior grid points
eta = np.log(theta) - np.log1p(-theta) # natural parameter
priors = {'Beta(1, 1)': np.ones_like(theta), # densities in theta
'eta ~ N(0, 1)': np.exp(-eta**2 / 2) / (theta * (1 - theta))}
for name, prior in priors.items():
post = prior * theta**x * (1 - theta)**(n - x)
post /= post.sum() # grid weights sum to one
mean = post @ theta
sd = math.sqrt(post @ (theta - mean)**2)
print(f'{name:13s}: mean {mean:.3f}, sd {sd:.3f}, '
f'mode {theta[post.argmax()]:.3f}')
Beta(1, 1) : mean 0.667, sd 0.118, mode 0.692
eta ~ N(0, 1): mean 0.644, sd 0.111, mode 0.665
Under the uniform prior, the grid recovers the exact moments of : mean , standard deviation , and mode . Placing a Gaussian prior on the log-odds pulls the posterior closer to a fair coin, lowering the mean to , the mode to , and the standard deviation slightly to . A grid handles the non-conjugate prior just as easily as the conjugate one, but only because is scalar; Section 24.8 develops methods that scale to high-dimensional parameter vectors. Figure 24.4.4 visualizes how the Beta posterior sharpens as flips accumulate.
Bayesian updating of a coin's bias . Left: the flat prior. Middle: the posterior after 9 heads in 13 flips of a coin with true bias (dashed), with mean and standard deviation . Right: the posterior after 130 flips, with standard deviation . Each update adds observed heads and tails to the pseudo-counts, and the posterior width shrinks like .
24.4.5.2 Conjugacy for Every Exponential Family#
At first glance, the Beta update looks like a lucky algebraic coincidence. In fact, it is a universal property of exponential families: every exponential family admits a conjugate prior, and updating it always amounts to adding the sufficient statistics.
Proposition (conjugate prior). Consider a likelihood (24.4.1) and the prior on its natural parameters
where and are chosen so that the density is normalizable. After independent observations , the posterior retains the exact same form, with updated to and updated to .
Proof. Dropping factors that do not depend on , the likelihood contributes . Multiplying it by the prior combines the exponents in a single line:
Normalizing this product gives the posterior, which therefore belongs to the same family with the updated parameters and .
The prior's parameters and , called hyperparameters, behave like pseudo-data: acts as a prior sum of sufficient statistics and as a prior sample size (Bishop, 2006). For the Bernoulli coin, this prior is written in terms of the logit ; changing variables from to transforms it into , and the general update , reproduces the Beta update , . Exercise 7 works through this change of variables, including its Jacobian.
24.4.5.3 Gamma–Poisson and Dirichlet–Multinomial#
Two more widely used conjugate pairs follow the same pattern, one for event rates and one for categorical probabilities over words or classes. Viewed as a function of the rate , the likelihood of Poisson counts is proportional to . The matching conjugate prior is the Gamma distribution with shape and rate , whose density is for (with mean ). Multiplying prior and likelihood yields the posterior , so the prior encodes imagined events spread across imagined time periods. Exercise 7 derives this pair directly from the general proposition.
To generalize the Beta prior from two outcomes to categories, we use the Dirichlet distribution, a density over probability vectors with and . With concentration parameters , its density is
which has mean and reduces to the Beta distribution when . Observing category counts gives a likelihood proportional to , so the posterior is : each category's observed count is added to its pseudo-count.
To see why this matters in practice, suppose a three-word vocabulary produces the counts . The maximum-likelihood estimate assigns probability zero to the unseen second word, which would make any future document containing that word seem impossible. Placing a uniform prior on yields the posterior , whose mean is . Adding one to every count before normalizing, known as add-one smoothing, is simply the posterior mean under this Dirichlet prior; the Naive Bayes classifier in Section 24.11 uses the two-class case.
Closed-form posteriors are the exception rather than the rule: outside conjugate pairs, Bayesian inference requires numerical approximation (Section 24.8). Before tackling that, however, we need an answer to a more basic question about point estimates. From 13 flips we obtained , a single number without an error bar: how far might be from the true bias, and does a coin with 11 heads in 13 flips really differ from one with 9? Section 24.5 takes up these questions.
24.4.6 Summary#
Nearly every distribution in our catalogue shares the exponential-family form , where data and parameters interact solely through the inner product , and maximizing entropy under fixed average statistics produces this exact form. Differentiating the log-partition function generates moments: is the mean of and is its covariance, which immediately proves that is convex. Consequently, maximum likelihood is a convex optimization problem that matches the model's expected sufficient statistics to their sample averages, admitting a finite solution whenever that sample average is attainable. Pairing an exponential family with its canonical link yields a generalized linear model whose gradient is always input times prediction minus observation, unifying linear, logistic, softmax, and Poisson regression while explaining why non-canonical links such as the probit behave differently. The softmax emerges as the mean map of the categorical family (as well as from Gumbel noise and the Boltzmann distribution). Finally, every exponential family admits a conjugate prior updated simply by adding sufficient statistics; for a coin, contributes and pseudo-counts to the posterior mean and and to the mode.
24.4.7 Exercises#
-
Exponential races. Let be independent with , for example the waiting times for the next event in independent event streams.
- Show that .
- Show that the -th stream fires first with probability .
- Let be independent variables and let be a vector of logits. Use (b) to show that is distributed according to the softmax probabilities (24.4.7). Because has the standard Gumbel distribution, this is a second proof that Gumbel noise gives the softmax.
-
Maximum entropy on the integers. Consider distributions on with a fixed mean .
- Maximize the Shannon entropy subject to and , using Lagrange multipliers (Section 23.6.1). Show that the stationary point is a geometric distribution , and express through .
- Repeat the derivation for the entropy relative to , , and show that the stationary point is .
- At , compute the Shannon entropy of both distributions numerically. Which one is larger, and why must it be? Compare under the two distributions. Which assumption about large counts does the choice of base measure encode?
- A stationary point of a Lagrangian need not be a maximum. Use the maximum-entropy proposition to prove that the two distributions of (a) and (b) are the global maximizers, by exhibiting each as a member of an exponential family whose mean equals .
-
Moments from the log-partition. The moment property (24.4.4) and its second-order form turn moment calculations into differentiation.
- For the Poisson, . Derive the mean and the variance from . Which property of the function makes them equal?
- For the Gaussian, the natural parameters are and . Show that , and differentiate it to recover , , and .
- The Laplace distribution with a fixed location and scale has the sufficient statistic . Write it in the form (24.4.1), and use to compute and . Check the result against the Laplace variance .
- For Gaussian observations, write the two moment-matching equations and solve them for and . What happens for ? Relate your answer to the condition that be an attainable mean.
-
[code] Probit and logit. For two classes with the score difference , the logit model gives and the probit model with noise scale gives .
- Show that the difference of two independent standard Gumbel variables has the CDF . The standard Gumbel distribution has variance . Find the scale for which the distribution with CDF has variance 1, like the standard Gaussian.
- Find numerically the scale that minimizes , and the value of this maximum. Why is this scale smaller than the one of (a)?
- An example of class 2 lies on the wrong side of the decision boundary, with . Show that its negative log-likelihood under the logit model lies between and , and that its derivative with respect to is less than 1. Use the bounds for to show that its negative log-likelihood under the probit model grows like , and that its derivative grows linearly in .
- Draw 100 inputs of class 1 and 100 inputs
of class 2, and let . Fit by
maximum likelihood under both models. Then add three examples at
labeled as class 2, and fit again. For each model, compute the
ratio of the slope with these mislabeled examples to the slope
without them, and explain the difference between the models with (c).
Compute with a numerically stable routine such as
scipy.special.log_ndtr.
-
Minimal categorical family. ● Code a categorical outcome as a one-hot vector with class probabilities , written as an exponential family with , natural parameters and .
- Compute and show that it equals the covariance of the one-hot vector . Every one-hot vector satisfies . Show that , and that the gradient of the negative log-likelihood of a dataset is orthogonal to at every . Gradient descent with a small step size runs on the logits from a starting point , and every class occurs in the data. Which function of does gradient descent never change? Which of the minimizers does it therefore approach?
- Fix . This gives a minimal representation with and . Show that is positive definite whenever every . Given class counts , solve the moment-matching condition for the maximum-likelihood . What happens when some class has ?
-
[code] Poisson regression. ● A generalized linear model for counts makes the natural parameter of a Poisson an affine function of the features: with .
- Use the negative log-likelihood (24.4.5) to write the loss as a function of , and compute its gradient and Hessian. Show that the loss is convex. Which equations does a zero gradient impose on the fitted means ?
- Generate examples with , and . Starting from zero, fit with Newton's method, which repeats the step for the loss , and check the equations of (a) at the solution.
- Multiply each rate by an independent , which has mean , so that the counts become overdispersed while their conditional means stay . Fit the Poisson model to such datasets and to datasets without the multiplier. Compare the mean and the standard deviation of the estimates across datasets. Explain the behavior of the mean with the equations of (a).
-
Conjugate priors from natural parameters. ● For a scalar natural parameter , the conjugate prior (24.4.10) reads , and observations update it by and .
- For the Poisson, and . Change variables from to , including the Jacobian, and show that the prior on is a Gamma distribution. Identify its shape and rate, and check that the update reproduces the Gamma posterior of Section 24.4.5.3.
- For the Bernoulli, and . Show that the prior on is , and find the values of for which it is normalizable.
- Take the flat prior on the logit, . Which density on does it induce, and is that density normalizable? After heads in flips, when is the posterior normalizable, and what is its mean? Compare it with the mean of the posterior (24.4.9) under the uniform prior on . What does the comparison say about the phrase "a flat prior"?