Module contents
Lesson 13 of 19Advanced 105 min

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.

Before you start

Motivation: Jaynes’s die

Someone has rolled a die many times and tells you only one thing: the mean outcome was 4.54.5, not 3.53.5. You must assign probabilities to its six faces to predict the next roll. The problem is severely underdetermined: six unknowns p1,…,p6p_1, \dots, p_6 and only two equations, ∑kpk=1\sum_k p_k = 1 and ∑kk pk=4.5\sum_k k\,p_k = 4.5. All these distributions are compatible with the observation:

  • (0,0,0,0.5,0.5,0)(0, 0, 0, 0.5, 0.5, 0): the die shows only 4 or 5.
  • (0.3,0,0,0,0,0.7)(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)(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)p(x) \propto e^{\lambda \cdot 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\mathcal{X} and functions f1,…,fK:X→Rf_1, \dots, f_K: \mathcal{X} \to \R, the features or statistics, collected in f(x)=(f1(x),…,fK(x))∈RKf(x) = (f_1(x), \dots, f_K(x)) \in \R^K. Available information consists of their expected values μ∈RK\mu \in \R^K.

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 nn rolls with counts n1,…,n6n_1, \dots, n_6. The number of distinct sequences with those counts is the multinomial coefficient, and by Stirling’s approximation

n!n1!⋯n6!=e n H⁡(p^)+O(log⁡n),p^=(n1/n,…,n6/n).\frac{n!}{n_1! \cdots n_6!} = e^{\,n\,\Ent(\hat p) + \bigO(\log n)}, \qquad \hat p = (n_1/n, \dots, n_6/n).

If all sequences with mean 4.54.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 qq by a factor en(H⁡(p∗)−H⁡(q))e^{n(\Ent(p^*) - \Ent(q))}. We will soon see that the exponent is exactly n KL⁡(q ∥ p∗)n\,\KL(q \,\|\, p^*). With n=1000n = 1000 and the “only 4 or 5” proposal, the factor is e920e^{920}. 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\lambda_k for each moment and ν\nu for normalization, is

L(p,λ,ν)=−∑xp(x)log⁡p(x)+∑k=1Kλk(∑xp(x)fk(x)−μk)+ν(∑xp(x)−1).\mathcal{L}(p, \lambda, \nu) = -\sum_x p(x)\log p(x) + \sum_{k=1}^K \lambda_k\Big(\sum_x p(x) f_k(x) - \mu_k\Big) + \nu\Big(\sum_x p(x) - 1\Big).

Differentiate with respect to each p(x)p(x) and set to zero: −log⁡p(x)−1+λ⋅f(x)+ν=0-\log p(x) - 1 + \lambda \cdot f(x) + \nu = 0, that is, p(x)=eν−1 eλ⋅f(x)p(x) = e^{\nu - 1}\, e^{\lambda \cdot 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 λ\lambda form an exponential family with sufficient statistic ff and natural parameter λ\lambda. 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)>0p^*(x) > 0 for every X\mathcal{X}, KL⁡(q ∥ p∗)\KL(q \,\|\, p^*) is finite and can be separated:

KL⁡(q ∥ p∗)=∑xq(x)log⁡q(x)−∑xq(x)log⁡p∗(x)=−H⁡(q)−∑xq(x)(λ∗⋅f(x)−A(λ∗)).\KL(q \,\|\, p^*) = \sum_x q(x) \log q(x) - \sum_x q(x)\log p^*(x) = -\Ent(q) - \sum_x q(x)\big(\lambda^* \cdot f(x) - A(\lambda^*)\big).

The last sum depends on qq only through Eq[f]=μ\E_q[f] = \mu: it equals λ∗⋅μ−A(λ∗)\lambda^* \cdot \mu - A(\lambda^*). Thus KL⁡(q ∥ p∗)=−H⁡(q)−λ∗⋅μ+A(λ∗)\KL(q \,\|\, p^*) = -\Ent(q) - \lambda^* \cdot \mu + A(\lambda^*). Taking q=p∗q = p^*, which also satisfies the constraints, 0=−H⁡(p∗)−λ∗⋅μ+A(λ∗)0 = -\Ent(p^*) - \lambda^*\cdot\mu + A(\lambda^*), giving H⁡(p∗)\Ent(p^*); subtracting the equalities yields the identity. By Gibbs’ inequality, KL⁡(q ∥ p∗)≥0\KL(q \,\|\, p^*) \ge 0 with equality only if q=p∗q = p^*.

∎

The identity is stronger than “p∗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)=kf(k) = k and p∗(k)∝eλkp^*(k) \propto e^{\lambda k}: a geometric progression with ratio eλe^\lambda. With mean 4.54.5 the equation ∑kk eλk/∑keλk=4.5\sum_k k\,e^{\lambda k} / \sum_k e^{\lambda k} = 4.5 has no closed-form solution, but its left side increases with λ\lambda and can be solved numerically: λ∗=0.371049\lambda^* = 0.371049 and

