TExcelTAD
Home › Information Theory › Entropy

Entropy

The entropy of a random variable is its average surprise: the expected number of bits of information you receive when you learn its value. It is the single most important quantity in information theory, because it is also the limit of lossless compression.

Definition

For a discrete random variable XX with distribution PP,

H(X)=∑xP(x)log⁡21P(x)=−∑xP(x)log⁡2P(x)H(X) = \sum_x P(x)\log_2 \frac{1}{P(x)} = -\sum_x P(x)\log_2 P(x)

with the convention 0log⁡0=00 \log 0 = 0. It is the expectation of the information content h(x)=log⁡21P(x)h(x) = \log_2 \frac{1}{P(x)} from Information Content and Surprise.

python · try it yourself
import numpy as np

def H(p):
    p = np.asarray(p, float); p = p[p > 0]
    return float(-np.sum(p * np.log2(p))) + 0.0

for name, p in [("fair coin", [0.5, 0.5]), ("biased coin 0.9", [0.9, 0.1]),
                ("fair die", [1 / 6] * 6), ("dyadic", [0.5, 0.25, 0.125, 0.125]),
                ("certain", [1.0, 0.0])]:
    print(f"{name:16s} H = {H(p):.4f} bits")
fair coin        H = 1.0000 bits
biased coin 0.9  H = 0.4690 bits
fair die         H = 2.5850 bits
dyadic           H = 1.7500 bits
certain          H = 0.0000 bits

The binary entropy function

A coin with heads probability pp has entropy

H2(p)=−plog⁡2p−(1−p)log⁡2(1−p)H_2(p) = -p\log_2 p - (1 - p)\log_2 (1 - p)

It is 0 at p=0p = 0 and p=1p = 1 (no uncertainty), and peaks at 1 bit for p=12p = \frac{1}{2}. We will meet H2H_2 again as the capacity loss of the binary symmetric channel (The Binary Symmetric Channel).

python · try it yourself
import numpy as np

def H2(p):
    p = np.asarray(p, float)
    with np.errstate(divide="ignore", invalid="ignore"):
        h = -p * np.log2(p) - (1 - p) * np.log2(1 - p)
    return np.nan_to_num(h)

for p in [0.0, 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0]:
    bar = "#" * int(round(40 * float(H2(p))))
    print(f"p = {p:4.2f}  H2 = {float(H2(p)):.4f}  {bar}")
p = 0.00  H2 = 0.0000
p = 0.01  H2 = 0.0808  ###
p = 0.10  H2 = 0.4690  ###################
p = 0.25  H2 = 0.8113  ################################
p = 0.50  H2 = 1.0000  ########################################
p = 0.75  H2 = 0.8113  ################################
p = 0.90  H2 = 0.4690  ###################
p = 1.00  H2 = 0.0000

The curve is steep near the ends: a coin with p=0.1p = 0.1 still has almost half a bit of entropy, and even p=0.01p = 0.01 has 0.08 bits.

Entropy as a number of questions

For the dyadic distribution (12,14,18,18)(\frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \frac{1}{8}) on a, b, c, d, the best yes/no strategy is "is it a?", then "is it b?", then "is it c?". It needs 1 question half the time, 2 a quarter of the time and 3 otherwise, an average of 1.751.75, which is exactly H(X)H(X). In general, entropy is the average number of well-chosen binary questions, up to less than one extra question (Optimal Code Lengths).

python · try it yourself
import numpy as np

p = np.array([0.5, 0.25, 0.125, 0.125])
questions = np.array([1, 2, 3, 3])
print("average questions:", float(p @ questions))
print("entropy:", float(-np.sum(p * np.log2(p))))
average questions: 1.75
entropy: 1.75

Estimating entropy from data

The plug-in estimate counts symbol frequencies and applies the formula. It is biased low for small samples, because rare symbols are often missing:

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
p = np.ones(50) / 50                       # uniform over 50 symbols: H = log2 50
true_H = np.log2(50)
for n in [20, 100, 1000, 100_000]:
    x = rng.choice(50, size=n, p=p)
    q = np.bincount(x, minlength=50) / n
    q = q[q > 0]
    print(f"n = {n:6d}: plug-in H = {-np.sum(q * np.log2(q)):.4f}   (true {true_H:.4f})")
n =     20: plug-in H = 3.9219   (true 5.6439)
n =    100: plug-in H = 5.2994   (true 5.6439)
n =   1000: plug-in H = 5.5913   (true 5.6439)
n = 100000: plug-in H = 5.6434   (true 5.6439)

The Miller-Madow correction adds k−12nln⁡2\frac{k - 1}{2n \ln 2} bits, where kk is the number of observed symbols, to reduce this bias.

In software

  • scipy.stats.entropy(counts, base=2) normalizes counts and returns the plug-in entropy.
  • Decision trees compute entropy of class labels at every split (Information Gain and Decision Trees).
  • Password-strength meters estimate entropy: a random 12-character password from 62 symbols has 12log⁡262≈71.512\log_2 62 \approx 71.5 bits.

Exercises

Exercise 1: Four outcomes

Compute H(X)H(X) for P=(0.4,0.3,0.2,0.1)P = (0.4, 0.3, 0.2, 0.1).

Answer

About 1.846 bits.

Solution

0.4log⁡22.5+0.3log⁡23.333+0.2log⁡25+0.1log⁡210=0.529+0.521+0.464+0.332=1.8460.4\log_2 2.5 + 0.3\log_2 3.333 + 0.2\log_2 5 + 0.1\log_2 10 = 0.529 + 0.521 + 0.464 + 0.332 = 1.846.

Exercise 2: Uniform distribution

What is the entropy of a uniform distribution over NN outcomes?

Answer

log⁡2N\log_2 N bits.

Solution

Every term is 1Nlog⁡2N\frac{1}{N}\log_2 N, and there are NN of them.

Exercise 3: Entropy of English letters (code)

With the approximate English letter frequencies below (for the 8 most common letters plus "other"), compute the entropy of this simplified distribution.

Answer

About 2.827 bits.

Solution
python · try it yourself
import numpy as np

p = np.array([0.127, 0.091, 0.082, 0.075, 0.070, 0.067, 0.063, 0.061])
p = np.append(p, 1 - p.sum())            # "other"
print(round(float(-np.sum(p * np.log2(p))), 3))
2.827

The full 26-letter distribution has about 4.2 bits; grouping letters into "other" hides some of the uncertainty.

Test yourself

The entropy of a fair coin is…

  1. 1 bit
  2. 0.5 bits
  3. 2 bits
  4. 0 bits

For which heads probability is the binary entropy largest?

  1. 0
  2. 0.25
  3. 0.5
  4. 1

The plug-in entropy estimate on a small sample tends to be…

  1. too low
  2. too high
  3. exactly right
  4. negative