v9.1.1
Menu

GAN Discriminator Loss

hardPROGenerative ModelsMachine Learning 2

Compute the discriminator loss for a Generative Adversarial Network.

The discriminator tries to maximize: LD=−1m∑i=1m[log⁡D(xi)+log⁡(1−D(G(zi)))]L_D = -\frac{1}{m}\sum_{i=1}^{m}[\log D(x_i) + \log(1 - D(G(z_i)))]

Given the discriminator's output for real data D(x)D(x) and for fake data D(G(z))D(G(z)) (both are probabilities in (0,1)(0, 1)), compute the discriminator loss.

Clip probabilities to [ϵ,1−ϵ][\epsilon, 1-\epsilon] where ϵ=10−7\epsilon = 10^{-7} to avoid log(0).

Return the loss rounded to 4 decimal places. Note: the loss is a positive number (we negate the objective).

Example

Input
d_real = [0.9, 0.8]
d_fake = [0.1, 0.2]
Output
0.3285
Reasoning
  • Inputs: d_real holds the discriminator's probability that each real sample is real, and d_fake its probability that each generated sample is real. Here m=2m = 2 and pairs line up by index: (0.9,0.1)(0.9, 0.1) and (0.8,0.2)(0.8, 0.2).
  • Clipping: every value already lies well inside [10−7,1−10−7][10^{-7}, 1 - 10^{-7}], so nothing changes. Clipping only matters for outputs of exactly 00 or 11, where the log would be −∞-\infty.
  • Pair 1: ln⁡0.9+ln⁡(1−0.1)=2ln⁡0.9≈2(−0.10536)=−0.21072\ln 0.9 + \ln(1 - 0.1) = 2\ln 0.9 \approx 2(-0.10536) = -0.21072.
  • Pair 2: ln⁡0.8+ln⁡(1−0.2)=2ln⁡0.8≈2(−0.22314)=−0.44629\ln 0.8 + \ln(1 - 0.2) = 2\ln 0.8 \approx 2(-0.22314) = -0.44629.
  • Average and negate: the pair total is −0.65701-0.65701; dividing by m=2m = 2 gives −0.32850-0.32850, and the minus sign in LDL_D turns it into 0.3285 (rounded to 4 decimal places).
  • Notice: a confident, correct discriminator drives every log toward 00, so the loss falls toward 00. A discriminator that outputs 0.50.5 everywhere scores 2ln⁡2≈1.38632\ln 2 \approx 1.3863, the value of pure guessing.

Constraints

  • d_real: list of discriminator outputs for real data (probabilities)
  • d_fake: list of discriminator outputs for fake data (probabilities)
  • Clip to [1e-7, 1-1e-7] before taking log
  • Return the discriminator loss (positive) rounded to 4 decimal places

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.