Contents
Entropy, Cross-Entropy and KL DivergenceInformation Theory for Machine Learning
Surprise, average surprise, and the price of wrong expectations
A tutorial companion to the video Machine Learning Interview #8: Entropy, Cross-Entropy and KL Divergence PDF
01Introduction
1.1The question
“What are entropy, cross-entropy and KL divergence, and why does machine learning care?” Interviewers ask it because the answer connects theory to practice: the loss you minimize when you train a classifier or a language model is a cross-entropy, and the reason that loss works is a property of the KL divergence. The definitions look like three different formulas, but they are one idea used three ways. Think of a weather forecast. If you live where it almost never rains in summer, “sunny tomorrow” tells you nothing, and “rain tomorrow” is a shock. Information theory measures that shock, and everything else follows from it.
1.2Prerequisites and notation
Prerequisites. Basic probability (discrete distributions, expectation), logarithms, and maximum likelihood (the tutorial of episode 5). Episode 7 covers cross-entropy as a loss function, including its gradient p-y; here we explain where it comes from.
Notation. p is the true distribution of an outcome x and q is a model’s distribution, or someone’s expectations, over the same outcomes. We write \log_2 for the base-2 logarithm (results in bits) and \ln for the natural logarithm (results in nats); a plain \log means either, when the base does not matter. Sums run over all outcomes x with p(x)>0, and 0\log0 is taken to be 0.
1.3A short history
Shannon (1948) founded information theory to answer an engineering question: how many symbols does it take to send a message? He measured information by the logarithm of probabilities, defined the entropy of a source, and proved that no code can use fewer symbols on average. He called the base-2 unit the bit, a word he credits to J. W. Tukey. Kullback and Leibler (1951) defined the quantity now called the KL divergence as the mean information for telling two hypotheses apart. Huffman (1952) found the optimal code for known probabilities, still inside ZIP files and PNG images. Good (1952) proposed scoring probability forecasts by the logarithm of the probability given to what happened: the log loss. Shannon (1951) estimated the entropy of English at roughly one bit per letter by asking people to guess the next letter of a sentence, the task a language model is trained on today. Quinlan (1986) grew decision trees by choosing the split with the largest information gain. Neural networks are trained with cross-entropy (Goodfellow et al., 2016, §6.2), language models such as GPT-2 (Radford et al., 2019) minimize it on the next token, and variational autoencoders (Kingma and Welling, 2014) put a KL divergence directly in their loss.