labs / lab-c-kl-divergence
Next task →
Practical Labs/Lab: KL Divergence and Cross Entropy
Level 3 · information-theory

Lab: KL Divergence and Cross Entropy

Build a minimal, verifiable implementation that demonstrates KL Divergence and Cross Entropy. Connect the code to the governing equation, inspect its output numerically, and explain one failure case.

Mathematical basis

For KL Divergence and Cross Entropy, compute DKL(p∥q)=∑xp(x)log⁡(p(x)/q(x))≥0D_{\mathrm{KL}}(p\|q)=\sum_x p(x)\log(p(x)/q(x))\ge 0 and verify identity when p=qp=q.

Instructions

  1. 01Read section 7 of the KL Divergence and Cross Entropy learning page and write its governing equation on paper.
  2. 02Implement the core operation in NumPy on synthetic discrete distributions. Do not call a library function that solves the whole task.
  3. 03Verify the implementation on a hand-computed three-element or 3×3 example before scaling up.
  4. 04Run the experiment with the smoothing ε and record KL divergence in nats.
  5. 05Inspect the output, identify one discrepancy with the theory, and write a one-paragraph explanation.

Starter code

import numpy as np

def kl(p, q, eps=1e-12):
    p = np.maximum(np.asarray(p, float), eps); q = np.maximum(np.asarray(q, float), eps)
    p /= p.sum(); q /= q.sum()
    return float(np.sum(p * np.log(p / q)))

assert kl([.5,.5],[.5,.5]) < 1e-9
assert kl([.5,.5],[.9,.1]) > 0
print(round(kl([.5,.5],[.9,.1]), 4))