Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Entropy, divergence and mutual information

ProblemMeasure how much information a source produces, how far one distribution is from another, and how much one variable reveals about another
Devised byClaude Shannon (1948), entropy and mutual information; Solomon Kullback and Richard Leibler (1951), the divergence; Frank Gray (1947, patented 1953), the reflected binary code
AccuracyExact sums; the library agrees with SciPy’s stats.entropy to the 12 digits shown (table below)
Cost for bytes or probabilities; for an joint table
Read firstPreliminaries: probability
APIentropy, entropy_from_probabilities, cross_entropy, kl_divergence, mutual_information, gray_code, gray_decode, gray_code_sequence

Overview

How much information does a message carry? Shannon’s answer is the entropy: the average number of bits needed to describe the outcome of a random source, if the description is as efficient as possible. It sets the limit for lossless compression, which the next entries approach. The cross entropy and the Kullback-Leibler divergence measure the cost of coding with the wrong distribution, and the mutual information measures how much one variable tells about another. Mutual information sets the capacity of a noisy channel, which the error-correcting codes of the next chapter approach. This entry also covers Gray codes, which order binary numbers so that neighbours differ in one bit.

Where it is used

Entropy, divergence and mutual information are the vocabulary of information theory and data science.

  • Compression and communication limits. Entropy is the least number of bits per symbol a lossless code can achieve; capacity of a channel is a mutual information.
  • Machine learning. Cross-entropy is the loss function of classifiers; KL divergence measures how far a model is from the data; mutual information selects features.
  • Statistics and physics. Maximum-entropy methods, and the thermodynamic entropy of a system, share the same formula.
  • Genomics and linguistics. Measuring the information in DNA sequences and text.

History

Claude Shannon’s “A mathematical theory of communication” (1948) founded information theory. It defined entropy, showed that it is the limit of lossless compression (the source coding theorem), defined mutual information and channel capacity, and showed that reliable communication is possible at any rate below capacity (the channel coding theorem). Ralph Hartley (1928) had measured information by the logarithm of the number of possible messages, and the name “entropy” came at John von Neumann’s suggestion, from statistical mechanics. Solomon Kullback and Richard Leibler (1951) introduced the divergence for statistical discrimination. Frank Gray at Bell Labs filed his patent on the reflected binary code in 1947, for pulse-code modulation. The same code is the solution of the Chinese rings puzzle, known for centuries.

The idea

Entropy

A source emitting symbol with probability has entropy

with the convention .

The formula is an average, and the quantity being averaged has a meaning of its own. Learning that an event of probability has occurred conveys bits of information, its surprise. The definition is forced by two reasonable requirements: a rarer event should be more informative, and the information from two independent events should add (their probabilities multiply, and the logarithm turns the product into a sum). An event of probability conveys 1 bit, the answer to one yes-or-no question; one of probability conveys 3 bits; a certain event conveys nothing. The entropy is the average surprise of the source’s symbols.

It ranges from 0, for a source whose outcome is certain, to , for equally likely outcomes, which is the most unpredictable a source with symbols can be. A fair coin has 1 bit and a byte of random data 8. A biased coin that lands heads 90% of the time has only bits: its outcomes are mostly predictable. entropy computes it for the empirical distribution of the bytes of a slice; entropy_from_probabilities for a given distribution.

Figure 18.1. Binary entropy.

Entropy is not just a measure of uncertainty; it is the answer to a practical question. Shannon’s source coding theorem says that no lossless code can use fewer than bits per symbol on average, and that codes exist using fewer than (coding single symbols) or (coding long blocks). Entropy is the limit of lossless compression, and the entropy coders approach it.

There is a caveat about what “the source” is. The byte entropy only describes symbols taken one at a time. Real data has structure between symbols, and the entropy of blocks, per symbol, falls as the blocks lengthen:

Table 18.1. Order-0 entropy of different sources.

sourceentropy (bits per byte)
1 000 000 uniformly random bytes7.9998
the text, one byte at a time4.6211
the text, pairs of bytes, per byte3.9808
the text, triples of bytes, per byte3.4962
the text: next byte given the previous two, 2.5271

The entropy rate of English is thought to be about 1–1.5 bits per character. Dictionary coders exploit this structure; order-0 entropy coders cannot.

Cross entropy and divergence

An ideal code gives a symbol of probability a codeword of bits. Suppose the code was designed for a distribution , but the symbols actually occur with distribution . The average cost per symbol is then the cross entropy

where the Kullback-Leibler divergence is the extra cost. It is never negative, it is zero only when (Gibbs’ inequality), and it is not symmetric. The cross entropy is infinite if gives zero probability to a symbol that occurs. In machine learning, minimising cross entropy is the same as maximising likelihood.

Table 18.2. Entropy and divergences against SciPy.

quantity (bits)librarySciPy stats.entropy
bytes of the King James Bible (4.6 MB)4.6211314318724.621131431872
, , uniform0.1535606553290.153560655329
0.1756874697070.175687469707

Mutual information

For a pair of variables with joint distribution ,

where is the uncertainty about that remains, on average, once is known. The mutual information is therefore the reduction in uncertainty about from knowing : the number of bits that one variable tells us about the other. It is symmetric in the two. It is also the divergence of the joint distribution from the product of its marginals, so it is zero exactly when the variables are independent. mutual_information takes the joint distribution as a row-major table. A binary symmetric channel, which flips each bit with probability , carries bits per use for a uniform input. That is its capacity:

Figure 18.2. BSC mutual information.

Gray codes