p∗=(0.0544, 0.0788, 0.1142, 0.1654, 0.2398, 0.3475),H⁡(p∗)=2.3279 bits.p^* = (0.0544,\ 0.0788,\ 0.1142,\ 0.1654,\ 0.2398,\ 0.3475), \qquad \Ent(p^*) = 2.3279 \text{ bits}.

Each face is e0.371≈1.45e^{0.371} \approx 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\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∗p^*, reaches 2.30192.3019 bits: it lacks 0.0260.026 bits, its KL relative to p∗p^*.

InteractiveJaynes's die
0.10.20.30.40.50.6123456
  • maximum entropy p∗p^*
  • your proposal qq (draggable)
  • mean μ\mu
Entropy of 300 random compatible distributions (bits)
No samples: only one compatible distribution exists.
Dual g(λ)=log⁡Z(λ)−λμg(\lambda) = \log Z(\lambda) - \lambda\mu (nats)
Minimum g(λ*) = 1.6136 nats = H(p*).
4.50
Your proposal qq
Multiplier λ\lambda0.3710
H⁡(p∗)\Ent(p^*)2.3279 bits
H⁡(q)\Ent(q)1.0000 bits
H⁡(p∗)−H⁡(q)\Ent(p^*) - \Ent(q)1.3279 bits
KL⁡(q ∥ p∗)\KL(q\,\|\,p^*)1.3279 bits
Mean and variance of qq4.500, 0.250
It meets the same constraints and has 1.328 bits less entropy: exactly KL⁡(q ∥ p∗)\KL(q\,\|\,p^*).
Set the mean μ\mu and inspect maximum-entropy distribution p∗p^* (gray outline), a geometric progression whose ratio eλe^{\lambda} is controlled by the multiplier. Blue bars are your proposal qq: drag them and the rest readjust to satisfy the constraints. Compare the highlighted readings: H⁡(p∗)−H⁡(q)\Ent(p^*) - \Ent(q) and KL⁡(q ∥ p∗)\KL(q\,\|\,p^*) always agree. At bottom left, 300 random compatible distributions: none crosses the H∗H^* line. At right, the dual g(λ)g(\lambda), whose minimum is λ∗\lambda^* and value H⁡(p∗)\Ent(p^*) in nats. Enable variance: p∗p^* becomes a ‘discrete Gaussian’ eλ1k+λ2k2e^{\lambda_1 k + \lambda_2 k^2}. Finally move μ\mu to 6: what happens to the dual?

Three things the figure shows and the rest of the lesson formalizes:

  1. More constraints, less entropy. With mean 4.54.5 and variance 11, the solution is p∗∝e3.8386 k−0.4181 k2p^* \propto e^{3.8386\,k - 0.4181\,k^2}, with H⁡=2.0112\Ent = 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.
  2. The multiplier measures constraint tension. With μ=3.5\mu = 3.5, λ=0\lambda = 0 and p∗p^* is uniform: the constraint does not bind. The farther μ\mu is from the center, the larger ∣λ∣\abs{\lambda}.
  3. At the boundary there is no Gibbs solution. With μ=6\mu = 6 the only compatible distribution always rolls 6, and no pλp_\lambda with finite λ\lambda assigns zero mass to the other faces: λ∗=+∞\lambda^* = +\infty. 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 entropy h(p)=−∫plog⁡ph(p) = -\int p \log p and prove the theorem as before, replacing sums by integrals (identity h(q)=h(p∗)−KL⁡(q ∥ p∗)h(q) = h(p^*) - \KL(q \,\|\, p^*) holds for any density qq with the same moments).

SupportConstraintsGibbs solutionMaximum entropy
{1,…,n}\{1, \dots, n\}noneuniformlog⁡n\log n
{0,1,2,… }\{0, 1, 2, \dots\}E[X]=m\E[X] = mgeometric, p(k)∝θkp(k) \propto \theta^k, θ=m1+m\theta = \frac{m}{1+m}(1+m)log⁡(1+m)−mlog⁡m(1+m)\log(1+m) - m\log m
[a,b][a, b]noneuniformlog⁡(b−a)\log(b - a)
[0,∞)[0, \infty)E[X]=m\E[X] = mexponential, p(x)=1me−x/mp(x) = \frac{1}{m}e^{-x/m}1+log⁡m1 + \log m
R\RE[∣X∣]=b\E[\abs{X}] = bLaplace, p(x)=12be−∣x∣/bp(x) = \frac{1}{2b}e^{-\abs{x}/b}1+log⁡(2b)1 + \log(2b)
R\RE[X]=m\E[X] = m, Var⁡(X)=σ2\Var(X) = \sigma^2N(m,σ2)\Normal(m, \sigma^2)12log⁡(2πeσ2)\tfrac12\log(2\pi e\sigma^2)
Rd\R^dmean m\vb{m}, covariance Σ\mat{\Sigma}N(m,Σ)\Normal(\vb{m}, \mat{\Sigma})12log⁡((2πe)ddet⁡Σ)\tfrac12\log\big((2\pi e)^d\det\mat{\Sigma}\big)

