v9.1.1
Menu

KL Divergence

mediumPROGenerative ModelsMachine Learning 2

Compute the Kullback-Leibler divergence between two discrete probability distributions.

DKL(P∥Q)=∑iP(i)ln⁡P(i)Q(i)D_{KL}(P \| Q) = \sum_{i} P(i) \ln\frac{P(i)}{Q(i)}

where PP and QQ are probability distributions over the same set of events.

By convention, if P(i)=0P(i) = 0, the term contributes 0 to the sum (since 0ln⁡0=00 \ln 0 = 0). If P(i)>0P(i) > 0 but Q(i)=0Q(i) = 0, the divergence is infinity.

Return the KL divergence rounded to 4 decimal places. Return float('inf') if undefined.

Example

Input
p = [0.4, 0.6]
q = [0.5, 0.5]
Output
0.0201
Reasoning
  • p and q are two probability distributions over the same two events: P=(0.4,0.6)P = (0.4, 0.6) is the "true" distribution and Q=(0.5,0.5)Q = (0.5, 0.5) is the uniform approximation being compared against it.
  • Each event contributes P(i)ln⁡P(i)Q(i)P(i)\ln\frac{P(i)}{Q(i)}, weighted by how likely it is under PP.
  • Event 1: the ratio is 0.40.5=0.8\frac{0.4}{0.5} = 0.8, and 0.4ln⁡0.8=0.4×(−0.22314)≈−0.089260.4 \ln 0.8 = 0.4 \times (-0.22314) \approx -0.08926. It is negative because QQ puts more mass here than PP does.
  • Event 2: the ratio is 0.60.5=1.2\frac{0.6}{0.5} = 1.2, and 0.6ln⁡1.2=0.6×0.18232≈0.109390.6 \ln 1.2 = 0.6 \times 0.18232 \approx 0.10939.
  • Summing: −0.08926+0.10939=0.02013-0.08926 + 0.10939 = 0.02013, which rounded to 4 decimal places is 0.0201.
  • Notice the total is small but positive: individual terms can be negative, yet the sum is never below 0, and it is exactly 0 only when P=QP = Q. It is also not symmetric: swapping the roles of PP and QQ gives 0.02040.0204, not 0.02010.0201.

Constraints

  • p, q: lists of probabilities (same length, sum to 1)
  • Use natural log
  • Return float rounded to 4 decimal places
  • Return float('inf') if P(i) > 0 and Q(i) = 0

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.