In ordinary binary, 3 → 4 changes three bits (011 → 100). A sensor reading the bits of a rotating disc at the moment of that change can briefly report anything from 000 to 111. The reflected binary code changes exactly one bit between consecutive values, so a misread is off by at most one step. The 3-bit Gray code: 0 → 000, 1 → 001, 2 → 011, 3 → 010, 4 → 110, 5 → 111, 6 → 101, 7 → 100. Decoding XORs together all the right shifts of , which gray_decode does in six doubling steps. Gray codes also label constellation points so that the likeliest symbol error flips a single bit.

Algorithm

Entropy of a byte sequence.

  1. Count the occurrences of each of the 256 byte values.
  2. For each value that occurs, with count out of bytes, add to the total. Values that do not occur contribute nothing.

Entropy of a distribution: the same sum over the given probabilities, skipping zeros.

Cross entropy and divergence of from : sum over the symbols with ; the result is infinite if any of those has . The divergence is the cross entropy minus the entropy of .

Mutual information, from a joint distribution given as a table.

  1. Sum each row to get the marginal distribution of the first variable, and each column to get for the second.
  2. Sum over the cells with .

Gray code. Encode: . Decode: start with and apply , then with shifts of 2, 4, 8, 16 and 32. Each step doubles the number of leading bits that are correct, so six steps suffice for 64 bits.

All of these cost one pass over the data or the table.

Implementation

    let mut counts = [0u64; 256];
    for &b in data {
        counts[b as usize] += 1;
    }
    let n = data.len() as f64;
    counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| {
            let p = c as f64 / n;
            // Written as p log2(1/p), which is +0 (not -0) for p = 1.
            p * (1.0 / p).log2()
        })
        .sum()
pub fn gray_code(n: u64) -> u64 {
    n ^ (n >> 1)
}

/// Inverts [`gray_code`]: returns the `n` whose Gray code is `g`.
pub fn gray_decode(g: u64) -> u64 {
    let mut n = g;
    let mut shift = 1;
    while shift < 64 {
        n ^= n >> shift;
        shift <<= 1;
    }
    n
}
  • All measures are in bits (base-2 logarithms).
  • The distribution functions return NaN for negative or non-finite entries and for mismatched lengths, and do not check that probabilities sum to one.

In practice

//! Entropy, divergence, mutual information and Gray codes.

use lib_jsl_information::operators::{cross_entropy, entropy, entropy_from_probabilities, kl_divergence, mutual_information};
use lib_jsl_information::source_coders::gray_codes::{gray_code, gray_decode};

fn main() {
    println!("entropy of \"aaaa\": {} bits per byte", entropy(b"aaaa"));
    println!("entropy of \"abab\": {} bits per byte", entropy(b"abab"));
    println!("entropy of \"abcd\": {} bits per byte", entropy(b"abcd"));
    println!("entropy of a fair die: {:.4} bits (log2 6 = {:.4})", entropy_from_probabilities(&[1.0 / 6.0; 6]), 6f64.log2());
    let p = [0.5, 0.25, 0.25];
    let q = [1.0 / 3.0; 3];
    println!("H(p) = {}, cross entropy H(p, q) = {:.4}, D(p||q) = {:.4}", entropy_from_probabilities(&p), cross_entropy(&p, &q), kl_divergence(&p, &q));
    // A binary symmetric channel with crossover 0.1 and a uniform input.
    let e = 0.1;
    let joint = [0.5 * (1.0 - e), 0.5 * e, 0.5 * e, 0.5 * (1.0 - e)];
    println!("I(X; Y) = {:.4} bits = 1 - H(0.1) = {:.4}", mutual_information(&joint, 2, 2), 1.0 - entropy_from_probabilities(&[e, 1.0 - e]));
    let codes: Vec<String> = (0..8).map(|n| format!("{:03b}", gray_code(n))).collect();
    println!("3-bit Gray code: {}", codes.join(" "));
    println!("gray_decode(0b110) = {}", gray_decode(0b110));
}
entropy of "aaaa": 0 bits per byte
entropy of "abab": 1 bits per byte
entropy of "abcd": 2 bits per byte
entropy of a fair die: 2.5850 bits (log2 6 = 2.5850)
H(p) = 1.5, cross entropy H(p, q) = 1.5850, D(p||q) = 0.0850
I(X; Y) = 0.5310 bits = 1 - H(0.1) = 0.5310
3-bit Gray code: 000 001 011 010 110 111 101 100
gray_decode(0b110) = 4

Strengths

  • Exact, simple and fast; the measures that bound compression and communication.

Weaknesses

  • Byte entropy is order-0: it ignores all dependence between symbols, so it is not a compression limit for real data.
  • Plug-in estimates from samples are biased low when the alphabet is large compared with the sample.

Exercises

  1. Show that for outcomes, with equality only for the uniform distribution.
  2. Prove Gibbs’ inequality from .
  3. Show that , and that it is symmetric.
  4. Compute the capacity of the binary erasure channel, which loses each bit with probability .
  5. Prove that consecutive Gray codes differ in exactly one bit, and that gray_decode inverts gray_code.
Hints and answers
  1. By Jensen’s inequality (or Gibbs with uniform), with equality iff uniform.
  2. using .
  3. , which is symmetric in and .
  4. The BEC has capacity : a bit gets through with probability and the receiver knows which ones were lost.
  5. . Consecutive and differ in exactly one bit (the bit that flips depends on the lowest set bit of ). The decoder inverts it.

Further reading

  • C. E. Shannon, “A mathematical theory of communication”, Bell System Technical Journal 27 (1948) 379–423 and 623–656.
  • T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed., Wiley, 2006, chapters 2 and 5.
  • S. Kullback and R. A. Leibler, “On information and sufficiency”, Annals of Mathematical Statistics 22 (1951) 79–86.
  • F. Gray, “Pulse code communication”, US patent 2 632 058, 1953.