The exponential arises with f(x)=xf(x) = x: p(x)∝eλxp(x) \propto e^{\lambda x} is integrable on [0,∞)[0, \infty) only if λ<0\lambda < 0, and the mean fixes λ=−1/m\lambda = -1/m. The Gaussian arises with f(x)=(x,x2)f(x) = (x, x^2): p(x)∝eλ1x+λ2x2p(x) \propto e^{\lambda_1 x + \lambda_2 x^2}, integrable if λ2<0\lambda_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]\E[X^2] gives Gaussian tails; fixing E[∣X∣]\E[\abs{X}] gives exponential tails.

Softmax is a Gibbs distribution

The most important machine-learning case appears by reversing the problem. You have nn options with scores s1,…,sns_1, \dots, s_n (a language model’s logits, an agent’s action values Q(s,a)Q(s, a)) and seek a distribution qq with high expected score that does not become deterministic. Two natural formulations are:

  • Constrained: maximize H⁡(q)\Ent(q) subject to Eq[s]=m\E_q[s] = m. This is maximum entropy with one feature, f=sf = s, and solution q∝eλsq \propto e^{\lambda s}.
  • Penalized: maximize Eq[s]+T H⁡(q)\E_q[s] + T\,\Ent(q) for entropy price T>0T > 0. Dividing by TT gives maximization of Eq[s/T]+H⁡(q)\E_q[s/T] + \Ent(q), and the variational-principle section will show the solution is q∝es/Tq \propto e^{s/T}.

Both give temperature softmax, qT(x)=softmax⁡(s/T)x=esx/T/∑yesy/Tq_T(x) = \softmax(s/T)_x = e^{s_x/T}/\sum_y e^{s_y/T}, with λ=1/T\lambda = 1/T. Temperature is literally the inverse Lagrange multiplier of the constraint. As T→0T \to 0, qTq_T concentrates on the argmax of ss; as T→∞T \to \infty, it tends to uniform.

There is clean geometry behind this. Plot each distribution qq as point (Eq[s],H⁡(q))(\E_q[s], \Ent(q)) in the plane. For each mean score mm between min⁡xsx\min_x s_x and max⁡xsx\max_x s_x (with scores not all equal), the greatest achievable entropy is H⁡∗(m)=A(λ(m))−λ(m) m\Ent^*(m) = A(\lambda(m)) - \lambda(m)\,m, and curve m↦H⁡∗(m)m \mapsto \Ent^*(m) is the frontier of the cloud. Differentiating by the chain rule and using A′(λ)=mA'(\lambda) = m, proved in the next section,

 ⁣dH⁡∗ ⁣dm=A′(λ) λ′(m)−λ′(m) m−λ=−λ=−1T, ⁣d2H⁡∗ ⁣dm2=−λ′(m)=−1Var⁡qT(s)<0,\frac{\dd \Ent^*}{\dd m} = A'(\lambda)\,\lambda'(m) - \lambda'(m)\,m - \lambda = -\lambda = -\frac{1}{T}, \qquad \frac{\dd^2 \Ent^*}{\dd m^2} = -\lambda'(m) = -\frac{1}{\Var_{q_T}(s)} < 0,

where qTq_T is the Gibbs distribution with λ(m)=1/T\lambda(m) = 1/T and λ′(m)=1/A′′(λ)\lambda'(m) = 1/A''(\lambda) because m=A′(λ)m = A'(\lambda). The frontier is concave and its slope at the softmax point is −1/T-1/T. Level lines of the penalized objective, Eq[s]+T H⁡(q)=c\E_q[s] + T\,\Ent(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/Tq_T(x) \propto e^{s_x/T}
uniform0.44cat2.200.27dog1.700.15fox1.100.09wolf0.600.03car−0.400.01cloud−1.20
Each distribution is a point (Eq[s], H⁡(q))(\E_q[s],\ \Ent(q))
  • frontier, T>0T > 0
  • frontier, T<0T < 0
  • line of slope −1/T-1/T
  • random distributions
Fix
1.00
TT1.000
Eq[s]\E_q[s]1.6224
H⁡(q)\Ent(q)1.3881 nats
Eq[s]/T+H⁡(q)\E_q[s]/T + \Ent(q)3.01046
log⁡∑xesx/T\log \sum_x e^{s_x/T}3.01046
Best in cloud…
The line of slope −1/T-1/T touches the frontier at qTq_T: no cloud distribution exceeds E+T HE + T\,H at that value.
Six options with fixed scores. At left, softmax qT∝es/Tq_T \propto e^{s/T}; at right, each distribution is a point (Eq[s],H⁡(q))(\E_q[s], \Ent(q)) in nats: the gray cloud contains random distributions and the blue curve is the Gibbs family with T>0T > 0. Move TT: the orange line, slope −1/T-1/T, touches the frontier exactly at qTq_T, and no distribution in the cloud beats the objective (compare ‘Best in cloud’ with log⁡∑xesx/T\log\sum_x e^{s_x/T}). Switch to ‘Fix entropy’: choose H0H_0 and the interactive finds the TT 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\Ent(q) = H_0 and temperature stops being a hyperparameter and becomes the needed multiplier. This is exactly what SAC does with temperature α\alpha: it fixes a target policy entropy and adjusts α\alpha by dual descent. The negative-temperature branch corresponds to minimizers: with T<0T < 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)A(\lambda) = \log\sum_x h(x)\,e^{\lambda\cdot f(x)}. In physics, “the partition function knows everything”; here two derivatives show why.

