Maximum entropy and the Gibbs variational principle
Formulate Jaynes's maximum-entropy principle and derive the Gibbs solution, temperature softmax, maximum-likelihood duality, information projection and the Gibbs variational principle used in KL regularization.
After this lesson you can
Solve maximum-entropy problems with moment constraints using Lagrange multipliers.
Prove the Gibbs form and recognize Gaussian, exponential, and softmax special cases.
Derive the duality between maximum entropy with empirical moments and maximum likelihood in the corresponding Gibbs family.
State and verify the information-projection Pythagorean theorem.
Prove the Gibbs variational principle and its relative-entropy form.
Someone has rolled a die many times and tells you only one thing: the mean outcome was 4.5, not 3.5. You must assign probabilities to its six faces to predict the next roll. The problem is severely underdetermined: six unknowns p1,…,p6 and only two equations, ∑kpk=1 and ∑kkpk=4.5. All these distributions are compatible with the observation:
(0,0,0,0.5,0.5,0): the die shows only 4 or 5.
(0.3,0,0,0,0,0.7): it shows only 1 or 6.
(0.024,0.081,0.138,0.195,0.252,0.310): the uniform distribution tilted along a straight line.
The first two assert things no one told you (“1 is impossible,” “3 is impossible”). The third seems reasonable, but a straight line is as arbitrary a choice as any other. In 1957 Edwin T. Jaynes proposed a rule for such problems: among all distributions compatible with what you know, choose the one with greatest entropy. Since Shannon entropy measures remaining uncertainty, maximizing it commits as little as possible: it adds no more information than the constraints contain.
The rule has consequences far beyond dice. We will see that the solution always has the same form, p(x)∝eλ⋅f(x), a Gibbs distribution. From it come temperature softmax, Gaussian and exponential distributions, logistic regression, and the optimal RLHF policy. We will also see that maximizing entropy with empirical moments is exactly equivalent to maximum-likelihood fitting of a log-linear model, that relative entropy has a Pythagorean theorem, and that a single inequality, the Gibbs variational principle, explains why KL appears so often as a regularizer.
The maximum-entropy principle
Fix a finite set of outcomes X and functions f1,…,fK:X→R, the features or statistics, collected in f(x)=(f1(x),…,fK(x))∈RK. Available information consists of their expected values μ∈RK.
The feasible set is the intersection of the simplex and an affine subspace: a convex polytope. Entropy is strictly concave on the simplex, so if the feasible set is nonempty, a maximum exists (the polytope is compact) and is unique. It remains to determine its form.
Why entropy rather than another measure of “spread”? There is an axiomatic justification (Shore and Johnson, 1980: it is the unique update rule consistent with a few consistency requirements), but the clearest is combinatorial and goes back to Boltzmann. Imagine n rolls with counts n1,…,n6. The number of distinct sequences with those counts is the multinomial coefficient, and by Stirling’s approximation
If all sequences with mean 4.5 appear equally plausible a priori, the empirical frequency with the most ways to arise is the maximum-entropy one, and it dominates any other q by a factor en(H(p∗)−H(q)). We will soon see that the exponent is exactly nKL(q∥p∗). With n=1000 and the “only 4 or 5” proposal, the factor is e920. This concentration is a version of Sanov’s theorem and the typical set, and is the underlying reason maximum entropy works in statistical mechanics: so many more microscopic configurations agree with it than with any alternative that, in practice, it is the only one observed.
The solution has Gibbs form
A calculation with Lagrange multipliers suggests the answer. The Lagrangian, with multiplier λk for each moment and ν for normalization, is
Differentiate with respect to each p(x) and set to zero: −logp(x)−1+λ⋅f(x)+ν=0, that is, p(x)=eν−1eλ⋅f(x). Normalization fixes the constant and leaves an exponential of a linear combination of features. You will do this calculation carefully in the first exercise; for now we name the result.
Gibbs distributions with free λ form an exponential family with sufficient statistic f and natural parameter λ. The Lagrange calculation gives only a necessary condition (without justifying that the maximum lies in the simplex interior, where derivatives make sense). The next theorem settles everything at once with a one-line identity.
Proof
Since p∗(x)>0 for every X, KL(q∥p∗) is finite and can be separated:
The last sum depends on q only through Eq[f]=μ: it equals λ∗⋅μ−A(λ∗). Thus KL(q∥p∗)=−H(q)−λ∗⋅μ+A(λ∗). Taking q=p∗, which also satisfies the constraints, 0=−H(p∗)−λ∗⋅μ+A(λ∗), giving H(p∗); subtracting the equalities yields the identity. By Gibbs’ inequality, KL(q∥p∗)≥0 with equality only if q=p∗.
∎
The identity is stronger than “p∗ is the maximum”: it gives exactly how much entropy is lost by choosing another compatible distribution, and that loss is a Kullback–Leibler divergence. It is also the concentration exponent in the previous section.
For the die, f(k)=k and p∗(k)∝eλk: a geometric progression with ratio eλ. With mean 4.5 the equation ∑kkeλk/∑keλk=4.5 has no closed-form solution, but its left side increases with λ and can be solved numerically: λ∗=0.371049 and
Each face is e0.371≈1.45 times more likely than the preceding one. The “only 4 or 5” proposal has entropy 1 bit, and the identity predicts KL(q∥p∗)=2.3279−1=1.3279 bits, which you can check by summing. Even the linear ramp from the motivation, which looks very like p∗, reaches 2.3019 bits: it lacks 0.026 bits, its KL relative to p∗.
InteractiveJaynes's die
maximum entropy p∗
your proposal q (draggable)
mean μ
Entropy of 300 random compatible distributions (bits)
No samples: only one compatible distribution exists.
Dual g(λ)=logZ(λ)−λμ (nats)
Minimum g(λ*) = 1.6136 nats = H(p*).
Your proposal q
Multiplier λ0.3710
H(p∗)2.3279 bits
H(q)1.0000 bits
H(p∗)−H(q)1.3279 bits
KL(q∥p∗)1.3279 bits
Mean and variance of q4.500, 0.250
It meets the same constraints and has 1.328 bits less entropy: exactly KL(q∥p∗).
Set the mean μ and inspect maximum-entropy distribution p∗ (gray outline), a geometric progression whose ratio eλ is controlled by the multiplier. Blue bars are your proposal q: drag them and the rest readjust to satisfy the constraints. Compare the highlighted readings: H(p∗)−H(q) and KL(q∥p∗) always agree. At bottom left, 300 random compatible distributions: none crosses the H∗ line. At right, the dual g(λ), whose minimum is λ∗ and value H(p∗) in nats. Enable variance: p∗ becomes a ‘discrete Gaussian’ eλ1k+λ2k2. Finally move μ to 6: what happens to the dual?
Three things the figure shows and the rest of the lesson formalizes:
More constraints, less entropy. With mean 4.5 and variance 1, the solution is p∗∝e3.8386k−0.4181k2, with H=2.0112 bits: the quadratic term with negative coefficient concentrates mass around the mean. Each added constraint is information and reduces the uncertainty that can be retained.
The multiplier measures constraint tension. With μ=3.5, λ=0 and p∗ is uniform: the constraint does not bind. The farther μ is from the center, the larger ∣λ∣.
At the boundary there is no Gibbs solution. With μ=6 the only compatible distribution always rolls 6, and no pλ with finite λ assigns zero mass to the other faces: λ∗=+∞. The dual decreases without attaining its infimum. We return to this in the partition-function section.
Special cases
The same recipe, “maximize entropy subject to these moments,” yields almost every named distribution. The continuous case needs care: maximize differential entropyh(p)=−∫plogp and prove the theorem as before, replacing sums by integrals (identity h(q)=h(p∗)−KL(q∥p∗) holds for any density q with the same moments).
Support
Constraints
Gibbs solution
Maximum entropy
{1,…,n}
none
uniform
logn
{0,1,2,…}
E[X]=m
geometric, p(k)∝θk, θ=1+mm
(1+m)log(1+m)−mlogm
[a,b]
none
uniform
log(b−a)
[0,∞)
E[X]=m
exponential, p(x)=m1e−x/m
1+logm
R
E[∣X∣]=b
Laplace, p(x)=2b1e−∣x∣/b
1+log(2b)
R
E[X]=m, Var(X)=σ2
N(m,σ2)
21log(2πeσ2)
Rd
mean m, covariance Σ
N(m,Σ)
21log((2πe)ddetΣ)
The exponential arises with f(x)=x: p(x)∝eλx is integrable on [0,∞) only if λ<0, and the mean fixes λ=−1/m. The Gaussian arises with f(x)=(x,x2): p(x)∝eλ1x+λ2x2, integrable if λ2<0, which becomes a normal distribution on completing the square; this is the Gaussian maximum-entropy property. Notice the logic: distribution shape is determined by the constrained features, not an assumption about the world. Fixing E[X2] gives Gaussian tails; fixing E[∣X∣] gives exponential tails.
Softmax is a Gibbs distribution
The most important machine-learning case appears by reversing the problem. You have n options with scores s1,…,sn (a language model’s logits, an agent’s action values Q(s,a)) and seek a distribution q with high expected score that does not become deterministic. Two natural formulations are:
Constrained: maximize H(q) subject to Eq[s]=m. This is maximum entropy with one feature, f=s, and solution q∝eλs.
Penalized: maximize Eq[s]+TH(q) for entropy price T>0. Dividing by T gives maximization of Eq[s/T]+H(q), and the variational-principle section will show the solution is q∝es/T.
Both give temperature softmax, qT(x)=softmax(s/T)x=esx/T/∑yesy/T, with λ=1/T. Temperature is literally the inverse Lagrange multiplier of the constraint. As T→0, qT concentrates on the argmax of s; as T→∞, it tends to uniform.
There is clean geometry behind this. Plot each distribution q as point (Eq[s],H(q)) in the plane. For each mean score m between minxsx and maxxsx (with scores not all equal), the greatest achievable entropy is H∗(m)=A(λ(m))−λ(m)m, and curve m↦H∗(m) is the frontier of the cloud. Differentiating by the chain rule and using A′(λ)=m, proved in the next section,
where qT is the Gibbs distribution with λ(m)=1/T and λ′(m)=1/A′′(λ) because m=A′(λ). The frontier is concave and its slope at the softmax point is −1/T. Level lines of the penalized objective, Eq[s]+TH(q)=c, have exactly that slope; maximizing the objective shifts the line upward until it last touches the cloud, at the frontier’s tangency point.
InteractiveTemperature as the price of entropy
qT(x)∝esx/T
Each distribution is a point (Eq[s],H(q))
frontier, T>0
frontier, T<0
line of slope −1/T
random distributions
Fix
T1.000
Eq[s]1.6224
H(q)1.3881 nats
Eq[s]/T+H(q)3.01046
log∑xesx/T3.01046
Best in cloud…
The line of slope −1/T touches the frontier at qT: no cloud distribution exceeds E+TH at that value.
Six options with fixed scores. At left, softmax qT∝es/T; at right, each distribution is a point (Eq[s],H(q)) in nats: the gray cloud contains random distributions and the blue curve is the Gibbs family with T>0. Move T: the orange line, slope −1/T, touches the frontier exactly at qT, and no distribution in the cloud beats the objective (compare ‘Best in cloud’ with log∑xesx/T). Switch to ‘Fix entropy’: choose H0 and the interactive finds the T producing it, like automatic temperature tuning in SAC. Enable negative temperature to follow the other branch.
“Fix entropy” takes the constrained viewpoint: impose H(q)=H0 and temperature stops being a hyperparameter and becomes the needed multiplier. This is exactly what SAC does with temperature α: it fixes a target policy entropy and adjusts α by dual descent. The negative-temperature branch corresponds to minimizers: with T<0 softmax favors low scores.
The partition function
Everything important about a Gibbs family is encoded in one convex function, the log-partition A(λ)=log∑xh(x)eλ⋅f(x). In physics, “the partition function knows everything”; here two derivatives show why.
Proof
Differentiating A=logZ gives ∂kA=Z1∑xh(x)fk(x)eλ⋅f(x)=∑xpλ(x)fk(x). Differentiating again, using ∂jpλ(x)=pλ(x)(fj(x)−∂jA),
A covariance matrix is positive semidefinite: u⊤∇2Au=Varpλ(u⋅f)≥0. Since pλ assigns positive mass to every X, that variance vanishes only if u⋅f is constant on X.
∎
Thus the moment map λ↦∇A(λ) is the gradient of a convex function. Its image is the interior of the moment polytope (marginal polytope) M=conv{f(x):x∈X}, the set of values Eq[f] some distribution can produce.
Proof
Uniqueness follows from strict convexity. For existence it suffices to show g is coercive. Take a unit direction u. As t→∞, A(λ+tu)=tmaxxu⋅f(x)+O(1), because the largest exponential term dominates the sum. Therefore g(λ+tu)=t(maxxu⋅f(x)−u⋅μ)+O(1). If μ is interior, u⋅μ<maxxu⋅f(x) for every u (otherwise hyperplane {v:u⋅v=u⋅μ} would support M at μ), so g grows linearly in all directions; by compactness of the unit sphere and continuity, growth is uniform and g attains its minimum, where ∇g=∇A−μ=0. If μ is on the boundary, some u has u⋅μ=maxxu⋅f(x), and along that direction g strictly decreases: the minimum escapes to infinity.
∎
This is what you saw with μ=6: with u=1, maxkk=6=μ, and g(λ)=log∑keλ(k−6) decreases toward 0 without reaching it. The infimum has meaning (the entropy of the unique compatible distribution, deterministic), but the multiplier does not exist.
Duality: maximum entropy is maximum likelihood
Maximum entropy is a convex problem (concave objective, linear constraints), and its dual function comes from maximizing the Lagrangian over p. The Gibbs theorem identity avoids differentiation: for any λ and any feasible q,
H(q)=A(λ)−λ⋅μ−KL(q∥pλ)≤A(λ)−λ⋅μ=g(λ).
(This is the theorem proof’s calculation, which did not use optimality of λ, only Eq[f]=μ.) This is weak duality: any λ gives an upper bound on maximum entropy. The bound is exact at λ∗, because q=pλ∗ is then feasible and KL vanishes. The dual problem,
λ∈RKming(λ)=A(λ)−λ⋅μ,
is convex, unconstrained, and of dimension K (number of constraints), not ∣X∣. Its gradient is Epλ[f]−μ, the moment error, and its Hessian the feature covariance: Newton’s method writes itself and converges quadratically. You will implement it below.
Now the twist. Suppose moments come from a sample, not an oracle: μ=μ^=n1∑i=1nf(xi). Forget maximum entropy and fit the log-linear model pλ by maximum likelihood.
Proof
logpλ(xi)=λ⋅f(xi)−A(λ) with h≡1. Averaging over the sample gives n1∑ilogpλ(xi)=λ⋅μ^−A(λ). The two functions of λ are identical, so have the same minimizer, which sets the gradient to zero: Epλ∗[f]=μ^. Existence and uniqueness are those of the multiplier theorem, and the minimum value is g(λ∗)=H(p∗) by the Gibbs theorem.
∎
Interior placement matters. With indicator features fx(y)=1[y=x] for every outcome except one (which are minimal), if one of those outcomes never occurs in the sample, μ^x=0, μ^ lies on the polytope boundary, the maximum-likelihood estimator does not exist (that outcome’s parameter escapes to −∞), and maximum entropy assigns it zero probability. This is the same phenomenon as the die with μ=6, and the underlying reason for count smoothing and regularization.
Read in both directions, the theorem illuminates the problem. From statistics: the maximum-likelihood estimator of an exponential family matches moments of sufficient statistics and, among all distributions matching them, chooses the most uncertain. From information theory: optimal value g(λ∗) is the minimum cross-entropy between empirical distribution and model, in nats per observation. For empirical distribution p^, g(λ)=H(p^,pλ)=H(p^)+KL(p^∥pλ), and pλ∗ is the projection of p^ onto the exponential family in the minλKL(p^∥pλ) sense.
The conditional version is most common. If you model p(y∣x)∝exp(wy⊤x) and require that the expected value of each feature xj1[y=c] under the model on the data match its empirical count, ∑ixijp(c∣xi)=∑ixij1[yi=c], you obtain the optimality condition for multinomial logistic regression. Softmax regression is a conditional maximum-entropy model; you will check this with scikit-learn at the end.
Minimum relative entropy and I-projection
Maximum entropy treats every outcome equally. But often you have a prior distribution p (a reference model, an older estimate) and receive new information as moments. Kullback’s natural generalization seeks the distribution compatible with the information that deviates least from p.
With p uniform over n outcomes, KL(q∥p)=logn−H(q): minimizing KL maximizes entropy. Maximum entropy is the I-projection of uniform. The Lagrange calculation, now with −KL(q∥p) as objective, gives q∗∝peλ⋅f: the Gibbs distribution with reference measure h=p. The prior is exponentially tilted toward the constraint, by the minimum necessary.
The last term equals λ∗⋅μ−A(λ∗), because Er[f]=μ. But q∗ also lies in L, so the same number is Eq∗[log(q∗/p)]=KL(q∗∥p). For the general convex inequality: if r∈E, qt=(1−t)q∗+tr∈E and t↦KL(qt∥p) has its minimum at t=0, so its right derivative at 0, equal to ∑x(r(x)−q∗(x))log(q∗(x)/p(x)), is nonnegative. This condition rewrites exactly as KL(r∥p)−KL(r∥q∗)−KL(q∗∥p)≥0 (when r≪q∗; otherwise the right side is infinite and Csiszár shows the left side is then infinite too).
∎
The name makes sense in a picture. p is a point outside line L, q∗ is the perpendicular foot, and r another point on the line: “hypotenuse squared equals the sum of the squares of the legs,” with KL as squared distance. Perpendicularity has a precise meaning: exponential family {peλ⋅f/Z} through p intersects L at q∗, and they are “orthogonal” in information geometry (the Fisher metric encountered in the Sanov lesson).
InteractivePythagoras on the simplex
Distributions over {1,2,3}: each vertex is a certain outcome
segment L: Eq[f]=μ
family q∝peλf
level KL(q∥p)=KL(q∗∥p)
KL(r∥p)
KL(r∥q∗)+KL(q∗∥p)
q∗(0.170, 0.310, 0.520)
Multiplier λ1.209
KL(r∥p)0.5189 nats
KL(r∥q∗)+KL(q∗∥p)0.5189 nats
Difference0.000000
Wherever you move r, the bars are equal: KL(r∥p)=KL(r∥q∗)+KL(q∗∥p).
The triangle contains distributions over three outcomes (each vertex is a certain outcome). Constraint Eq[f]=μ is the aquamarine segment L. Drag prior p (blue): its I-projection q∗ (magenta) is the intersection of L with exponential family q∝peλf through p (dashed), and the level curve of KL(⋅∥p) through q∗ is tangent to L. Drag r (orange) along the segment: the two bars below always agree. Enable comparison with reverse projection argminqKL(p∥q): point qM differs and the sum no longer matches. All values are in nats.
Two readings of the theorem to keep in mind:
Argument order matters. The “reverse” projection argminq∈LKL(p∥q) (M-projection) is another point and has no Pythagorean theorem on linear families. Symmetry lies elsewhere: M-projection does satisfy Pythagoras on exponential families, the maximum-likelihood fitting version from the previous section. The projections are dual; algorithms such as iterative proportional fitting exploit this by alternating I-projections on linear constraints.
It probabilistically justifies maximum entropy. Conditional Sanov says that if you draw n iid samples from p and condition on the empirical mean of f being μ, the distribution of any sample converges to I-projection q∗ as n→∞ (Csiszár, 1984). If you know only moments, the most likely conditional distribution is Gibbs. See the Sanov lesson.
The Gibbs variational principle
We reach the identity unifying everything above. So far we fixed moments and sought a distribution; now fix a function f and seek the distribution that best balances “being where f is large” with “not moving away from p.”
This is the Gibbs variational principle. The second hypothesis ensures q∗ itself is admissible: Eq∗∣f∣=Ep[∣f∣ef]/Ep[ef]. Without it the equality holds as a supremum, but may not be attained. The proof again splits a logarithm: logq∗q=logpq−f+logEp[ef], then takes expectations under q. You will do it in the second guided exercise. Its special case with p uniform on finite X (adding log∣X∣ to both sides) is the free-energy form:
logx∑ef(x)=q∈Δ(X)max{Eq[f]+H(q)}.
With f=−E/T and multiplying by −T we obtain −TlogZ=minq{Eq[E]−TH(q)}: Helmholtz free energy F=U−TS is the minimum of mean energy minus temperature times entropy, attained by the Boltzmann distribution. In the softmax interactive this is the tangent line Eq[s]+TH(q)=Tlog∑xesx/T, which intersects axis Eq[s]=0 at height log∑xesx/T, the corresponding readout.
The relative form has a useful dual reading. Rearranging, every bounded f satisfies KL(q∥p)≥Eq[f]−logEp[ef], with equality at f=log(q/p) plus a constant (if that function is unbounded, the supremum is approached by truncating it). That is,
KL(q∥p)=fsup{Eq[f]−logEp[ef]},
the Donsker–Varadhan formula seen as the variational representation of KL. The formulas are the same assertion viewed from either side of Fenchel duality: q↦KL(q∥p) and f↦logEp[ef], the log moment-generating function (cumulant-generating function), are convex conjugates.
Why it appears everywhere
Whenever a problem has the form “maximize an expected objective without moving too far, in KL, from a reference,” the variational principle gives a closed-form solution:
RLHF. The preference-fitting objective is maxπEy∼π[r(y)]−βKL(π∥πref) for each prompt. With f=r/β and p=πref, the optimal policy is π∗(y)∝πref(y)er(y)/β and optimal value βlogEπref[er/β]. DPO starts from this closed form (RLHF objective).
Variational inference. With p(z∣x)∝p(x,z), the principle says logp(x)=maxq{Eq[logp(x,z)]+H(q)}: the ELBO bound is the variational-principle objective, and its gap is KL(q∥p(⋅∣x)) (variational inference).
KL-regularized optimization. Entropy-regularized RL policies, multiplicative updates, PAC-Bayes: in all of them the optimum is a Gibbs distribution relative to the reference. See KL as a regularizer.
Interpretations in machine learning
The three pieces (Gibbs, duality, variational principle) put familiar constructions in a new light.
Log-linear and energy-based models. A softmax classifier, conditional random field, or energy-based model is a Gibbs distribution. Maximum-likelihood training matches model feature moments to data moments, and the whole difficulty lies in ∇A=Epλ[f], which requires model samples when X is enormous. That is why the partition function bottlenecks these models.
Maximum-entropy RL. Adding αH(π(⋅∣s)) to reward turns the maximum in Bellman’s equation into a soft maximum: V(s)=αlog∑aeQ(s,a)/α and π(a∣s)∝eQ(s,a)/α. This applies the variational principle state by state (maximum-entropy RL).
Temperature as multiplier. Sampling a language model at temperature T chooses the score–entropy frontier point with slope −1/T. Fixing a target entropy and adjusting T, as in SAC, solves the constrained problem through its dual.
Implementation from scratch
Follow the dual plan: minimize g(λ)=A(λ)−λ⋅μ with damped Newton. The gradient is moment error and the Hessian is feature covariance; both use pλ itself, and A always uses log-sum-exp.
[ ]Maximum entropy via the dual with NewtonBrowser
import numpy as np
def logsumexp(a):
"""log Σ exp(a) sin desbordar: se resta el máximo antes de exponenciar."""
a = np.asarray(a, dtype=float)
m = a.max()
return m + np.log(np.exp(a - m).sum())
def gibbs(lam, F, logh=None):
"""p(x) ∝ h(x) exp(λ·f(x)) sobre un soporte finito. F tiene forma (K, n)."""
w = lam @ F + (0.0 if logh is None else logh)
return np.exp(w - logsumexp(w))
def maxent_newton(F, mu, logh=None, tol=1e-10, max_iter=60, verbose=False):
"""Minimiza el dual g(λ) = log Z(λ) − λ·μ con Newton amortiguado."""
F = np.atleast_2d(np.asarray(F, dtype=float))
mu = np.atleast_1d(np.asarray(mu, dtype=float))
lam = np.zeros(F.shape[0])
dual = lambda l: logsumexp(l @ F + (0.0 if logh is None else logh)) - l @ mu
for it in range(max_iter):
p = gibbs(lam, F, logh)
m = F @ p # ∇ log Z = E_p[f]
g = m - mu # gradiente del dual
if verbose:
print(f" it {it} ‖∇g‖ = {np.linalg.norm(g):.2e} λ = {np.round(lam, 6)}")
if np.linalg.norm(g) < tol:
break
C = (F * p) @ F.T - np.outer(m, m) # ∇² log Z = Cov_p[f]
d = np.linalg.solve(C, g) # paso de Newton
t, g0 = 1.0, dual(lam)
# retroceso de Armijo, con una holgura del tamaño del redondeo: cerca del óptimo
# la mejora del dual es menor que el error de coma flotante y no debe frenar el paso
while dual(lam - t * d) > g0 - 0.25 * t * (g @ d) + 1e-12 and t > 1e-12:
t /= 2
lam = lam - t * d
return lam, gibbs(lam, F, logh), it
def H_bits(p):
p = p[p > 0]
return -(p * np.log2(p)).sum()
caras = np.arange(1, 7)
print("Dado de Jaynes, media 4.5:")
lam, p, its = maxent_newton(caras[None, :], [4.5], verbose=True)
print(f"λ = {lam[0]:.6f} p = {np.round(p, 4)} H = {H_bits(p):.4f} bits")
# comprobación independiente: la media de p_λ crece con λ, así que basta una bisección
lo, hi = -20.0, 20.0
for _ in range(200):
mid = (lo + hi) / 2
lo, hi = (mid, hi) if gibbs(np.array([mid]), caras[None, :]) @ caras < 4.5 else (lo, mid)
print(f"bisección: λ = {lo:.6f}")
print("\nMedia 4.5 y varianza 1 (segundo momento 21.25):")
F2 = np.vstack([caras, caras**2])
lam2, p2, its2 = maxent_newton(F2, [4.5, 21.25])
print(f"λ = {np.round(lam2, 4)} p = {np.round(p2, 4)} H = {H_bits(p2):.4f} bits iteraciones: {its2}")
print("momentos de p:", np.round(F2 @ p2, 10))
Gradient norm goes from 1 to 6.6×10−2, 10−3, 3×10−7, and 2×10−14: correct digits double at each step, Newton’s quadratic convergence. Starting from λ=0 (uniform), four iterations suffice.
What if constraints lie at the boundary of the moment polytope? The next cell shows what Newton does when the minimum does not exist.
[ ]Boundary constraints: the dual divergesBrowser
import matplotlib.pyplot as plt
for mu in [5.9, 5.99, 5.999]:
lam, p, its = maxent_newton(caras[None, :], [mu])
print(f"μ = {mu:<6} iteraciones = {its:2d} λ = {lam[0]:7.3f} p(6) = {p[5]:.6f}")
print("\nμ = 6, Newton puro:")
lam = 0.0
for it in range(1, 13):
p = gibbs(np.array([lam]), caras[None, :])
m, v = p @ caras, p @ caras**2 - (p @ caras) ** 2
lam -= (m - 6) / v
if it % 2 == 0:
g = logsumexp(lam * caras) - 6 * lam
print(f" it {it:2d} λ = {lam:7.3f} g(λ) = {g:.2e} E[X] − 6 = {m - 6:.1e}")
ls = np.linspace(-1, 8, 300)
for mu, c in [(4.5, "C0"), (5.9, "C1"), (6.0, "C3")]:
plt.plot(ls, [logsumexp(l * caras) - l * mu for l in ls], color=c, label=f"μ = {mu}")
plt.xlabel("λ"); plt.ylabel("g(λ) = log Z(λ) − λμ"); plt.legend(); plt.show()
Near the boundary, λ∗ grows as −log of the distance to the boundary (with μ=6−ε, λ∗≈log(1/ε)) and Newton still converges, although it initially needs more damped steps. The 10−12 slack in line search matters: without it, with μ=5.99, backtracking rejects good steps because improvement in the dual is below rounding, and the method stalls at gradient 6×10−10 until iterations are exhausted. At the boundary, each iteration adds approximately 1 to λ forever: for large λ, E[X]≈6−e−λ and Var(X)≈e−λ, so step −(E[X]−6)/Var(X) is almost exactly 1. No step-size criterion detects this; first check that μ is inside M (in one dimension, minf<μ<maxf; in general, a linear feasibility program with margin).
Now duality with maximum likelihood in a two-variable log-linear model x1,x2∈{0,1,2} with features x1, x2, and interaction x1x2. Data come from a distribution outside the family.
[ ]Maximum entropy and maximum likelihood give the same λBrowser
from scipy.optimize import minimize
rng = np.random.default_rng(0)
X = np.array([(a, b) for a in range(3) for b in range(3)]) # 9 resultados
F = np.vstack([X[:, 0], X[:, 1], X[:, 0] * X[:, 1]]).astype(float) # (3, 9)
verdad = np.array([0.20, 0.05, 0.02, 0.08, 0.15, 0.07, 0.03, 0.10, 0.30]) # fuera de la familia
datos = rng.choice(9, size=400, p=verdad)
mu_emp = F[:, datos].mean(axis=1)
print("momentos empíricos:", np.round(mu_emp, 4))
lam_me, p_me, _ = maxent_newton(F, mu_emp)
def nll(l):
"""Log-verosimilitud negativa media de la familia de Gibbs, sin saber nada de entropías."""
return -np.mean(l @ F[:, datos] - logsumexp(l @ F))
lam_mv = minimize(nll, np.zeros(3), method="BFGS", options={"gtol": 1e-10}).x
print("λ por máxima entropía: ", np.round(lam_me, 5))
print("λ por máx. verosimilitud:", np.round(lam_mv, 5))
print("momentos del modelo: ", np.round(F @ p_me, 4))
for l in rng.normal(size=(3, 3)):
print(f" λ al azar: NLL(λ) = {nll(l):.10f} dual g(λ) = {logsumexp(l @ F) - l @ mu_emp:.10f}")
print(f"H(p*) = {-(p_me * np.log(p_me)).sum():.6f} nats NLL(λ*) = {nll(lam_me):.6f} nats")
Both paths give the same λ; the model reproduces the three empirical moments, and negative log-likelihood matches the dual at every λ, not only the optimum: they are literally the same function. Optimal value 1.863 nats is both maximum entropy and the mean cost of encoding data with the fitted model.
Finally, Pythagoras and the variational principle with random distributions and features. For I-projection, simply pass logp as reference measure to the same solver.
[ ]Pythagoras and the variational principle, numericallyBrowser
rng = np.random.default_rng(1)
n = 5
p = rng.dirichlet(np.ones(n)) # previa
F = rng.normal(size=(2, n)) # dos características
mu = F @ rng.dirichlet(np.ones(n)) # momentos alcanzables
lam, q, _ = maxent_newton(F, mu, logh=np.log(p)) # I-proyección de p sobre L
KL = lambda a, b: np.sum(a[a > 0] * np.log(a[a > 0] / b[a > 0]))
# puntos r de L: q* más una dirección del núcleo de [1; F], sin salir del símplex
A = np.vstack([np.ones(n), F])
N = np.linalg.svd(A)[2][A.shape[0]:]
peor = 0.0
for _ in range(2000):
d = rng.normal(size=N.shape[0]) @ N
tmax = np.min(np.where(d < 0, -q / np.where(d < 0, d, -1), np.inf))
r = q + rng.uniform(0, tmax) * d
peor = max(peor, abs(KL(r, p) - KL(r, q) - KL(q, p)))
print(f"2000 puntos r de L: máx |D(r‖p) − D(r‖q*) − D(q*‖p)| = {peor:.1e}")
f = 2 * rng.normal(size=n)
valor = np.log(p @ np.exp(f))
qg = p * np.exp(f) / (p @ np.exp(f))
print(f"log E_p[e^f] = {valor:.10f} E_q*[f] − D(q*‖p) = {qg @ f - KL(qg, p):.10f}")
otras = rng.dirichlet(np.ones(n), size=5000)
print(f"mejor de 5000 q al azar: {max(o @ f - KL(o, p) for o in otras):.6f}")
The Pythagorean equality holds to machine rounding at 2000 points of L, and none of 5000 random distributions exceeds value logEp[ef] attained by the Gibbs distribution.
With libraries
In practice, solve the dual with a generic optimizer supplied with gradient and Hessian; scipy.special.logsumexp and softmax handle stability, and conditional maximum entropy directly uses logistic regression.
[ ]The dual with scipy and logistic regression as maximum entropyBrowser
from scipy.optimize import minimize
from scipy.special import logsumexp as lse, softmax
from sklearn.linear_model import LogisticRegression
F1 = caras[None, :].astype(float)
mu = np.array([4.5])
dual = lambda l: lse(l @ F1) - l @ mu
grad = lambda l: F1 @ softmax(l @ F1) - mu
def hess(l):
p = softmax(l @ F1); m = F1 @ p
return (F1 * p) @ F1.T - np.outer(m, m)
res = minimize(dual, np.zeros(1), jac=grad, hess=hess, method="trust-exact")
print(f"scipy: λ = {res.x[0]:.6f} en {res.nit} iteraciones p = {np.round(softmax(res.x @ F1), 4)}")
# regresión softmax sin regularización: iguala los momentos x_j · 1[y = c]
rng = np.random.default_rng(0)
centros = np.array([[0, 0], [1.5, 0.5], [0.5, 1.5]])
y = rng.integers(0, 3, size=600)
Xd = centros[y] + rng.normal(scale=0.9, size=(600, 2))
clf = LogisticRegression(C=1e8, max_iter=5000, tol=1e-10).fit(Xd, y)
P = clf.predict_proba(Xd)
Y = np.eye(3)[y]
X1 = np.hstack([np.ones((600, 1)), Xd]) # la columna de unos es el sesgo
with np.printoptions(suppress=True, precision=2):
print("momentos empíricos Σ x_j 1[y=c] (filas: sesgo, x1, x2; columnas: clase):\n", X1.T @ Y)
print("máx |Σ x_j (1[y=c] − p(c|x))| =", f"{np.abs(X1.T @ (Y - P)).max():.1e}")
Multinomial logistic regression fitted without regularization reproduces empirical moments of the nine features xj1[y=c] (including bias) to optimizer tolerance: it is the conditional maximum-entropy model with those constraints. With L2 regularization, the optimality condition becomes “empirical count minus model count equals wc/C” for each weight (bias is unregularized and still exactly matched): maximum entropy with “soft” constraints, allowed to miss moments in exchange for small weights.
Common mistakes
Exercises
NumericThe unbiased die
What is the maximum entropy in bits of a six-sided die whose only known property is mean 3.5?
NumericKL without calculating the distribution
The maximum-entropy distribution of a die with mean 4.5 has H(p∗)=2.3279 bits. Without calculating p∗, what is KL(q∥p∗) in bits for q=(0,0,0.25,0.25,0.25,0.25)?
NumericA mean lifetime
A waiting time X≥0 has mean 2 and nothing else is known. What is the maximum differential entropy in nats consistent with this information?
NumericA free energy
For three options with scores s=(0,log3,log4), what is the maximum of Eq[s]+H(q) over all distributions q (entropy in nats)?
NumericThe optimal RLHF policy
A reference model assigns equal probability to 4 responses. Rewards are r=(1,0,0,0) and the KL coefficient is β=0.5. What probability does the policy maximizing Eπ[r]−βKL(π∥πref) assign to the first response?
QuizContinuous maximum entropy
Which distribution maximizes differential entropy on [0,∞) with fixed mean, and which on R with fixed mean and variance?
QuizHas Jaynes been refuted?
You assign the maximum-entropy distribution to a die with mean 4.5, giving face 6 probability 0.3475. You roll it 10000 times: the mean remains 4.5 but 6 occurs with frequency 0.25. What conclusion is correct?
QuizWhat is true and what is not
Let p∗=pλ∗ be the maximum-entropy distribution with E[f]=μ, μ interior to the moment polytope. Which statements are true?
More than one answer may be correct.
ProofGibbs form via Lagrange
Prove: The solution of maxpH(p) subject to ∑xp(x)fk(x)=μk (k=1,…,K) and ∑xp(x)=1, on finite set X, has form p(x)=eλ⋅f(x)/Z(λ).
0
Assume the problem is feasible with some full-support distribution.
Step 1 of 4. What Lagrangian do you set up?
ProofThe Gibbs variational principle
Prove: On a finite set, with pf(x)=ef(x)/Z and Z=∑xef(x), every distribution q satisfies Eq[f]+H(q)=logZ−KL(q∥pf). Consequently logZ=maxq{Eq[f]+H(q)}, with unique maximum at q=pf.
0
Fix any distribution q on X.
Step 1 of 4. Where do you start?
CodeMaximum entropy via the dual
Implement maxent_dual(F, mu) to solve maximum entropy on finite support with constraints Ep[fk]=μk. F is a (K, n) matrix with fk(x) in row k and mu a vector of length K. Return (lam, p): multiplier λ∈RK and distribution p(x)∝eλ⋅f(x), which must satisfy moments with error below 10−7. Minimize dual logZ(λ)−λ⋅μ with Newton (gradient: moments minus μ; Hessian: covariance), compute logZ with log-sum-exp, and damp the step if needed. Tests use feasible interior constraints.
import numpy as np
def maxent_dual(F, mu, tol=1e-10, max_iter=100):
"""Máxima entropía con E_p[f_k] = mu_k. F: (K, n); mu: (K,). Devuelve (lam, p)."""
F = np.atleast_2d(np.asarray(F, dtype=float))
mu = np.atleast_1d(np.asarray(mu, dtype=float))
lam = np.zeros(F.shape[0])
# tu código: Newton sobre g(lam) = log Z(lam) - lam·mu
p = np.full(F.shape[1], 1.0 / F.shape[1])
return lam, p
Shift+Enter to run
Summary
Key idea
Among all distributions with given moments, the maximum-entropy one is Gibbs p∝eλ⋅f, and any other loses exactly KL(q∥p∗) of entropy; the same calculation gives maximum-likelihood duality, I-projection Pythagoras, and variational principle logEp[ef]=maxqEq[f]−KL(q∥p).
Principle. Given only moments E[f]=μ, choose the maximum-entropy distribution: it assumes the least and concentrates exponentially more compatible configurations in n.
Gibbs form. The solution is pλ∝heλ⋅f, and for every compatible q, H(q)=H(p∗)−KL(q∥p∗). Uniform, geometric, exponential, Laplace, Gaussian, and temperature softmax are special cases; T=1/λ is the price of entropy and the score–entropy frontier slope is −1/T.
Log-partition.A=logZ is convex, ∇A=E[f] and ∇2A=Cov[f]. The multiplier exists if and only if μ is inside the moment polytope; at the boundary the dual has no minimum. Always compute with log-sum-exp.
Duality. Minimize dual A(λ)−λ⋅μ with Newton (gradient: moment error; Hessian: covariance); with empirical moments it is exactly the negative log-likelihood of the log-linear model: maximum entropy and maximum likelihood are the same problem.
I-projection.argminq∈LKL(q∥p)∝peλ⋅f and satisfies Pythagoras: KL(r∥p)=KL(r∥q∗)+KL(q∗∥p) for every r in the linear family. Not with reversed arguments.
Variational principle.logEp[ef]=maxq{Eq[f]−KL(q∥p)} with maximizer q∗∝pef: free energy, softmax as a soft maximum, optimal RLHF policy, ELBO, and Donsker–Varadhan are the same identity.