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 with distribution ,
with the convention . It is the expectation of the information content from Information Content and Surprise.
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 has entropy
It is 0 at and (no uncertainty), and peaks at 1 bit for . We will meet again as the capacity loss of the binary symmetric channel (The Binary Symmetric Channel).
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 still has almost half a bit of entropy, and even has 0.08 bits.
Entropy as a number of questions
For the dyadic distribution 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 , which is exactly . In general, entropy is the average number of well-chosen binary questions, up to less than one extra question (Optimal Code Lengths).
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:
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 bits, where 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 bits.
Exercises
Exercise 1: Four outcomes
Compute for .
Answer
About 1.846 bits.
Solution
.
Exercise 2: Uniform distribution
What is the entropy of a uniform distribution over outcomes?
Answer
bits.
Solution
Every term is , and there are 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
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 bit
- 0.5 bits
- 2 bits
- 0 bits
For which heads probability is the binary entropy largest?
- 0
- 0.25
- 0.5
- 1
The plug-in entropy estimate on a small sample tends to be…
- too low
- too high
- exactly right
- negative