Proof

Differentiating A=log⁡ZA = \log Z gives ∂kA=1Z∑xh(x) fk(x) eλ⋅f(x)=∑xpλ(x) fk(x)\partial_k A = \frac{1}{Z}\sum_x h(x)\,f_k(x)\,e^{\lambda\cdot f(x)} = \sum_x p_\lambda(x)\,f_k(x). Differentiating again, using ∂jpλ(x)=pλ(x)(fj(x)−∂jA)\partial_j p_\lambda(x) = p_\lambda(x)\big(f_j(x) - \partial_j A\big),

∂j∂kA=∑xpλ(x) fk(x)(fj(x)−Epλ[fj])=E[fjfk]−E[fj] E[fk]=Cov⁡(fj,fk).\partial_j\partial_k A = \sum_x p_\lambda(x)\,f_k(x)\big(f_j(x) - \E_{p_\lambda}[f_j]\big) = \E[f_j f_k] - \E[f_j]\,\E[f_k] = \Cov(f_j, f_k).

A covariance matrix is positive semidefinite: u⊤∇2A u=Var⁡pλ(u⋅f)≥0u\T\hess A\,u = \Var_{p_\lambda}(u\cdot f) \ge 0. Since pλp_\lambda assigns positive mass to every X\mathcal{X}, that variance vanishes only if u⋅fu \cdot f is constant on X\mathcal{X}.

∎

Thus the moment map λ↦∇A(λ)\lambda \mapsto \grad A(\lambda) is the gradient of a convex function. Its image is the interior of the moment polytope (marginal polytope) M=conv⁡{f(x):x∈X}\mathcal{M} = \operatorname{conv}\{f(x) : x \in \mathcal{X}\}, the set of values Eq[f]\E_q[f] some distribution can produce.

Proof

Uniqueness follows from strict convexity. For existence it suffices to show gg is coercive. Take a unit direction uu. As t→∞t \to \infty, A(λ+tu)=tmax⁡xu⋅f(x)+O(1)A(\lambda + tu) = t\max_x u\cdot f(x) + \bigO(1), because the largest exponential term dominates the sum. Therefore g(λ+tu)=t(max⁡xu⋅f(x)−u⋅μ)+O(1)g(\lambda + tu) = t\big(\max_x u\cdot f(x) - u\cdot\mu\big) + \bigO(1). If μ\mu is interior, u⋅μ<max⁡xu⋅f(x)u\cdot\mu < \max_x u\cdot f(x) for every uu (otherwise hyperplane {v:u⋅v=u⋅μ}\{v : u \cdot v = u\cdot\mu\} would support M\mathcal{M} at μ\mu), so gg grows linearly in all directions; by compactness of the unit sphere and continuity, growth is uniform and gg attains its minimum, where ∇g=∇A−μ=0\grad g = \grad A - \mu = 0. If μ\mu is on the boundary, some uu has u⋅μ=max⁡xu⋅f(x)u\cdot\mu = \max_x u\cdot f(x), and along that direction gg strictly decreases: the minimum escapes to infinity.

∎

This is what you saw with μ=6\mu = 6: with u=1u = 1, max⁡kk=6=μ\max_k k = 6 = \mu, and g(λ)=log⁡∑keλ(k−6)g(\lambda) = \log\sum_k e^{\lambda(k - 6)} decreases toward 00 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 pp. The Gibbs theorem identity avoids differentiation: for any λ\lambda and any feasible qq,

H⁡(q)=A(λ)−λ⋅μ−KL⁡(q ∥ pλ)≤A(λ)−λ⋅μ=g(λ).\Ent(q) = A(\lambda) - \lambda\cdot\mu - \KL(q \,\|\, p_\lambda) \le A(\lambda) - \lambda\cdot\mu = g(\lambda).

(This is the theorem proof’s calculation, which did not use optimality of λ\lambda, only Eq[f]=μ\E_q[f] = \mu.) This is weak duality: any λ\lambda gives an upper bound on maximum entropy. The bound is exact at λ∗\lambda^*, because q=pλ∗q = p_{\lambda^*} is then feasible and KL vanishes. The dual problem,

min⁡λ∈RK g(λ)=A(λ)−λ⋅μ,\min_{\lambda\in\R^K}\ g(\lambda) = A(\lambda) - \lambda\cdot\mu,

is convex, unconstrained, and of dimension KK (number of constraints), not ∣X∣\abs{\mathcal{X}}. Its gradient is Epλ[f]−μ\E_{p_\lambda}[f] - \mu, 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: μ=μ^=1n∑i=1nf(xi)\mu = \hat\mu = \frac1n\sum_{i=1}^n f(x_i). Forget maximum entropy and fit the log-linear model pλp_\lambda by maximum likelihood.

