GANs: learning from a changing discriminator
生成对抗网络
Derive the optimal discriminator, train a five-parameter GAN and test what a score of one half means.
gansA learned training signal
Suppose a synthetic data source draws numbers uniformly between −0.7 and 1.7. You want another program to produce the same distribution from noise. Matching the mean alone is insufficient: always returning 0.5 gets the mean right but loses all variation. A fixed squared error against arbitrarily paired real samples is also a poor description of this distribution-learning problem.
A generative adversarial network, or GAN, learns a discriminator that distinguishes real samples from generated samples. The generator changes its outputs in response to this learned signal. The original GAN paper formulates this as a two-player game. A discriminator is a training component; once trained, the generator can produce samples without asking it for permission. Start with generative models and binary cross-entropy.
Which player minimizes what?
Let P be the real distribution, Z a chosen noise distribution and Gθ a differentiable generator. Its outputs have an induced distribution Qθ. Dψ maps a sample to a number between zero and one, interpreted as its real-class probability for the balanced classification problem used here.
D maximizes the classification log-likelihood; equivalently it minimizes its negative. In the minimax version, G minimizes the fake-sample term while holding D fixed for that update. “Holding D fixed” means not updating its parameters, not cutting the derivative of D’s output with respect to its input. That input derivative is how the generator receives a signal.
Section 3 of the paper also proposes the commonly used non-saturating generator objective. This changes G’s update while keeping D’s classification objective:
What the optimal discriminator tells us
First consider a finite support, with real and generated probabilities p and q. For each location j, maximize its contribution with respect to Dj. The interior first derivative vanishes at the density ratio below, while the second derivative is nonpositive. When one mass is zero the optimum can lie at an endpoint; when both are zero the choice is irrelevant.
Substitute this optimum into the value. With the mixture m, the two logarithms split into a log2 constant and a KL term. Their average is the Jensen–Shannon divergence:
Thus matching distributions attain −log4, and the optimal discriminator is one half on their support. Disjoint distributions give JS=log2 and value zero. These are statements about an optimized, unrestricted discriminator, not a guarantee that every neural training run minimizes JS directly. The identity also does not make the non-saturating objective identical to JS minimization at every step. Theorem 1 and Proposition 2 separate the optimum from conditional convergence; later convergence analysis gives simple games where unregularized updates do not converge.
The executable model has a two-parameter affine generator and a three-parameter quadratic-logit discriminator. The target distribution is exactly representable within this deliberately restricted generator family:
For discriminator features φ(x)=[x,x²,1], differentiate the logistic log-likelihood. A real sample contributes (1-D)φ; a fake sample contributes −Dφ. For G, differentiate through the logit with D’s parameters fixed:
For the minimax gradient, replace −(1-D) with −D. The generator’s continuous map supplies a pathwise derivative. Sampling a hard categorical index would require another estimator or relaxation; one cannot silently differentiate through an integer draw using this formula.
Five parameters, two distinct checks
Save as gan.py; use Python 3.12 and NumPy 1.26.4. The finite-support functions check the ideal D/JS identity. The training functions implement the separate continuous GAN. They use 32-point Gauss–Legendre quadrature to approximate expectations, not random minibatches. This quadrature is exact for suitable low-degree polynomials, but the logistic integrands here are not polynomials; tests compare 32 and 64 points at specified parameters.
Each of 2,000 rounds uses five D ascent steps of size 0.1 and one non-saturating G descent step of size 0.03. Both players use explicit gradients. All three D parameters and both G parameters are checked by finite differences with the other player fixed. With B quadrature points and I rounds, this fixed-size model costs O(IB) for a fixed number of D updates and O(B) working space, plus saved checkpoints. Larger network costs depend on their architectures.
"""Original five-parameter continuous GAN and a separate finite-distribution theorem check."""
import json
from functools import lru_cache
import numpy as np
def probability(p):
p = np.asarray(p, float)
if (p.ndim != 1 or not 1 <= p.size <= 128 or not np.isfinite(p).all()
or np.any(p < 0) or abs(float(p.sum())-1) > 1e-12):
raise ValueError('A finite probability vector of length 1..128 summing to one required.')
return p
def optimal_discriminator(p, q):
p, q = probability(p), probability(q)
if p.shape != q.shape:
raise ValueError('Distributions must use the same support.')
d = np.full(p.shape, .5)
np.divide(p, p+q, out=d, where=p+q > 0)
return d
def finite_game(p, q):
p, q = probability(p), probability(q)
d = optimal_discriminator(p, q)
# Avoid 0*log(0); use q/(p+q), not 1-d, to avoid cancellation.
ip, iq = p > 0, q > 0
value = np.sum(p[ip]*np.log(d[ip])) + np.sum(q[iq]*np.log(q[iq]/(p+q)[iq]))
m = (p+q)/2
js = .5*(np.sum(p[ip]*np.log(p[ip]/m[ip]))+np.sum(q[iq]*np.log(q[iq]/m[iq])))
return float(value), float(js)
@lru_cache(maxsize=8)
def quadrature(order=32):
if isinstance(order, bool) or not isinstance(order, int) or not 4 <= order <= 128:
raise ValueError('Integer quadrature order in [4,128] required.')
z, weights = np.polynomial.legendre.leggauss(order)
z.setflags(write=False)
weights = weights/2
weights.setflags(write=False)
return z, weights
def parameters(generator, discriminator):
g, d = np.asarray(generator, float), np.asarray(discriminator, float)
if (g.shape != (2,) or d.shape != (3,) or not np.isfinite(g).all()
or not np.isfinite(d).all() or np.max(abs(g)) > 10 or np.max(abs(d)) > 10):
raise ValueError('Two generator and three discriminator parameters bounded by 10 required.')
return g, d
def features(x):
return np.column_stack((x, x*x, np.ones_like(x)))
def discriminator_objective(generator, discriminator, order=32):
"""Maximize this value with G fixed. Quadrature is approximate for logistic integrands."""
g, d = parameters(generator, discriminator)
z, w = quadrature(order)
real, fake = features(1.2*z+.5), features(g[0]*z+g[1])
tr, tf = real@d, fake@d
real_complement = np.exp(-np.logaddexp(0., tr))
df = np.exp(-np.logaddexp(0., -tf))
value = w@(-np.logaddexp(0., -tr)-np.logaddexp(0., tf))
gradient = (w*real_complement)@real - (w*df)@fake
return float(value), gradient
def generator_objective(generator, discriminator, mode='non-saturating', order=32):
"""Minimize with D fixed; differentiate through continuous affine G."""
g, d = parameters(generator, discriminator)
z, w = quadrature(order)
fake = g[0]*z+g[1]
t = features(fake)@d
df = np.exp(-np.logaddexp(0., -t))
if mode == 'non-saturating':
loss, dt = np.logaddexp(0., -t), -np.exp(-np.logaddexp(0., t))
elif mode == 'minimax':
loss, dt = -np.logaddexp(0., t), -df
else:
raise ValueError('Choose non-saturating or minimax.')
dx = dt*(d[0]+2*d[1]*fake)
return float(w@loss), np.array([w@(dx*z), w@dx])
def train(steps=2000, discriminator_steps=5):
if (isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 4000
or isinstance(discriminator_steps, bool) or not isinstance(discriminator_steps, int)
or not 1 <= discriminator_steps <= 10):
raise ValueError('Integer steps in [0,4000] and D steps in [1,10] required.')
g, d = np.array([.4, -.4]), np.zeros(3)
history = []
for step in range(steps+1):
if step % 100 == 0 or step == steps:
history.append([step, float(g[1]), float(g[0]**2/3),
discriminator_objective(g, d)[0], generator_objective(g, d)[0]])
if step < steps:
for _ in range(discriminator_steps):
d += .1*discriminator_objective(g, d)[1]
g -= .03*generator_objective(g, d)[1]
return g, d, history
def demo():
g, d, history = train()
cases = {}
for name, p, q in [('matched', [.5, .5], [.5, .5]), ('disjoint', [1., 0.], [0., 1.]),
('missing_mode', [.5, 0., 0., .5], [1., 0., 0., 0.])]:
value, js = finite_game(p, q)
cases[name] = dict(discriminator=optimal_discriminator(p, q).tolist(), value=value, js=js)
return dict(generator=g.tolist(), discriminator=d.tolist(), target_mean=.5, target_variance=.48,
final_mean=float(g[1]), final_variance=float(g[0]**2/3),
checkpoints=history, finite_cases=cases, quadrature_order=32)
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, allow_nan=False))
One half is not a certificate
The default run moves from generator (a,b)=(0.4,−0.4) toward (1.2,0.5), reaching mean about 0.5 and variance about 0.48. These moments, the recovered affine distribution and the discriminator near zero logit agree in this synthetic example. The finite-support checks give value −1.386294 for matching distributions and zero for disjoint ones. None of these results is an image benchmark.
Set all D parameters to zero before training. It outputs 0.5 for every input even though the initial generator distribution is wrong. Its input derivative is zero, so G receives no gradient on that update. D itself still has a nonzero improvement direction. This is why a classifier score, a balanced accuracy or a generator loss alone cannot certify distribution equality.
Finite networks constrain both distributions and discriminators. Alternating optimization changes the signal being followed; a stationary point need not be the desired game equilibrium. Mode collapse can produce plausible samples while omitting parts of the distribution. Compare sample quality, diversity and held-out behavior, keeping training conditions fixed. The GAN training article studies rotation and coverage separately; WGAN changes the distributional objective and critic constraints. Neither name replaces the need to measure what the model generates.
Check the interpretation
- At one location p=0.75 and q=0.25. What is D*, and why is it not one?
Answer: It is 0.75. Generated samples can also occur at this location, so a balanced real/fake classification problem does not assign certainty to the real class.
- Calculate the optimized value for matching and disjoint distributions.
Answer: Matching gives JS=0 and value −log4≈−1.386294. Disjoint gives JS=log2 and value zero. The formulas concern optimized D and the minimax value, not an arbitrary reported generator loss.
- Why does freezing D’s weights not mean detaching its output during a G update?
Answer: G needs the derivative of D with respect to G’s generated input. Detaching the output removes this path. Freezing only D’s parameters preserves the input derivative while preventing a D parameter update.
- A constant generator returns 0.5. Which target statistic does it match, and which does it miss in this example?
Answer: It matches the mean 0.5 but has variance zero, versus the target’s 0.48. Mean agreement alone therefore does not identify the desired distribution.
Reading the papers as separate claims
The original 2014 paper is most useful when read as three separate arguments: Section 3 defines the learning procedure, Section 4.1 identifies an ideal optimum, and Section 4.2 lists conditions for a convergence argument. The 2018 convergence paper examines what can fail outside such conditions. Read its Dirac-GAN example before treating an equilibrium theorem as a prediction about a finite training trace. Our quadrature example illustrates one successful restricted run; it does not establish the missing general guarantee.
Make a prediction, then check
An untrained D outputs .5 everywhere. Has G learned the data distribution?
Learning objectives
- Define the two-player objective.
- Derive optimal D and the JS relation.
- Differentiate through a continuous generator.
- Separate ideal theory from finite training.
Prerequisites & connections
Explore related knowledge →References
- Generative Adversarial Nets (v1): game, optimal discriminator and limits
Ian J. Goodfellow; Jean Pouget-Abadie; Mehdi Mirza; Bing Xu; David Warde-Farley; Sherjil Ozair; Aaron Courville; Yoshua Bengio · 2014 - Which Training Methods for GANs do actually Converge?
Lars Mescheder; Andreas Geiger; Sebastian Nowozin · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked original GAN v1 objective, ideal discriminator/JS and conditional convergence, alongside selected Mescheder2018 limits. Seven paired equations, four exercises, finite-distribution checks and an original five-parameter continuous GAN. All player gradients checked; quadrature is approximate, not image training.
- Checked finite-support optimal D/JS with zeros, all3 D and2 G gradients for fixed other player,32/64-point quadrature agreement at tested parameters,2000 rounds and mean/variance. Constant untrained D=.5 is explicitly not proof of distribution equality.
- Four computed SVGs bind each actual bilingual program. Group passed16 numerical/geometry checks and24 isolated responsive cases at390/768/1536 with four fallback fonts. Eight final representative screenshots actually viewed. Added VQ numeric labels and equal-unit phase axes with preserved originals; data unchanged. Full article-page acceptance is separate, not independent human review.
Source locations checked:
- Generative Adversarial Nets (v1): game, optimal discriminator and limits · Read Section3 objective/non-saturating training,4.1 optimal D/JS,4.2 conditional convergence and Section6 opening on collapse; inspected PDF page5. Same cached v1 as011o, with expanded reading. No benchmark replication.
- Which Training Methods for GANs do actually Converge? · Read selected Section2.2 Dirac-GAN/rotation and Section3.3 zero-centered penalties; inspected PDF page6 Equations7–8 and small-step qualification. ICML2018, PMLR80:3481–3490. No supplement, full general proof or experiment replication.
Related topics