Laplace's method and asymptotic approximations
Approximate integrals depending on a large parameter, ∫e^{n f(x)}dx, by replacing the integrand with a Gaussian centered at the maximum. This yields Stirling's formula, the temperature behavior of logsumexp and softmax, and the idea that becomes the Laplace approximation of a posterior in m14. Asymptotic series are introduced: they may diverge while remaining excellent approximations.
After this lesson you can
- Derive Laplace's method in one and several variables, including its leading term and error order.
- Prove Stirling's formula from the Gamma function.
- Bound logsumexp between the maximum and the maximum plus τ·log n, and relate its gradient to softmax.
- Distinguish convergent and asymptotic series and select optimal truncation of an asymptotic series.
- Implement Laplace approximations of normalization constants and measure their error against quadrature.
Before you start
Motivation: integrals dominated by one point
A family of integrals and sums appears everywhere in machine learning and almost never has a closed form: those depending on a large parameter multiplying an exponent.
- Normalization constants. With independent observations, the Bayesian posterior of a parameter is , where is the average log likelihood plus the log prior divided among the observations. The missing constant, , is the model evidence: it compares models, selects hyperparameters and gives the BIC criterion. Integrating in with in the thousands is impossible by quadrature.
- Giant factorials. . Counting configurations, estimating binomial coefficients or calculating count entropies requires knowing how grows when is of order , long before the number can be written down.
- Softmax with temperature. Transformer attention, LLM sampling and soft Bellman operators calculate and its gradient. This is a sum, not an integral, but with has exactly the same form , and the question is the same: what happens as grows.
All three feature with large , and an exponential with a large exponent amplifies differences dramatically: if , with the integrand at is times larger than at . All mass concentrates around the maximum of , and near the maximum any smooth function is a parabola. The exponential of a parabola is Gaussian, and Gaussians can be integrated. This is the whole idea of Laplace’s method. This lesson turns it into a theorem with precise assumptions and error order, extends it to several variables, derives Stirling’s formula and logsumexp behavior, studies failure cases and ends with a surprising phenomenon: successive corrections form divergent series that are nonetheless extraordinary approximations.
Intuition: the peak becomes Gaussian
Take on . Its maximum is at , where . Factoring out the value at the maximum,
There are two approximations in that : replacing by its osculating parabola and extending the interval to the entire line. Both improve with , because the normalized integrand has width of order : as grows, only an increasingly small neighborhood of the maximum matters, where the parabola becomes increasingly accurate, and what lies outside the interval is a negligible Gaussian tail.
The right-hand graph shows something the informal argument does not: relative error not only tends to zero, it does so exactly like , with a constant depending on the third and fourth derivatives of at the maximum. And the two-peak case shows the method’s limit: “asymptotic” means “as ,” and for a particular a slightly lower but much wider maximum can contribute most of the integral.
Laplace’s method in one variable
This approximation is Laplace’s method: replace the integrand by the Gaussian with the same maximum and curvature there. The three assumptions play concrete roles. The first gives the parabola, through the second derivative test. The second prevents another region of the domain from competing with the maximum: without it, a sequence of local maxima approaching the height of at infinity might contribute as much mass as the peak. The third guarantees finite tails for some , and therefore for all larger values.
Proof
Without loss of generality, and (translate the variable and factor out ). Let and fix . By continuity of there is with if . By the Lagrange remainder, for there exists between and with , so
Central part. Integrating the upper bound over the entire line and using the Gaussian integral ,
where is the probability that a centered normal of variance lies outside , which tends to 0.
Tails. By assumption 2, . For , in region we have , so
which is exponentially small and, multiplied by , still tends to 0.
Conclusion. Multiplying everything by and taking limits,
Since is arbitrary, the ratio tends to 1.
∎The proof also explains the scale order. Relevant width is , so the region that matters shrinks; what happens at fixed distance from the maximum is penalized by , much smaller than any power of . Thus the method needs only local information at the maximum and a global condition ruling out competitors.
The error order: the first correction
To see why error is , and with what constant, change to the natural variable , in which the Gaussian has fixed width. Write , and .
The calculation is formal (it interchanges series and integral), but is made rigorous by the same scheme as the proof: cut off at with slowly, bound the Taylor remainder and the tails are exponentially small. With of class it gives the theorem’s error , and with , the expansion through . Two checks using the figure:
- : , , , hence . The exact integral is , with the modified Bessel function, and indeed .
- : , , , hence . That is the first correction in Stirling’s formula, as you will soon see.
The error measured by the figure is that of the leading term, : that is why error stabilizes at and .
With a prefactor
Almost always the integral has a factor that does not grow with , . If is continuous at with and , the same proof gives
The slow factor is evaluated at the maximum and taken outside. This matters for a posterior’s prior: the prior does not scale with and enters only through .
The multivariable case
In the parabola becomes a quadratic form defined by the Hessian, and the one-dimensional Gaussian becomes a multivariate Gaussian.
Proof
With , and , which is positive definite. By the multivariable Taylor theorem with Lagrange remainder, with on the segment from to . Given less than the smallest eigenvalue of , Hessian continuity gives a ball on which , and therefore
For any positive-definite , the change of variables , with Jacobian , converts the Gaussian integral into a product of one-dimensional integrals:
Tails outside the ball are handled exactly as in one variable. Since , by the relationship between determinant and eigenvalues, both bounds converge to as .
∎The geometric reading is direct: is proportional to the volume of the uncertainty ellipsoid. A Hessian with eigenvalues defines a Gaussian with standard deviations along eigendirections, and its mass is the product of the widths times . A very flat direction (small eigenvalue) contributes much volume; a highly curved one, little.
Model evidence and BIC
Apply the theorem to the evidence. With the posterior mode (MAP estimator) and ,
This is the Laplace evidence, and the Gaussian producing it is the Laplace approximation of the posterior. With independent data, , where is Fisher information per observation, so and
Removing bounded terms yields the BIC criterion: each parameter costs nats of evidence. You will implement it below with two-parameter logistic regression and verify that approximation error in falls like .
Stirling’s formula
The method’s most famous example is the factorial. With the Gamma function, , and the integrand has its maximum at , which moves with . The change fixes it at :
Now the exponent is times a fixed function, , with a unique maximum at with and . Laplace’s method gives , and multiplying by yields Stirling’s formula:
You will prove the first part by checking the method’s assumptions in the guided exercise at the end. The second, with bounded remainder, is a classical result obtained using Euler–Maclaurin summation or Binet’s formula for (see de Bruijn’s book in the sources). The first terms are
Notice is the calculated for : Laplace’s first correction reproduces Stirling’s first term, as it must, because .
The accuracy is astonishing even for small . For , the leading term gives , relative error . With correction we obtain : error falls to . In practice the useful form is logarithmic: for is nats, a number no computer writes as a factorial, but which gives to 13 correct digits.
When the leading term fails
The theorem’s assumptions are not decorative. Breaking each one changes the answer, and in each case there is a known correction. The opening figure has all three cases.
Maximum at the boundary. If is an interval endpoint, only half a Gaussian is integrated. There are two subcases:
- If and , as in on , the answer is half: . Without factor , relative error tends to instead of zero.
- If (the function simply decreases from the boundary), the linear term dominates: and . Now the scale is , not .
Multiple maxima. With several global maxima, each contributes its Gaussian and they are added. With a global maximum and another local one of height with small , the theorem still holds, but the ratio of the two contributions is
which is small only when exceeds the logarithm of the curvature ratio. In the figure, and curvatures are and : the broad peak wins until . For a multimodal posterior the consequence is serious: the Laplace approximation at the mode can miss most of the mass, and in high dimension the volume ratio is a product of factors.
Degenerate Hessian. If , the formula gives : the Gaussian would have infinite variance. The mass is then controlled by the first nonzero derivative. If near the maximum, with , the change and the definition of give
which decreases like , more slowly than . For and this is the figure’s quartic correction. Its relative error falls only like , not . In the figure, , and on the natural scale the sixth-degree term is : it is even, so does not vanish on integration, and its average against gives error , the reference line in the degenerate case.
Boundary note: singular models
In a regular model, the optimal parameter set is a point and the Hessian is nondegenerate. In neural networks, Gaussian mixtures or factor models, the set of parameters giving the same distribution is a variety with singularities (for example, if an output weight is zero, that neuron’s input weights are arbitrary), and the Hessian there is singular. The minimal example is on : the maximum is the entire cross , with no point at which to center a Gaussian.
Sumio Watanabe developed the theory replacing Laplace in this case using algebraic geometry’s resolution of singularities. Its central result says free energy (minus log evidence) behaves like
where , the real log canonical threshold (or learning coefficient), and its multiplicity are geometric invariants of the singular set. In a regular model and , recovering BIC. In a singular one , often much smaller: the model is “simpler” than its parameter count suggests. For , and , so replaces the of a regular two-parameter model.
import numpy as np
from scipy import integrate, special
def Z_singular(n):
# ∫∫_{[-1,1]^2} exp(-n x^2 y^2): la integral en y es sqrt(pi/n)/|x| · erf(sqrt(n)|x|)
interior = lambda x: np.sqrt(np.pi / n) * special.erf(np.sqrt(n) * x) / x if x > 0 else 2.0
return 2 * integrate.quad(interior, 0, 1, points=[1 / np.sqrt(n)], limit=200)[0]
def Z_regular(n):
# ∫∫_{[-1,1]^2} exp(-n (x^2 + y^2)) = (sqrt(pi/n) erf(sqrt(n)))^2
return (np.sqrt(np.pi / n) * special.erf(np.sqrt(n))) ** 2
print(" n Z regular n·Z Z singular sqrt(n)·Z/log n")
for n in [1e2, 1e3, 1e4, 1e5, 1e6]:
zr, zs = Z_regular(n), Z_singular(n)
print(f"{n:9.0e} {zr:.3e} {n*zr:.4f} {zs:.3e} {np.sqrt(n)*zs/np.log(n):.4f}")The regular case satisfies to every printed digit, as Laplace predicts with (the difference is a Gaussian tail of order ). The singular case decays much more slowly: factor accompanying is exactly Watanabe’s term with , seen in . Column tends to , but very slowly, because the next correction is relative order (the free-energy term ). No adjustment to the Hessian fixes this; another theory is needed.
Logsumexp as a smooth maximum
The discrete version of Laplace’s method is the most used in machine learning. Given and , define
Here is the number of components, so the large parameter has a different name: with , the sum is , a Laplace “integral” over a finite set with , and the expectation is the same: the largest term dominates. Since there is no curvature to measure, what remains of the Gaussian is the number of indices tied at the maximum.
These five properties are what we call logsumexp as a smooth maximum. You will prove the bounds in point 1 in a guided exercise; the rest follow in a few lines.
Proof
(2) Factoring , . Each term in the sum is at most , so , using .
(3) Differentiating, . Differentiating again, . For every , , which is the variance of with and therefore nonnegative.
(4) : the factor leaves the logarithm as and cancels in the softmax quotient.
(5) Let , so . For any in the simplex,
Since KL divergence is nonnegative and vanishes only if , the maximum is and is attained only at softmax.
∎The figure shows both regimes. As , softmax tends to the uniform distribution over maximum indices (one-hot if unique) and the smooth maximum to the maximum. As , softmax tends to uniform and , the mean of logits: expanding, . The identity in point 5 appears in the readouts: equals the smooth maximum for any and .
This structure appears throughout the curriculum:
- Attention. The factor in attention softmax is a temperature: without it, dot products grow like and softmax saturates toward the one-hot regime, where its Jacobian is nearly zero and the gradient vanishes.
- Sampling. An LLM’s temperature sampling rescales logits before softmax: concentrates on the most likely tokens, flattens.
- Soft Bellman. In maximum-entropy RL, a state’s value is instead of , and the optimal policy is softmax: it is the variational form in point 5 applied at each state (soft Bellman equations).
Asymptotic series
Stirling’s formula with corrections has a puzzling property: the series diverges for every . Bernoulli numbers grow like , so term behaves like apart from slow factors, and the factorial eventually beats any power. Yet, as seen with , the first terms are extraordinarily accurate. To understand this, separate two questions that go together in Taylor series.
The definition says nothing about what happens when more terms are summed with fixed ; it only requires each truncation to be better than the preceding one in the limit. Convergence and asymptoticity look in perpendicular directions:
| Fix | Let tend | Question | |
|---|---|---|---|
| Convergence | does the partial sum approach ? | ||
| Asymptoticity | is error smaller than the last term included? |
Two immediate consequences. If it exists, the expansion is unique for a given sequence, because each coefficient is recovered as . But the function is not determined by its expansion: for every as , so and have the same expansion in powers of . Exponentially small terms are invisible to a power series, and this is exactly what limits attainable accuracy.
Euler’s example
Proof
The finite geometric sum gives . Integrating against and using , the remainder is , and since , . For fixed this is , the definition of asymptotic series. Divergence follows from the ratio test: .
∎The error is smaller than the first omitted term, . Those terms decrease while and increase afterward, so it is best to truncate just before the smallest term, at . The resulting error is of order the smallest term, which by Stirling is : exponentially small in , the same scale as the earlier ambiguity . This is optimal truncation, and the associated error cannot be improved with this series.
import mpmath
mpmath.mp.dps = 40
x = mpmath.mpf("0.1")
E = mpmath.quad(lambda t: mpmath.e**(-t) / (1 + x * t), [0, mpmath.inf])
print("E(0.1) =", mpmath.nstr(E, 15))
suma, errores = mpmath.mpf(0), []
for K in range(0, 26): # K = número de términos sumados
errores.append(abs(E - suma))
suma += (-1)**K * mpmath.factorial(K) * x**K
for K in [0, 2, 5, 8, 10, 12, 15, 20, 25]:
cota = mpmath.factorial(K) * x**K
print(f"K = {K:2d}: error = {mpmath.nstr(errores[K], 3):>9s} cota K!·x^K = {mpmath.nstr(cota, 3):>9s}")
K_opt = min(range(26), key=lambda K: errores[K])
print("truncamiento óptimo: K* =", K_opt, " error mínimo =", mpmath.nstr(errores[K_opt], 3),
" sqrt(2π/x)·e^(-1/x) =", mpmath.nstr(mpmath.sqrt(2 * mpmath.pi / x) * mpmath.e**(-1 / x), 3))With , the optimum is at terms, with error . With 25 terms error is already , almost half of itself, and each new term multiplies it by more than . The bound always holds, and actual error is a fraction of it, roughly half near the optimum, typical of alternating series of this kind.
Stirling, again
The same happens with Stirling’s series, with playing the role of . Term is minimal near , optimal error is of order , and, as Stirling’s theorem says, the remainder has the sign of the first omitted term and is smaller than it: the series is called enveloping, because partial sums alternate above and below .
The practical lesson is the same as for asymptotic expansions in combinatorics: in an asymptotic series, “more terms” does not mean “more accuracy.” For large , two or three terms give more digits than needed; for small , there is a limit no number of terms surpasses, and the correct use is to truncate at the smallest term. Beyond optimal truncation there are techniques (Borel resummation, hyperasymptotics) recovering the exponentially small part, but these are specialist asymptotic analysis.
Implementation from scratch
First, Laplace’s method in one variable with Newton for the mode. The example is evidence for a coin with uniform prior: with heads in tosses, , which has closed form and allows exact error measurement. We also compare approximation in the original variable with approximation in logit variable , in which the integrand becomes due to Jacobian .
import numpy as np
from math import lgamma, log, pi
def newton_1d(d1, d2, x0, tol=1e-12, max_iter=50):
"""Máximo de log f por Newton: x <- x - f'(x)/f''(x)."""
x = x0
for _ in range(max_iter):
paso = d1(x) / d2(x)
x -= paso
if abs(paso) < tol:
break
return x
def laplace_logZ_1d(logf, d1, d2, x0):
"""log ∫ f ≈ log f(x*) + ½ log(2π / |(log f)''(x*)|)."""
xs = newton_1d(d1, d2, x0)
A = -d2(xs)
assert A > 0, "el máximo debe ser no degenerado"
return logf(xs) + 0.5 * log(2 * pi / A)
sig = lambda u: 1 / (1 + np.exp(-u))
print(" n k log Z exacto error en θ n·error error en logit n·error")
for n in [10, 20, 50, 100, 200, 500, 1000]:
k = round(0.3 * n)
exacto = lgamma(k + 1) + lgamma(n - k + 1) - lgamma(n + 2) # log B(k+1, n-k+1)
en_theta = laplace_logZ_1d(lambda t: k * np.log(t) + (n - k) * np.log1p(-t),
lambda t: k / t - (n - k) / (1 - t),
lambda t: -k / t**2 - (n - k) / (1 - t)**2, 0.5)
en_logit = laplace_logZ_1d(lambda u: (k + 1) * np.log(sig(u)) + (n - k + 1) * np.log(sig(-u)),
lambda u: (k + 1) * sig(-u) - (n - k + 1) * sig(u),
lambda u: -(n + 2) * sig(u) * sig(-u), 0.0)
e1, e2 = np.expm1(en_theta - exacto), np.expm1(en_logit - exacto)
print(f"{n:5d} {k:4d} {exacto:12.4f} {e1:+.2e} {n*e1:+.3f} {e2:+.2e} {n*e2:+.3f}")The two error columns stabilize: relative error is , as the theorem says. But constants differ, in and in the logit variable. The Laplace approximation is not invariant under reparameterization: the Jacobian changes the integrand, and with it the mode and curvature. In the integrand is asymmetric and close to a boundary; in it is more symmetric and Gaussian-like, and error is reduced by more than half. Choosing the parameterization in which the posterior is more Gaussian is a modeling decision, not a detail.
Now the two-variable case: evidence for Bayesian logistic regression with slope and bias, , prior and unnormalized log posterior
Its gradient is and Hessian , with : always negative definite, thanks to the prior. The reference is quadrature on a grid of points in whitened coordinates , with , where the integrand is nearly standard Gaussian and the trapezoid rule converges very quickly.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
w_real = np.array([1.5, -0.5]) # pendiente y sesgo
X_todo = np.column_stack([rng.normal(size=640), np.ones(640)])
y_todo = (rng.random(640) < sig(X_todo @ w_real)).astype(float)
s2 = 4.0 # varianza del prior
def log_post(W, X, y):
"""Log-posterior no normalizada en cada fila de W (forma (m, 2))."""
W = np.atleast_2d(W)
Z = X @ W.T
return y @ Z - np.logaddexp(0, Z).sum(axis=0) - (W**2).sum(axis=1) / (2 * s2) - np.log(2 * np.pi * s2)
def grad_hess(w, X, y):
p = sig(X @ w)
g = X.T @ (y - p) - w / s2
H = -(X.T * (p * (1 - p))) @ X - np.eye(2) / s2
return g, H
def moda_newton(X, y, tol=1e-10):
w = np.zeros(2)
for it in range(50):
g, H = grad_hess(w, X, y)
paso = np.linalg.solve(H, g)
w = w - paso
if np.linalg.norm(paso) < tol:
break
return w, grad_hess(w, X, y)[1], it + 1
def laplace_logZ(X, y):
w, H, its = moda_newton(X, y)
signo, logdet = np.linalg.slogdet(-H)
assert signo > 0, "el hessiano debe ser definido negativo"
d = len(w)
return log_post(w, X, y)[0] + 0.5 * d * np.log(2 * np.pi) - 0.5 * logdet, w, H, its
def cuadratura_logZ(X, y, w, H, m=61, R=7.0):
L = np.linalg.cholesky(np.linalg.inv(-H)) # w = w* + L u
u = np.linspace(-R, R, m)
U = np.stack(np.meshgrid(u, u), -1).reshape(-1, 2)
lp = log_post(w + U @ L.T, X, y)
c = lp.max()
peso = np.ones(m); peso[[0, -1]] = 0.5 # regla del trapecio
P = np.outer(peso, peso).ravel()
h = u[1] - u[0]
return c + np.log(np.sum(P * np.exp(lp - c)) * h * h) + np.log(np.linalg.det(L))
ns, errores = [10, 20, 40, 80, 160, 320, 640], []
print(" n iter. Newton log Z (cuadratura) log Z (Laplace) error n·error")
for n in ns:
X, y = X_todo[:n], y_todo[:n]
lz, w, H, its = laplace_logZ(X, y)
q = cuadratura_logZ(X, y, w, H)
errores.append(lz - q)
print(f"{n:5d} {its} {q:13.6f} {lz:13.6f} {lz - q:+.2e} {n * (lz - q):+.3f}")
w, H, _ = moda_newton(X_todo[:10], y_todo[:10])
fina = cuadratura_logZ(X_todo[:10], y_todo[:10], w, H, m=101, R=9.0)
print("comprobación de la cuadratura con n = 10 (malla 101x101):",
f"{abs(fina - cuadratura_logZ(X_todo[:10], y_todo[:10], w, H)):.1e}")
plt.loglog(ns, np.abs(errores), "o-", label="|log Z Laplace − log Z cuadratura|")
plt.loglog(ns, 1.6 / np.array(ns), "--", color="gray", label="1.6 / n")
plt.xlabel("número de datos n"); plt.ylabel("error en log Z"); plt.legend(); plt.show()Newton converges in 5 or 6 iterations in every case (the log posterior is concave), and error in falls like , with error stabilizing around from onward (the sample is the same enlarged, so the constant still oscillates somewhat with the data). Quadrature, with error at most , is a reliable reference. In two dimensions that grid costs likelihood evaluations; in , the same resolution would require . Laplace costs one Newton fit plus a determinant, in any dimension: this is why it is the default approximation when is large and the posterior unimodal.
Finally, stable logsumexp and softmax. Naive and stable versions are compared with normal, large and very negative logits and with (a masked token).
import numpy as np
def logsumexp_ingenuo(z):
return np.log(np.sum(np.exp(z)))
def logsumexp_estable(z, tau=1.0):
z = np.asarray(z, dtype=float) / tau
M = np.max(z)
if np.isneginf(M): # todos son -inf: la suma vacía
return -np.inf
return tau * (M + np.log(np.sum(np.exp(z - M))))
def softmax_estable(z, tau=1.0):
z = np.asarray(z, dtype=float) / tau
e = np.exp(z - np.max(z))
return e / e.sum()
casos = {"normales": [2.0, 1.0, 0.5], "grandes": [1000.0, 999.0, 0.0],
"negativos": [-1000.0, -1001.0, -2000.0], "con -inf": [3.0, -np.inf, 1.0]}
with np.errstate(over="ignore", divide="ignore", invalid="ignore"):
for nombre, z in casos.items():
print(f"{nombre:10s} ingenuo = {logsumexp_ingenuo(np.array(z)):>10.4f} "
f"estable = {logsumexp_estable(z):>10.4f} softmax = {np.round(softmax_estable(z), 4)}")
z = np.array([2.0, 1.2, 0.3, -0.8, 1.7])
print()
for tau in [10.0, 1.0, 0.1, 0.01]:
S = logsumexp_estable(z, tau)
print(f"tau = {tau:5}: max = {z.max():.4f} <= {S:.6f} <= {z.max() + tau * np.log(len(z)):.4f}")
h = 1e-6
grad = np.array([(logsumexp_estable(z + h * e) - logsumexp_estable(z - h * e)) / (2 * h) for e in np.eye(len(z))])
print("\nmáx |gradiente numérico − softmax| =", np.abs(grad - softmax_estable(z)).max())The naive version returns inf with logits and -inf with logits ; the stable one gives and . With the gap is already only , and with the smooth maximum equals the maximum to every printed digit: the term with there is .
The professional version
| Tool | Purpose |
|---|---|
scipy.special.gammaln(x) | without overflow; gammaln(n + 1) is |
scipy.special.logsumexp(z, axis, b=None) | stable logsumexp over axes, with optional weights |
scipy.special.softmax(z, axis) | stable softmax over axes |
scipy.optimize.minimize(fun, x0, jac, method) | the mode, minimizing the negated log posterior |
mpmath | arbitrary-precision arithmetic to check asymptotics |
torch.logsumexp, torch.softmax | the same in PyTorch, with automatic differentiation |
import numpy as np
import mpmath
from scipy.special import gammaln, logsumexp, softmax
from scipy.optimize import minimize
# Stirling con K correcciones frente a mpmath con 50 cifras
mpmath.mp.dps = 50
def stirling_ln(n, K):
n = mpmath.mpf(n)
s = n * mpmath.log(n) - n + mpmath.log(2 * mpmath.pi * n) / 2
for k in range(1, K + 1):
s += mpmath.bernoulli(2 * k) / (2 * k * (2 * k - 1) * n**(2 * k - 1))
return s
print(" n gammaln(n+1) error K=0 K=1 K=2 K=4")
for n in [1, 5, 10, 100]:
exacto = mpmath.loggamma(n + 1)
errs = [float(abs(stirling_ln(n, K) - exacto)) for K in (0, 1, 2, 4)]
print(f"{n:4d} {gammaln(n + 1):18.12f} " + " ".join(f"{e:.2e}" for e in errs))
print("ln(10^6 !) =", gammaln(1e6 + 1), " Stirling K=0:", float(stirling_ln(10**6, 0)))
# logsumexp y softmax por ejes, comparados con lo implementado arriba
Zl = np.array([[1000.0, 999.0, 0.0], [-1000.0, -1001.0, -2000.0], [3.0, -np.inf, 1.0]])
print("\nscipy logsumexp por filas:", logsumexp(Zl, axis=1))
print("propio: ", [logsumexp_estable(fila) for fila in Zl])
print("softmax por filas:\n", np.round(softmax(Zl, axis=1), 4))
# la moda de la regresión logística con BFGS frente a Newton
X, y = X_todo[:80], y_todo[:80]
res = minimize(lambda w: -log_post(w, X, y)[0], np.zeros(2),
jac=lambda w: -grad_hess(w, X, y)[0], method="BFGS")
w_newton, H, _ = moda_newton(X, y)
print("\nmoda BFGS:", np.round(res.x, 6), " moda Newton:", np.round(w_newton, 6), " evaluaciones:", res.nfev)
cov_exacta = np.linalg.inv(-H)
print("hess_inv de BFGS:\n", np.round(res.hess_inv, 4))
print("(-H)^-1 exacta:\n", np.round(cov_exacta, 4))
print("error relativo de hess_inv:", np.linalg.norm(res.hess_inv - cov_exacta) / np.linalg.norm(cov_exacta))gammaln agrees with mpmath.loggamma to float64 precision, and the error table reproduces the figure: for , two corrections already go below . For , Stirling’s leading term and gammaln differ by over : exactly the first correction, , at float64 rounding level. scipy.special.logsumexp handles the same extreme cases as our version, including rows with .
The last part deserves a warning. minimize with BFGS finds the mode, but its hess_inv approximates the inverse Hessian using the few directions explored by the optimizer; it is not the Hessian at the mode. Laplace requires the actual Hessian: analytic, by automatic differentiation (in PyTorch, torch.func.hessian) or by finite differences of the gradient.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. The maximum of exponent is at and moves with . What do you do?
Step 1 of 3. How do you start?
logsumexp(z, axis=-1) and softmax(z, axis=-1) for NumPy arrays of any shape. logsumexp removes axis axis; softmax preserves shape and its values sum to 1 along axis. They must handle logits without warnings or infinities, accept inputs (which give probability 0) and, if all entries of a row are , logsumexp must return for that row. Do not use scipy.special.import numpy as np
def logsumexp(z, axis=-1):
z = np.asarray(z, dtype=float)
return np.log(np.sum(np.exp(z), axis=axis))
def softmax(z, axis=-1):
z = np.asarray(z, dtype=float)
e = np.exp(z)
return e / np.sum(e, axis=axis, keepdims=True)Summary
- Laplace’s method needs a unique, interior, separated and nondegenerate maximum. In the factor is , proportional to the uncertainty ellipsoid’s volume; applied to model evidence, it gives the Laplace approximation of the posterior and BIC.
- The first correction is with . Applied to after , it gives Stirling’s formula and first correction .
- The leading term fails at the boundary (factor , or scale if ), with multiple comparable maxima (sum them), and with a degenerate Hessian (scale ). In singular models such as neural networks, Watanabe’s theory replaces with a coefficient .
- is a smooth maximum: between and , convex, its gradient is softmax, and it is the maximum of on the simplex. Always compute it by subtracting the maximum.
- An asymptotic series improves each truncation as , but with fixed it can diverge: Euler’s and Stirling’s do. Truncate before the smallest term, and the remaining error is of that order, exponentially small in .