Proof

log⁡pλ(xi)=λ⋅f(xi)−A(λ)\log p_\lambda(x_i) = \lambda\cdot f(x_i) - A(\lambda) with h≡1h \equiv 1. Averaging over the sample gives 1n∑ilog⁡pλ(xi)=λ⋅μ^−A(λ)\frac1n\sum_i \log p_\lambda(x_i) = \lambda\cdot\hat\mu - A(\lambda). The two functions of λ\lambda are identical, so have the same minimizer, which sets the gradient to zero: Epλ∗[f]=μ^\E_{p_{\lambda^*}}[f] = \hat\mu. Existence and uniqueness are those of the multiplier theorem, and the minimum value is g(λ∗)=H⁡(p∗)g(\lambda^*) = \Ent(p^*) by the Gibbs theorem.

∎

Interior placement matters. With indicator features fx(y)=1[y=x]f_x(y) = \ind[y = x] for every outcome except one (which are minimal), if one of those outcomes never occurs in the sample, μ^x=0\hat\mu_x = 0, μ^\hat\mu lies on the polytope boundary, the maximum-likelihood estimator does not exist (that outcome’s parameter escapes to −∞-\infty), and maximum entropy assigns it zero probability. This is the same phenomenon as the die with μ=6\mu = 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(λ∗)g(\lambda^*) is the minimum cross-entropy between empirical distribution and model, in nats per observation. For empirical distribution p^\hat p, g(λ)=H⁡(p^,pλ)=H⁡(p^)+KL⁡(p^ ∥ pλ)g(\lambda) = \Ent(\hat p, p_\lambda) = \Ent(\hat p) + \KL(\hat p \,\|\, p_\lambda), and pλ∗p_{\lambda^*} is the projection of p^\hat p onto the exponential family in the min⁡λKL⁡(p^ ∥ pλ)\min_\lambda \KL(\hat p \,\|\, p_\lambda) sense.

