f-divergences, Jensen-Shannon and variational representations
Unify KL, reverse KL, total variation, Hellinger, chi-squared, and Jensen–Shannon as f-divergences. Study data processing, Jensen–Shannon and GANs, Pinsker's inequality, and variational representations that turn divergence estimation into optimization over critics.
After this lesson you can
- Express KL, reverse KL, total variation, Hellinger, chi-squared, and Jensen–Shannon as f-divergences using their generators.
- Prove data processing for f-divergences using Jensen's inequality.
- Prove the Jensen–Shannon upper bound and derive the original GAN objective with the optimal discriminator.
- Prove Pinsker's inequality and use it to bound differences in probabilities.
- Derive the Fenchel and Donsker–Varadhan representations and explain why the latter is tighter for KL.
Before you start
Motivation: each divergence is an algorithm
Much of distribution learning consists of choosing a way to measure how far a model is from data and minimizing it. This choice is not a technical detail: it changes the algorithm, what can be estimated from samples, and how it fails.
- Maximum likelihood minimizes KL divergence : it requires evaluating and severely penalizes a model that assigns almost zero probability to something produced by the data.
- The original GAN (Goodfellow et al., 2014) minimizes Jensen–Shannon divergence with an optimal discriminator. It only needs samples from , not its evaluation, but stops providing a gradient when model and data do not overlap (the GAN minimax game).
- The Wasserstein GAN (Arjovsky, Chintala, and Bottou, 2017) replaces JSD with an optimal transport distance that can see how far apart disjoint supports are (WGAN).
- Two-sample tests (do these data come from the same distribution as those?) use total variation, which exactly determines the best achievable error (classifier two-sample test).
- Neural mutual-information estimators (MINE, InfoNCE) maximize a KL lower bound over a “critic” network, using a variational representation we will see later (InfoNCE as a mutual-information bound).
This lesson shows that almost all these quantities are cases of one family, the f-divergences independently introduced by Csiszár (1963) and Ali and Silvey (1966). They share properties (nonnegativity, convexity, data processing) proved once for all, and each is specified by a convex function of one variable. We then study the three most common in machine learning besides KL: total variation, Hellinger, and Jensen–Shannon; relate them to one another (Pinsker); and reach the idea that makes them useful in practice: each divergence is the value of an optimization problem over critic functions, and can therefore be estimated by training a discriminator.
f-divergences
KL compares and through the likelihood ratio : . It is the mean under of evaluated at that ratio. Changing gives a whole family.
The second convention is the natural limit: as . It specifies the cost of mass of where puts none. For KL, , recovering if is not absolutely continuous with respect to .
| Divergence | Generator | Maximum | ||
|---|---|---|---|---|
| KL | ||||
| Reverse KL | ||||
| Total variation | does not exist | |||
| Squared Hellinger | ||||
| Pearson | ||||
| Jensen–Shannon |
In the last row, ; an exercise checks that this generator gives JSD. There are two Hellinger conventions: here ; other texts put in front so it lies in . Always check the source’s convention.
Three observations about the generator save work:
- The generator is not unique. For any , gives the same divergence, because (if ). Choosing (or minus a subgradient at 1 if is not differentiable there, as in TV) gives a generator with minimum at , and thus nonnegative: for KL, . Its integrand is also pointwise nonnegative, although that of is not.
- Swapping arguments changes the generator. with , which is also convex (the perspective of ). For , : reverse KL. An f-divergence is symmetric if and only if has the form .
- Near , all resemble . If is twice differentiable at 1, Taylor expansion , multiplied by and summed, gives : the linear term vanishes by observation 1. Thus all smooth divergences locally have the same quadratic form, the Fisher information of lesson 16, up to a factor.
With the figure shows the main division in the family. Total variation, Hellinger, and Jensen–Shannon saturate at 1, 2, and : beyond a certain separation they no longer distinguish “far” from “very far.” KL grows as and explodes as . With , KL and change on swapping arguments (with , is even infinite while is finite); TV, Hellinger, and JSD do not, because their generators satisfy . On a logarithmic scale, tends to 1 as with , for all except TV, whose generator has a cusp at and grows linearly.
Common properties
Proof
We handle the case (if then ); the general case adds and is treated similarly using .
(1) By Jensen’s inequality with variable , : . If is strictly convex at 1, equality in Jensen requires to be constant -almost surely, that is, .
(2) It suffices to show that the perspective is jointly convex in and sum over . If , then is a convex combination, and by convexity of , . For KL this is the log-sum inequality, used to prove its joint convexity.
(3) Fix an output with and define weights , which sum to 1 over (they are the input posterior given the output under ). Then
and by Jensen, . Multiply by and sum over : the right-hand side becomes , because .
(4) For a convex function, the chord slope from 0, , increases with and tends to . Hence , and multiplying by gives . Summing, . If the supports are disjoint, each has (contributing ) or (contributing ), and the sum is exactly .
∎Point (3) generalizes the data-processing inequality for mutual information: no transformation of data, deterministic or random, makes two distributions more distinguishable, and this holds for every f-divergence at once. If the transformation is invertible, apply it both ways and divergence is unchanged. This invariance has a hidden side: an f-divergence does not care how space is organized, only about ratios .
Point (4) is the saturation seen in the figure, now for the entire family: TV is on disjoint supports, Hellinger , JSD , and KL and , . Two distributions with disjoint supports have the same f-divergence whether their supports are or apart. We return to this with GANs.
Total variation and Hellinger: error of the best test
The three expressions agree. With , for any event , , and by symmetry . Since , the two sums over and its complement are equal, , and the supremum is attained at . The third expression follows from . It is the f-divergence of and also a metric: half the norm.
Its operational interpretation explains why it appears everywhere.
Proof
A deterministic rule is a set on which one says “.” Its error probability is , minimized when is maximal, that is, at , where it equals . A randomized rule says “” with probability and its error, , is linear in , so its minimum is at a vertex .
∎Thus means no test beats a coin flip, and means a perfect test exists. With priors and the minimum error is by the same argument. This is the simplest form of the Neyman–Pearson lemma and the basis for using a classifier trained to distinguish samples as a two-sample test: its accuracy is bounded by .
Many observations: Hellinger tensorizes
What if you observe iid samples? The question becomes , which has no simple expression in terms of . Hellinger, however, behaves beautifully with products. Write it using the Bhattacharyya coefficient :
For products, factors, so and . It remains to relate Hellinger and TV:
Proof
Left: , hence . Right: by Cauchy–Schwarz, , and divide by 2.
∎The consequence is a scaling law: distinguishing from with small error requires on the order of samples, no more and no less. For a fair coin against one with probability of heads, and . To guarantee error requires . The left bound says suffices, that is, ; the right says at least is needed. The exact value, computed with the two binomials, is , between the two and of order times a constant. KL tensorizes even better, (the chain rule), and satisfies . TV does not tensorize: that is why statistical lower-bound proofs usually go through Hellinger or KL and return to TV at the end.
Jensen–Shannon: a divergence that can be symmetrized sensibly
KL is asymmetric and can be infinite. The naive fix, , is symmetric but remains infinite whenever one support does not contain the other. Lin (1991) proposed comparing both with their mixture, which always contains them.
The second form explains the name: it is the Jensen gap of entropy, which is concave, between the entropy of the mixture and the mixture of entropies. Since and , the ratios and are bounded by 2, and both KL terms are finite.
Proof
(1) Mutual information is the average KL between conditionals and the marginal: , and here the marginal of is . (2) , with equality if and only if , that is, if seeing reveals which distribution it came from: disjoint supports. Nonnegativity, with equality only if , follows from KL. (3) Symmetry is immediate from the definition; the exercises verify the generator. (5) Lower bound: , and by Pinsker’s inequality in the next section, , likewise for , then average. Upper bound: with , decompose and , where , , and ; and have disjoint supports. By joint convexity, .
∎The mutual-information interpretation is most useful: JSD measures how much an observer learns about the “real or generated” label upon seeing a sample from the equally weighted mixture. With weights and distributions, with , and its maximum over is the channel capacity (the “information radius” of lesson 9). The root is used as a distance between distributions in clustering and document retrieval because it is a bounded metric; JSD without the root does not satisfy the triangle inequality (you will check this numerically).
JSD and GANs
A GAN pits a generator , which transforms noise into samples with distribution , against a discriminator estimating the probability that comes from data . The original objective is
For fixed , the maximum over can be found pointwise: at each maximize with , , whose derivative vanishes at . Therefore the optimal discriminator is
the posterior probability of “real” with equal priors. Substitution gives:
The proof is one line of algebra you will do in the guided exercise: write . This result justified GANs, but also points to their weakness. If and have disjoint supports, property (4) says for every in a neighborhood: the objective is constant and its gradient with respect to is exactly zero. This is not rare. Arjovsky and Bottou (2017) observed that when data and generator samples live on manifolds of lower dimension than the ambient space (images of pixels generated from 100-dimensional noise), they typically do not intersect, and a perfect discriminator exists.
With uniform shapes, while supports overlap, JSD is exactly , a straight line, and stops increasing at . Beyond that the optimal discriminator is 1 throughout the support of and 0 on that of , and shifting the generator does not change it. With Gaussians the gradient is never zero, but at with it is already of order : practically the same. In contrast, for any translation: slope 1 at any distance.
Goodfellow et al. already proposed in 2014 training the generator with the non-saturating loss instead of : with a discriminator that confidently rejects fake samples, is flat, but is very steep. This fix works, but no longer minimizes JSD: Arjovsky and Bottou showed that, with an optimal discriminator, its gradient is that of , a peculiar combination that pushes both to reduce reverse KL (which tolerates forgetting modes of ) and to move away in JSD. You will measure this in the minimal GAN at the end of the lesson.
The fundamental solution was to change families. The Wasserstein distance is defined by optimal transport and, by Kantorovich–Rubinstein duality, is also a supremum over critics: . Compare it with total variation, which has the same form with another class: . TV lets the critic jump from to in one step, so it ignores support separation; forces it to rise with bounded slope, making distance between supports count. It is not an f-divergence: it depends on the space’s metric, precisely what f-divergences ignore.
Pinsker’s inequality and other relations
Does small KL force the probabilities of every event to be close? Yes, with an optimal constant.
Pinsker’s inequality is proved in two steps; the first is the general pattern for relating f-divergences: reduce to the binary case using data processing. Let and apply to and the deterministic channel . The outputs are two coins, and with and . By data processing, , where is binary KL; TV loses nothing, because exactly (the supremum was attained at ). This leaves an inequality between two numbers,
proved using single-variable calculus: function is 0 at and decreases on , because and . You will reconstruct the details in the guided exercise.
In practice, Pinsker translates KL constraints, which can be imposed and optimized, into guarantees about probabilities, which are what matter. If a model satisfies nats, no event’s probability changes by more than , whether “the answer is toxic” or “the action is to jump.” This is used in policy trust-region methods (TRPO bounds KL between new and old policies and Pinsker converts that to a TV bound used in its improvement guarantee) and in RLHF’s KL penalty.
The figure also shows what Pinsker does not say. The bound is one-way: there is no upper bound on KL in terms of TV, because only needs to assign probability 0 where assigns a little for KL to be infinite with arbitrarily small TV. And when TV approaches 1, falls short while KL may be enormous. A better bound exists in that regime.
Proof
All follow from Jensen. because . Next, . By concavity of the logarithm, , and . For Bretagnolle–Huber, Cauchy–Schwarz gives , and with we obtain .
∎Bretagnolle–Huber, written as , is worse than Pinsker for small TV (growing as rather than ) but tends to infinity as . The two curves cross at , where nats. Comparison also explains the zoo figure: explodes exponentially while KL grows only quadratically.
Variational representations: a divergence is the best discriminator
All previous formulas require densities and . In learning we rarely have them: we have samples from data and samples (or a simulator) from the model. The solution is to rewrite each divergence as the maximum of an optimization problem over functions , whose objective contains only expectations, estimable by sample means.
Fenchel representation
Recall the convex conjugate . For convex lower-semicontinuous , , that is, : every convex function is the upper envelope of its tangent lines.
Proof
By Fenchel–Young, for every and . Apply it at each with and , multiply by and sum: . Equality in Fenchel–Young holds when is a subgradient of at , so turns the inequality into equality at every .
∎This variational representation of divergence has a transformative interpretation: divergence is the value of the best critic. tries to take high values where lies and values with low where lies; the better it separates them, the larger the bound; and the optimal critic is a function of the likelihood ratio, like the optimal GAN discriminator. For KL, and the bound is that of Nguyen, Wainwright, and Jordan (NWJ, 2010):
| Divergence | Domain of | Optimal critic | |
|---|---|---|---|
| KL | |||
| Reverse KL | |||
| (and if ) | |||
| Hellinger² | |||
| Total variation | |||
| GAN: |
The last row closes the circle. The GAN generator is convex but does not satisfy (it equals ), so does not vanish at but equals that constant: , and if the critic is written with , the Fenchel objective is : the original GAN is the variational representation of an f-divergence. Nowozin, Cseke, and Tomioka (2016) generalized the recipe as f-GANs (f-GAN): choose a generator , parameterize the critic as with network and output activation respecting the domain of , and solve . Each choice of gives a different GAN, and all inherit point (4): with disjoint supports, they all saturate.
Donsker–Varadhan representation
For KL there is a different, tighter representation.
Proof
Given , define the tilted distribution with . Then , and taking expectation under ,
Equality holds if and only if , that is, .
∎Why is it tighter? Because for every (with equality at ), so for the same , , and
Moreover, if you optimize NWJ only over the constant, , derivative vanishes at and the value is exactly . DV is NWJ with the constant chosen optimally. Two practical consequences: if the critic class admits adding constants (a network with output bias), the suprema coincide; and DV is invariant to that constant, while NWJ must learn it. The difference is in estimation: NWJ is linear in , so a minibatch mean is an unbiased estimator of the bound for fixed ; DV contains the logarithm of a mean, and by Jensen, so its estimator is biased upward, as are its minibatch gradients. MINE (Belghazi et al., 2018), the neural mutual-information estimator based on DV, corrects that bias with a moving average of the denominator.
The figure shows four facts that determine whether a variational estimator is useful. With a family containing the optimum and many samples, both bounds reach KL; DV is often ahead in early iterations because it starts at 0 instead of and need not learn the constant. With an overly poor family (linear with ), both stay below: the bound is valid but loose. With a very flexible family and few samples, the critic memorizes samples and the estimate exceeds KL: it is no longer a bound, because the bound holds for fixed and here was selected using the same data on which it is evaluated. Dispersion across repetitions grows very quickly with KL: term is dominated by rare samples of where is enormous. This is not specific to these estimators: McAllester and Stratos (2020) proved that no high-confidence lower bound built from samples, without further distributional assumptions, can exceed a value of order . Estimating large divergences or mutual information from samples is intrinsically difficult; see variational mutual-information bounds.
Beyond: Rényi and optimal transport
Two neighboring families complete the map. The Rényi divergence of order ,
is not an f-divergence, but is an increasing function of one: equals with convex generator if , and with if ; in both cases prefactor makes increase with . It therefore inherits data processing. It interpolates between familiar cases: , as , and ; the comparison chain above is monotonicity of in . It appears in differential privacy (Rényi accounting) and variational inference.
Optimal transport distances measure the cost of moving mass from to when moving one unit from to costs . Unlike f-divergences, they depend on the geometry of space, are finite between disjoint supports, and grow with their separation; in return, they have no closed-form expression in terms of , are costlier to compute, and their sample estimation worsens with dimension. Neither family is better: each answers a different question (how much are they confused versus how far must mass move?).
Implementation from scratch
First, a function computes any discrete f-divergence from its generator, with both zero conventions. We check it against the table, symmetry under swapping arguments, and saturation on disjoint supports.
import numpy as np
def f_divergencia(p, q, f, f_inf):
"""D_f(p||q) = sum_x q f(p/q), con 0 f(0/0) = 0 y, si q = 0 < p, el término p * f'(inf)."""
p, q = np.asarray(p, float), np.asarray(q, float)
total = 0.0
for pi, qi in zip(p, q):
if qi > 0:
total += qi * f(pi / qi)
elif pi > 0:
total += pi * f_inf # f_inf = lim f(t)/t cuando t -> inf
return total
def xlogx(t):
return t * np.log(t) if t > 0 else 0.0
# nombre: (generador, f'(inf))
GEN = {
"KL": (xlogx, np.inf),
"KL inversa": (lambda t: -np.log(t) if t > 0 else np.inf, 0.0),
"TV": (lambda t: 0.5 * abs(t - 1), 0.5),
"Hellinger²": (lambda t: (np.sqrt(t) - 1) ** 2, 1.0),
"χ²": (lambda t: (t - 1) ** 2, np.inf),
"JS": (lambda t: 0.5 * (xlogx(t) - (1 + t) * np.log((1 + t) / 2)), np.log(2) / 2),
}
p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.3, 0.5])
print(f"{'':11s} {'D(p||q)':>9s} {'D(q||p)':>9s}")
for nombre, (f, f_inf) in GEN.items():
print(f"{nombre:11s} {f_divergencia(p, q, f, f_inf):9.4f} {f_divergencia(q, p, f, f_inf):9.4f}")
def H(r):
r = r[r > 0]
return -np.sum(r * np.log(r))
m = (p + q) / 2
print("\nJS como hueco de Jensen de la entropía:", round(H(m) - (H(p) + H(q)) / 2, 6))
# soportes disjuntos: toda divergencia f vale f(0) + f'(inf)
a = np.array([0.5, 0.5, 0.0, 0.0])
b = np.array([0.0, 0.0, 0.3, 0.7])
for nombre, (f, f_inf) in GEN.items():
print(f"disjuntas, {nombre:11s}: {f_divergencia(a, b, f, f_inf):.4f} f(0) + f'(inf) = {f(0.0) + f_inf:.4f}")KL and change on swapping and ; TV, Hellinger, and JSD do not. On disjoint supports each divergence takes exactly its maximum : , , and for the bounded ones, for the others.
Now test the lesson’s general claims on many random pairs: data processing with random channels for all six divergences, Pinsker, Bretagnolle–Huber, JSD bounds in terms of TV, and the triangle inequality for (and its failure without the square root).
import numpy as np
rng = np.random.default_rng(0)
def divs(p, q):
"""Las seis divergencias, vectorizadas por filas (p, q de forma (N, k), sin ceros)."""
m = (p + q) / 2
kl = np.sum(p * np.log(p / q), axis=1)
return {
"KL": kl,
"KL inversa": np.sum(q * np.log(q / p), axis=1),
"TV": 0.5 * np.abs(p - q).sum(axis=1),
"Hellinger²": np.sum((np.sqrt(p) - np.sqrt(q)) ** 2, axis=1),
"χ²": np.sum((p - q) ** 2 / q, axis=1),
"JS": 0.5 * np.sum(p * np.log(p / m), axis=1) + 0.5 * np.sum(q * np.log(q / m), axis=1),
}
N, k, k_sal = 20000, 5, 3
p = rng.dirichlet(np.ones(k), N)
q = rng.dirichlet(np.ones(k), N)
K = rng.dirichlet(np.ones(k_sal), (N, k)) # un canal aleatorio k -> k_sal por par
pK = np.einsum("nx,nxy->ny", p, K)
qK = np.einsum("nx,nxy->ny", q, K)
antes, despues = divs(p, q), divs(pK, qK)
print("Procesamiento de datos: máximo de D(PK||QK) / D(P||Q) en", N, "pares")
for nombre in antes:
print(f" {nombre:11s} {np.max(despues[nombre] / antes[nombre]):.4f}")
d = divs(p, q)
tv, kl, js = d["TV"], d["KL"], d["JS"]
print("\nPinsker, mín KL / (2 TV²): ", round(np.min(kl / (2 * tv**2)), 4))
print("Bretagnolle-Huber, máx TV / sqrt(1-e^-KL):", round(np.max(tv / np.sqrt(1 - np.exp(-kl))), 4))
print("JS >= TV²/2, mín JS / (TV²/2): ", round(np.min(js / (tv**2 / 2)), 4))
print("JS <= TV log 2, máx JS / (TV log 2): ", round(np.max(js / (tv * np.log(2))), 4))
H2, c2 = d["Hellinger²"], d["χ²"]
print("cadena H² <= KL <= log(1+χ²) <= χ²: ", bool(np.all(H2 <= kl) and np.all(kl <= np.log1p(c2)) and np.all(np.log1p(c2) <= c2)))
# desigualdad triangular con tríos de distribuciones de 3 resultados
a, b, c = (rng.dirichlet(0.5 * np.ones(3), N) + 1e-12 for _ in range(3))
js_ab, js_bc, js_ac = divs(a, b)["JS"], divs(b, c)["JS"], divs(a, c)["JS"]
print("\nsqrt(JS): máx de d(a,c) - d(a,b) - d(b,c) =", round(np.max(np.sqrt(js_ac) - np.sqrt(js_ab) - np.sqrt(js_bc)), 6))
print("JS sin raíz: máx de JS(a,c) - JS(a,b) - JS(b,c) =", round(np.max(js_ac - js_ab - js_bc), 4))No data-processing ratio exceeds 1 and all inequalities hold. The extremes are informative: the minimum Pinsker ratio is very close to 1 (the constant 2 cannot be improved), as is JSD against . The square root of JSD never violates the triangle inequality; JSD without the root violates it substantially.
Finally, variational bounds from samples. With and , ratio is linear in , so a linear critic contains the optimum and what we measure is estimation error, not approximation error. Both empirical bounds are concave in , and we maximize them with scipy.optimize.minimize using analytic gradient and Hessian (with BFGS and no Hessian, exponentials overflow as soon as line search tries a long step).
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp, softmax
def rasgos(x):
return np.stack([np.ones_like(x), x], axis=1) # crítico lineal T(x) = th0 + th1 x
def nwj(th, Fp, Fq):
"""Valor, gradiente y hessiana de la cota NWJ empírica (cóncava en th)."""
e = np.exp(Fq @ th - 1) / len(Fq)
return Fp.mean(0) @ th - e.sum(), Fp.mean(0) - Fq.T @ e, -(Fq.T * e) @ Fq
def dv(th, Fp, Fq):
"""Lo mismo para Donsker-Varadhan, con log-sum-exp para no desbordar."""
s = Fq @ th
w = softmax(s)
g = Fq.T @ w
return Fp.mean(0) @ th - (logsumexp(s) - np.log(len(s))), Fp.mean(0) - g, -((Fq.T * w) @ Fq - np.outer(g, g))
def maximizar(cota, Fp, Fq):
res = minimize(lambda th: -cota(th, Fp, Fq)[0], np.zeros(2), jac=lambda th: -cota(th, Fp, Fq)[1],
hess=lambda th: -cota(th, Fp, Fq)[2], method="trust-exact")
return -res.fun
rng = np.random.default_rng(1)
n, reps = 1000, 25
print(f"n = {n} muestras de cada distribución, {reps} repeticiones")
print(" mu | KL verdadera | NWJ: media (desv.) | DV: media (desv.) | máx |NWJ - DV|")
for mu in [1.0, 2.0, 2.5]:
kl_verdad = mu**2 / 2
est_n, est_d = [], []
for _ in range(reps):
Fp, Fq = rasgos(rng.normal(mu, 1, n)), rasgos(rng.normal(0, 1, n))
est_n.append(maximizar(nwj, Fp, Fq))
est_d.append(maximizar(dv, Fp, Fq))
est_n, est_d = np.array(est_n), np.array(est_d)
print(f" {mu:.1f} | {kl_verdad:12.3f} | {est_n.mean():8.3f} ({est_n.std():.3f}) | {est_d.mean():7.3f} ({est_d.std():.3f}) | {np.max(np.abs(est_n - est_d)):.1e}")
# El sesgo del logaritmo de una media: crítico ÓPTIMO fijo, estimaciones en minilotes de tamaño B
mu = 1.5
kl_verdad, chi2 = mu**2 / 2, np.exp(mu**2) - 1
print(f"\nCrítico óptimo fijo, mu = {mu}: KL = {kl_verdad:.4f}, chi² = {chi2:.2f}")
for B in [16, 64, 256]:
xp = rng.normal(mu, 1, (4000, B))
xq = rng.normal(0, 1, (4000, B))
T_p, T_q = mu * xp - mu**2 / 2, mu * xq - mu**2 / 2 # T* = log(p/q)
dv_mb = T_p.mean(1) - np.log(np.exp(T_q).mean(1))
nwj_mb = (T_p + 1).mean(1) - np.exp(T_q).mean(1) # T* de NWJ = 1 + log(p/q)
print(f"B = {B:3d}: sesgo DV = {dv_mb.mean() - kl_verdad:+.4f} (predicción chi²/2B = {chi2 / (2 * B):.4f}),"
f" sesgo NWJ = {nwj_mb.mean() - kl_verdad:+.4f}, desv. DV = {dv_mb.std():.3f}, NWJ = {nwj_mb.std():.3f}")Three results. The NWJ and DV maxima agree to optimizer precision because the linear critic has a constant term and DV is NWJ with the optimal constant. Standard deviation grows rapidly with KL (from at KL to at KL ), and the mean begins to overshoot ( versus ). There is a concrete reason: for large , , so if no sample from exceeds the mean of samples from , the empirical maximum is infinite. With and this happens about half the time; that is why the table stops at with . With the optimal critic fixed, minibatch DV estimation is biased upward while NWJ is not. A second-order expansion of around predicts bias , because the variance of under is ; the prediction works well for and exaggerates with small minibatches, where heavy tails of break the expansion. In return, DV has somewhat less variance than NWJ here: no estimator is free.
A minimal 1D GAN
To see saturation in real training, without networks or automatic differentiation, an affine generator with and a logistic discriminator on quadratic features, , suffice; it can represent the optimal discriminator between two Gaussians. Data are . The two generator losses differ only in their derivative with respect to : with the logit and ,
When the discriminator confidently rejects a fake sample, : the first derivative vanishes and the second does not. First measure the generator gradient with the discriminator fitted to optimum (logistic regression by Newton’s method) at different separations; then actually train both versions from far away.
import numpy as np
def sigmoide(s):
return 0.5 * (1 + np.tanh(0.5 * s))
def phi(x):
return np.stack([np.ones_like(x), x, x * x], axis=1)
MU_P, SD_P = 2.0, 0.5
def discriminador_optimo(xr, xf, iters=25, lam=1e-3):
"""Regresión logística (reales = 1, falsos = 0) por Newton: el mejor D de la familia."""
X = np.vstack([phi(xr), phi(xf)])
y = np.r_[np.ones(len(xr)), np.zeros(len(xf))]
w = np.zeros(3)
for _ in range(iters):
d = sigmoide(X @ w)
g = X.T @ (y - d) / len(y) - lam * w
H = (X * (d * (1 - d))[:, None]).T @ X / len(y) + lam * np.eye(3)
w = w + np.linalg.solve(H, g)
return w
def grad_generador(w, a, b, z, perdida):
x = a * z + b
d = sigmoide(phi(x) @ w)
ds = w[1] + 2 * w[2] * x
gx = -d * ds if perdida == "saturante" else -(1 - d) * ds
return np.array([np.mean(gx * z), np.mean(gx)]) # (dL/da, dL/db)
rng = np.random.default_rng(0)
xr, z = rng.normal(MU_P, SD_P, 4000), rng.normal(size=4000)
print(" b | JSD estimada (nats) | |grad| saturante | |grad| no saturante")
for b in [1.0, 0.0, -1.0, -2.0, -3.0]:
xf = SD_P * z + b
w = discriminador_optimo(xr, xf)
V = np.mean(np.log(sigmoide(phi(xr) @ w))) + np.mean(np.log(1 - sigmoide(phi(xf) @ w)))
js = (V + np.log(4)) / 2 # V(D*, G) = 2 JS - log 4
gs = np.linalg.norm(grad_generador(w, SD_P, b, z, "saturante"))
gn = np.linalg.norm(grad_generador(w, SD_P, b, z, "no saturante"))
print(f" {b:4.1f} | {js:19.4f} | {gs:16.2e} | {gn:.2e}")
def entrenar(perdida, pasos=1200, lote=128, k=3, lr_d=0.1, lr_g=0.05, seed=1):
r = np.random.default_rng(seed)
a, b, w = 0.5, -3.0, np.zeros(3)
normas, llegada = [], None
for t in range(pasos):
for _ in range(k): # k pasos del discriminador
xr_, xf_ = r.normal(MU_P, SD_P, lote), a * r.normal(size=lote) + b
dr, df = sigmoide(phi(xr_) @ w), sigmoide(phi(xf_) @ w)
w += lr_d * (phi(xr_).T @ (1 - dr) - phi(xf_).T @ df) / lote
g = grad_generador(w, a, b, r.normal(size=lote), perdida)
a, b = a - lr_g * g[0], b - lr_g * g[1]
normas.append(np.linalg.norm(g))
if llegada is None and abs(b - MU_P) < 0.25:
llegada = t
return a, b, np.median(normas[:200]), llegada
print("\nEntrenamiento desde b = -3 (los datos están en 2):")
for perdida in ["saturante", "no saturante"]:
a, b, med, llegada = entrenar(perdida)
print(f" {perdida:13s} mediana de |grad| en los 200 primeros pasos = {med:.1e};"
f" llega a |b - 2| < 0.25 en el paso {llegada}; final a = {a:.2f}, b = {b:.2f}")With the optimal discriminator, estimated JSD approaches as soon as the Gaussians separate, and the saturating loss gradient falls with separation while the non-saturating one remains of order 1. At the saturating gradient is about 570 times smaller. In real training the discriminator is not optimal (it gets only three gradient steps per generator step), leaving some gradient: the saturating version eventually arrives, but at step 1061, after hundreds of almost stalled steps with gradients of order ; the non-saturating version arrives at step 64. Notice the final value of : the saturating run ends with (0.002), a generator producing almost always the same point near the data mean. This is miniature mode collapse: is a fixed point, because with constant and symmetric the gradient with respect to is , and the generator cannot escape. The non-saturating version ends with , near for the data, but there is no guarantee: another seed or step count can also collapse.
The library version
SciPy provides the pieces, with conventions worth knowing:
| Function | What it computes | Watch out for |
|---|---|---|
scipy.special.rel_entr(p, q) | elementwise | sum yourself; handles and |
scipy.special.kl_div(p, q) | nonnegative generator ; sum equals KL only if | |
scipy.stats.entropy(p, q, base=2) | , normalizing and | normalizes silently |
scipy.spatial.distance.jensenshannon(p, q, base=2) | returns the square root; base by default | |
torch.distributions.kl_divergence(P, Q) | closed-form KL between parametric distributions | registered pairs only |
torch.nn.functional.kl_div(input, target) | with input in logarithms | argument order is reversed relative to notation |
import numpy as np
from scipy.special import rel_entr, kl_div
from scipy.stats import entropy
from scipy.spatial.distance import jensenshannon
p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.3, 0.5])
print("KL con rel_entr: ", rel_entr(p, q).sum())
print("KL con kl_div: ", kl_div(p, q).sum(), " (elemento a elemento:", np.round(kl_div(p, q), 4), ")")
print("KL con entropy: ", entropy(p, q))
print("JS (divergencia, nats):", jensenshannon(p, q) ** 2)
print("JS (distancia, bits): ", jensenshannon(p, q, base=2))
# sin normalizar: kl_div incluye -p + q, rel_entr no; entropy normaliza en silencio
p2, q2 = 2 * p, q
print("\nsin normalizar: rel_entr =", round(rel_entr(p2, q2).sum(), 4), " kl_div =", round(kl_div(p2, q2).sum(), 4),
" entropy =", round(entropy(p2, q2), 4))All three paths give the same KL for normalized distributions; kl_div has positive contributions in every term although that of rel_entr in the third is negative, because it uses the shifted generator from the first section. With unnormalized vectors all three differ. In PyTorch, loss F.kl_div(log_q, p, reduction="batchmean") computes with as the first argument: reversing the order is a classic silent error.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What do you check first?
Step 1 of 3. How do you rewrite and in terms of ?
Step 1 of 3. How do you reduce the problem to two coins?
div_f(p, q, nombre) for nombre in 'kl', 'tv', 'hellinger2', 'chi2', and 'js', vectorized with NumPy and using the lesson's conventions: with do not count, those with contribute (which may be np.inf), and those with contribute . Return a float in nats. Do not use Python loops over elements or SciPy.import numpy as np
def div_f(p, q, nombre):
"""Divergencia f discreta D_f(p||q) en nats, con los convenios para los ceros."""
p, q = np.asarray(p, float), np.asarray(q, float)
# tu código: separa los casos q > 0, q = 0 < p y p = q = 0
return 0.0Summary
- with convex and includes KL (), reverse KL (), TV (), Hellinger (), (), and JSD. All are nonnegative, jointly convex, decrease under data processing, and attain maximum on disjoint supports. Near , .
- TV gives the best test error: . Hellinger tensorizes () and establishes that distinguishing two distributions costs on the order of samples.
- JSD is mutual information between a mixture sample and its label: symmetric, bounded by (1 bit), with a metric. With optimal discriminator, the GAN objective is , so it saturates when supports do not overlap; Wasserstein does not, because it uses spatial geometry.
- Pinsker, , converts KL bounds into bounds on event probabilities; it follows by reducing to the binary case via data processing and is tight for nearly fair coins. Bretagnolle–Huber improves it as TV approaches 1.
- By convex duality, (NWJ for KL, f-GAN generally), and for KL, Donsker–Varadhan is tighter for each and equal after optimizing a constant. Estimating them from samples requires monitoring the critic (underestimation if too weak, overfitting if flexible), minibatch logarithm bias, and variance growing exponentially with divergence.