The conditional version is most common. If you model p(y∣x)∝exp⁡(wy⊤x)p(y \given \vb{x}) \propto \exp(\vb{w}_y\T\vb{x}) and require that the expected value of each feature xj 1[y=c]x_j\,\ind[y = c] under the model on the data match its empirical count, ∑ixij p(c∣xi)=∑ixij 1[yi=c]\sum_i x_{ij}\,p(c \given \vb{x}_i) = \sum_i x_{ij}\,\ind[y_i = 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 pp (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 pp.

With pp uniform over nn outcomes, KL⁡(q ∥ p)=log⁡n−H⁡(q)\KL(q \,\|\, p) = \log n - \Ent(q): minimizing KL maximizes entropy. Maximum entropy is the I-projection of uniform. The Lagrange calculation, now with −KL⁡(q ∥ p)-\KL(q\,\|\,p) as objective, gives q∗∝p eλ⋅fq^* \propto p\,e^{\lambda\cdot f}: the Gibbs distribution with reference measure h=ph = p. The prior is exponentially tilted toward the constraint, by the minimum necessary.

Proof

For r∈Lr \in \mathcal{L}, split the logarithm through q∗q^*:

KL⁡(r ∥ p)=∑xr(x)log⁡r(x)q∗(x)+∑xr(x)log⁡q∗(x)p(x)=KL⁡(r ∥ q∗)+Er[λ∗⋅f−A(λ∗)].\KL(r \,\|\, p) = \sum_x r(x)\log\frac{r(x)}{q^*(x)} + \sum_x r(x)\log\frac{q^*(x)}{p(x)} = \KL(r \,\|\, q^*) + \E_r\big[\lambda^*\cdot f - A(\lambda^*)\big].

The last term equals λ∗⋅μ−A(λ∗)\lambda^*\cdot\mu - A(\lambda^*), because Er[f]=μ\E_r[f] = \mu. But q∗q^* also lies in L\mathcal{L}, so the same number is Eq∗[log⁡(q∗/p)]=KL⁡(q∗ ∥ p)\E_{q^*}[\log(q^*/p)] = \KL(q^* \,\|\, p). For the general convex inequality: if r∈Er \in \mathcal{E}, qt=(1−t)q∗+tr∈Eq_t = (1-t)q^* + t r \in \mathcal{E} and t↦KL⁡(qt ∥ p)t \mapsto \KL(q_t \,\|\, p) has its minimum at t=0t = 0, so its right derivative at 00, equal to ∑x(r(x)−q∗(x))log⁡(q∗(x)/p(x))\sum_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\KL(r\,\|\,p) - \KL(r\,\|\,q^*) - \KL(q^*\,\|\,p) \ge 0 (when r≪q∗r \ll 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. pp is a point outside line L\mathcal{L}, q∗q^* is the perpendicular foot, and rr 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 {p eλ⋅f/Z}\{p\,e^{\lambda\cdot f}/Z\} through pp intersects L\mathcal{L} at q∗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}\{1, 2, 3\}: each vertex is a certain outcome
  • segment LL: Eq[f]=μ\E_q[f] = \mu
  • family q∝p eλfq \propto p\,e^{\lambda f}
  • level KL⁡(q ∥ p)=KL⁡(q∗ ∥ p)\KL(q\,\|\,p) = \KL(q^*\,\|\,p)
KL⁡(r ∥ p)\KL(r\,\|\,p)
KL⁡(r ∥ q∗)+KL⁡(q∗ ∥ p)\KL(r\,\|\,q^*) + \KL(q^*\,\|\,p)
1.35
q∗q^*(0.170, 0.310, 0.520)
Multiplier λ\lambda1.209
KL⁡(r ∥ p)\KL(r\,\|\,p)0.5189 nats
KL⁡(r ∥ q∗)+KL⁡(q∗ ∥ p)\KL(r\,\|\,q^*) + \KL(q^*\,\|\,p)0.5189 nats
Difference0.000000
Wherever you move rr, the bars are equal: KL⁡(r ∥ p)=KL⁡(r ∥ q∗)+KL⁡(q∗ ∥ p)\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]=μ\E_q[f] = \mu is the aquamarine segment LL. Drag prior pp (blue): its I-projection q∗q^* (magenta) is the intersection of LL with exponential family q∝p eλfq \propto p\,e^{\lambda f} through pp (dashed), and the level curve of KL⁡(⋅ ∥ p)\KL(\cdot\,\|\,p) through q∗q^* is tangent to LL. Drag rr (orange) along the segment: the two bars below always agree. Enable comparison with reverse projection arg min⁡qKL⁡(p ∥ q)\argmin_q \KL(p\,\|\,q): point qMq_M 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 arg min⁡q∈LKL⁡(p ∥ q)\argmin_{q\in\mathcal{L}}\KL(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 nn iid samples from pp and condition on the empirical mean of ff being μ\mu, the distribution of any sample converges to I-projection q∗q^* as n→∞n \to \infty (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 ff and seek the distribution that best balances “being where ff is large” with “not moving away from pp.”

This is the Gibbs variational principle. The second hypothesis ensures q∗q^* itself is admissible: Eq∗∣f∣=Ep[∣f∣ ef]/Ep[ef]\E_{q^*}\abs{f} = \E_p[\abs{f}\,e^f]/\E_p[e^f]. Without it the equality holds as a supremum, but may not be attained. The proof again splits a logarithm: log⁡qq∗=log⁡qp−f+log⁡Ep[ef]\log\frac{q}{q^*} = \log\frac{q}{p} - f + \log\E_p[e^f], then takes expectations under qq. You will do it in the second guided exercise. Its special case with pp uniform on finite X\mathcal{X} (adding log⁡∣X∣\log\abs{\mathcal{X}} to both sides) is the free-energy form:

log⁡∑xef(x)=max⁡q∈Δ(X) {Eq[f]+H⁡(q)}.\log\sum_{x} e^{f(x)} = \max_{q\in\Delta(\mathcal{X})}\ \Big\{\E_q[f] + \Ent(q)\Big\}.

With f=−E/Tf = -E/T and multiplying by −T-T we obtain −Tlog⁡Z=min⁡q{Eq[E]−T H⁡(q)}-T\log Z = \min_q \{\E_q[E] - T\,\Ent(q)\}: Helmholtz free energy F=U−TSF = 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]+T H⁡(q)=Tlog⁡∑xesx/T\E_q[s] + T\,\Ent(q) = T\log\sum_x e^{s_x/T}, which intersects axis Eq[s]=0\E_q[s] = 0 at height log⁡∑xesx/T\log\sum_x e^{s_x/T}, the corresponding readout.

The relative form has a useful dual reading. Rearranging, every bounded ff satisfies KL⁡(q ∥ p)≥Eq[f]−log⁡Ep[ef]\KL(q \,\|\, p) \ge \E_q[f] - \log\E_p[e^f], with equality at f=log⁡(q/p)f = \log(q/p) plus a constant (if that function is unbounded, the supremum is approached by truncating it). That is,

KL⁡(q ∥ p)=sup⁡f {Eq[f]−log⁡Ep[ef]},\KL(q \,\|\, p) = \sup_f\ \Big\{\E_q[f] - \log\E_p\big[e^f\big]\Big\},

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)q \mapsto \KL(q \,\|\, p) and f↦log⁡Ep[ef]f \mapsto \log\E_p[e^f], 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)\max_\pi \E_{y\sim\pi}[r(y)] - \beta\,\KL(\pi \,\|\, \pi_{\text{ref}}) for each prompt. With f=r/βf = r/\beta and p=πrefp = \pi_{\text{ref}}, the optimal policy is π∗(y)∝πref(y) er(y)/β\pi^*(y) \propto \pi_{\text{ref}}(y)\,e^{r(y)/\beta} and optimal value βlog⁡Eπref[er/β]\beta\log\E_{\pi_{\text{ref}}}[e^{r/\beta}]. DPO starts from this closed form (RLHF objective).
  • Variational inference. With p(z∣x)∝p(x,z)p(z \given x) \propto p(x, z), the principle says log⁡p(x)=max⁡q{Eq[log⁡p(x,z)]+H⁡(q)}\log p(x) = \max_q \{\E_q[\log p(x, z)] + \Ent(q)\}: the ELBO bound is the variational-principle objective, and its gap is KL⁡(q ∥ p(⋅∣x))\KL(q \,\|\, p(\cdot \given 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]\grad A = \E_{p_\lambda}[f], which requires model samples when X\mathcal{X} is enormous. That is why the partition function bottlenecks these models.
  • Maximum-entropy RL. Adding α H⁡(π(⋅∣s))\alpha\,\Ent(\pi(\cdot \given s)) to reward turns the maximum in Bellman’s equation into a soft maximum: V(s)=αlog⁡∑aeQ(s,a)/αV(s) = \alpha\log\sum_a e^{Q(s,a)/\alpha} and π(a∣s)∝eQ(s,a)/α\pi(a \given s) \propto e^{Q(s,a)/\alpha}. This applies the variational principle state by state (maximum-entropy RL).
  • Temperature as multiplier. Sampling a language model at temperature TT chooses the score–entropy frontier point with slope −1/T-1/T. Fixing a target entropy and adjusting TT, as in SAC, solves the constrained problem through its dual.

Implementation from scratch

Follow the dual plan: minimize g(λ)=A(λ)−λ⋅μg(\lambda) = A(\lambda) - \lambda\cdot\mu with damped Newton. The gradient is moment error and the Hessian is feature covariance; both use pλp_\lambda itself, and AA 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 11 to 6.6×10−26.6\times 10^{-2}, 10−310^{-3}, 3×10−73\times 10^{-7}, and 2×10−142\times 10^{-14}: correct digits double at each step, Newton’s quadratic convergence. Starting from λ=0\lambda = 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, λ∗\lambda^* grows as −log⁡-\log of the distance to the boundary (with μ=6−ε\mu = 6 - \eps, λ∗≈log⁡(1/ε)\lambda^* \approx \log(1/\eps)) and Newton still converges, although it initially needs more damped steps. The 10−1210^{-12} slack in line search matters: without it, with μ=5.99\mu = 5.99, backtracking rejects good steps because improvement in the dual is below rounding, and the method stalls at gradient 6×10−106\times 10^{-10} until iterations are exhausted. At the boundary, each iteration adds approximately 11 to λ\lambda forever: for large λ\lambda, E[X]≈6−e−λ\E[X] \approx 6 - e^{-\lambda} and Var⁡(X)≈e−λ\Var(X) \approx e^{-\lambda}, so step −(E[X]−6)/Var⁡(X)-(\E[X] - 6)/\Var(X) is almost exactly 11. No step-size criterion detects this; first check that μ\mu is inside M\mathcal{M} (in one dimension, min⁡f<μ<max⁡f\min f < \mu < \max f; 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}x_1, x_2 \in \{0, 1, 2\} with features x1x_1, x2x_2, and interaction x1x2x_1x_2. 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 λ\lambda; the model reproduces the three empirical moments, and negative log-likelihood matches the dual at every λ\lambda, not only the optimum: they are literally the same function. Optimal value 1.8631.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 log⁡p\log p 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\mathcal{L}, and none of 5000 random distributions exceeds value log⁡Ep[ef]\log\E_p[e^f] 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.

ToolPurpose
scipy.special.logsumexp, softmaxstable log-partition and Gibbs distribution
scipy.optimize.minimize(..., jac, hess, method="trust-exact")maximum-entropy dual with few constraints
scipy.optimize.linprogcheck that μ\mu is inside the moment polytope
sklearn.linear_model.LogisticRegressionconditional maximum entropy (softmax regression)
torch.logsumexp, torch.softmaxthe same within a differentiable model
[ ]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 xj 1[y=c]x_j\,\ind[y = c] (including bias) to optimizer tolerance: it is the conditional maximum-entropy model with those constraints. With L2L_2 regularization, the optimality condition becomes “empirical count minus model count equals wc/C\vb{w}_c/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.53.5?
NumericKL without calculating the distribution
The maximum-entropy distribution of a die with mean 4.54.5 has H⁡(p∗)=2.3279\Ent(p^*) = 2.3279 bits. Without calculating p∗p^*, what is KL⁡(q ∥ p∗)\KL(q\,\|\,p^*) in bits for q=(0,0,0.25,0.25,0.25,0.25)q = (0, 0, 0.25, 0.25, 0.25, 0.25)?
NumericA mean lifetime
A waiting time X≥0X \ge 0 has mean 22 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,log⁡3,log⁡4)s = (0, \log 3, \log 4), what is the maximum of Eq[s]+H⁡(q)\E_q[s] + \Ent(q) over all distributions qq (entropy in nats)?
NumericThe optimal RLHF policy
A reference model assigns equal probability to 4 responses. Rewards are r=(1,0,0,0)r = (1, 0, 0, 0) and the KL coefficient is β=0.5\beta = 0.5. What probability does the policy maximizing Eπ[r]−β KL⁡(π ∥ πref)\E_\pi[r] - \beta\,\KL(\pi\,\|\,\pi_{\text{ref}}) assign to the first response?
QuizContinuous maximum entropy
Which distribution maximizes differential entropy on [0,∞)[0, \infty) with fixed mean, and which on R\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.34750.3475. You roll it 10 00010\,000 times: the mean remains 4.54.5 but 6 occurs with frequency 0.250.25. What conclusion is correct?
QuizWhat is true and what is not
Let p∗=pλ∗p^* = p_{\lambda^*} be the maximum-entropy distribution with E[f]=μ\E[f] = \mu, μ\mu interior to the moment polytope. Which statements are true?

More than one answer may be correct.

ProofGibbs form via Lagrange
Prove: The solution of max⁡pH⁡(p)\max_p \Ent(p) subject to ∑xp(x)fk(x)=μk\sum_x p(x) f_k(x) = \mu_k (k=1,…,Kk = 1, \dots, K) and ∑xp(x)=1\sum_x p(x) = 1, on finite set X\mathcal{X}, has form p(x)=eλ⋅f(x)/Z(λ)p(x) = e^{\lambda\cdot f(x)}/Z(\lambda).
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)/Zp_f(x) = e^{f(x)}/Z and Z=∑xef(x)Z = \sum_x e^{f(x)}, every distribution qq satisfies Eq[f]+H⁡(q)=log⁡Z−KL⁡(q ∥ pf)\E_q[f] + \Ent(q) = \log Z - \KL(q\,\|\,p_f). Consequently log⁡Z=max⁡q{Eq[f]+H⁡(q)}\log Z = \max_q \{\E_q[f] + \Ent(q)\}, with unique maximum at q=pfq = p_f.
0
Fix any distribution qq on X\mathcal{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\E_p[f_k] = \mu_k. F is a (K, n) matrix with fk(x)f_k(x) in row kk and mu a vector of length K. Return (lam, p): multiplier λ∈RK\lambda \in \R^K and distribution p(x)∝eλ⋅f(x)p(x) \propto e^{\lambda\cdot f(x)}, which must satisfy moments with error below 10−710^{-7}. Minimize dual log⁡Z(λ)−λ⋅μ\log Z(\lambda) - \lambda\cdot\mu with Newton (gradient: moments minus μ\mu; Hessian: covariance), compute log⁡Z\log Z 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λ⋅fp \propto e^{\lambda\cdot f}, and any other loses exactly KL⁡(q ∥ p∗)\KL(q\,\|\,p^*) of entropy; the same calculation gives maximum-likelihood duality, I-projection Pythagoras, and variational principle log⁡Ep[ef]=max⁡qEq[f]−KL⁡(q ∥ p)\log\E_p[e^f] = \max_q \E_q[f] - \KL(q\,\|\,p).
  • Principle. Given only moments E[f]=μ\E[f] = \mu, choose the maximum-entropy distribution: it assumes the least and concentrates exponentially more compatible configurations in nn.
  • Gibbs form. The solution is pλ∝h eλ⋅fp_\lambda \propto h\,e^{\lambda\cdot f}, and for every compatible qq, H⁡(q)=H⁡(p∗)−KL⁡(q ∥ p∗)\Ent(q) = \Ent(p^*) - \KL(q\,\|\,p^*). Uniform, geometric, exponential, Laplace, Gaussian, and temperature softmax are special cases; T=1/λT = 1/\lambda is the price of entropy and the score–entropy frontier slope is −1/T-1/T.
  • Log-partition. A=log⁡ZA = \log Z is convex, ∇A=E[f]\grad A = \E[f] and ∇2A=Cov⁡[f]\hess A = \Cov[f]. The multiplier exists if and only if μ\mu is inside the moment polytope; at the boundary the dual has no minimum. Always compute with log-sum-exp.
  • Duality. Minimize dual A(λ)−λ⋅μA(\lambda) - \lambda\cdot\mu 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. arg min⁡q∈LKL⁡(q ∥ p)∝p eλ⋅f\argmin_{q\in\mathcal{L}}\KL(q\,\|\,p) \propto p\,e^{\lambda\cdot f} and satisfies Pythagoras: KL⁡(r ∥ p)=KL⁡(r ∥ q∗)+KL⁡(q∗ ∥ p)\KL(r\,\|\,p) = \KL(r\,\|\,q^*) + \KL(q^*\,\|\,p) for every rr in the linear family. Not with reversed arguments.
  • Variational principle. log⁡Ep[ef]=max⁡q{Eq[f]−KL⁡(q ∥ p)}\log\E_p[e^f] = \max_q\{\E_q[f] - \KL(q\,\|\,p)\} with maximizer q∗∝p efq^* \propto p\,e^f: free energy, softmax as a soft maximum, optimal RLHF policy, ELBO, and Donsker–Varadhan are the same identity.