Skip to content
E
Educatum

Entropy

Curated by Educatum AI teamLast updated:
Model EvaluationLoss
Direct Answer

Shannon entropy measures the average uncertainty or expected surprise (information content) of a random variable's probability distribution. Zero entropy corresponds to a deterministic outcome, whereas entropy reaches its maximum under a uniform distribution; in machine learning it underpins decision tree information gain and cross-entropy loss.

Study Card: Entropy

Direct Answer

Shannon entropy measures the average uncertainty, randomness, or expected information content required to encode draws from a probability distribution. For a discrete random variable XX taking values {x1,…,xn}\{x_1, \dots, x_n\} with probability mass function P(xi)P(x_i), entropy is defined as:

H(X)=−∑i=1nP(xi)log⁡bP(xi)H(X) = -\sum_{i=1}^{n} P(x_i) \log_b P(x_i)

with the standard convention 0log⁡b0=00 \log_b 0 = 0. Using base b=2b = 2 measures entropy in bits (common in information theory and decision trees), while using the natural logarithm (ln⁡\ln) measures entropy in nats (standard in deep learning cross-entropy loss). Discrete entropy satisfies 0≤H(X)≤log⁡bn0 \le H(X) \le \log_b n: it equals 00 when the outcome is completely certain (P(xk)=1P(x_k) = 1) and attains its maximum log⁡bn\log_b n when all nn outcomes are equally likely.

Key Terms

  • Uncertainty: The unpredictability of a random variable’s outcome prior to observation.
  • Self-Information (Surprisal): −log⁡bP(xi)-\log_b P(x_i), the information gained upon observing an event of probability P(xi)P(x_i); entropy is its expected value.
  • Bits vs. Nats: Units of entropy determined by logarithm base (log⁡2\log_2 yields bits; ln⁡\ln yields nats, where 1 nat≈1.443 bits1\text{ nat} \approx 1.443\text{ bits}).
  • Node Impurity: In decision trees (ID3/C4.5), high entropy means mixed class labels at a node, while zero entropy means a pure single-class leaf.

Example

Consider two bags of marbles: Bag A holds 5 red and 5 blue marbles (P=[0.5,0.5]P = [0.5, 0.5]), while Bag B holds 9 red and 1 blue marble (P=[0.9,0.1]P = [0.9, 0.1]).

For Bag A (maximum binary uncertainty):

H(A)=−(510log⁡2510+510log⁡2510)=−(0.5(−1)+0.5(−1))=1.00 bitH(A) = -\left(\frac{5}{10}\log_2\frac{5}{10} + \frac{5}{10}\log_2\frac{5}{10}\right) = -\big(0.5(-1) + 0.5(-1)\big) = 1.00\text{ bit}

For Bag B (more predictable):

H(B)=−(910log⁡2910+110log⁡2110)≈−(0.9(−0.1520)+0.1(−3.3219))≈0.47 bitsH(B) = -\left(\frac{9}{10}\log_2\frac{9}{10} + \frac{1}{10}\log_2\frac{1}{10}\right) \approx -\big(0.9(-0.1520) + 0.1(-3.3219)\big) \approx 0.47\text{ bits}

Code Implementation

import numpy as np
import matplotlib.pyplot as plt

def calculate_entropy(probabilities):
    """Calculate Shannon entropy (in bits) of a discrete probability distribution."""
    probs = np.asarray(probabilities, dtype=float)
    probs = probs[probs > 0]  # Apply convention 0 * log2(0) = 0
    return float(-np.sum(probs * np.log2(probs)))

# Example distributions
entropy_fair_coin = calculate_entropy([0.5, 0.5])
entropy_biased_coin = calculate_entropy([0.9, 0.1])
entropy_deterministic = calculate_entropy([1.0, 0.0])

print(f"Entropy of a fair coin:          {entropy_fair_coin:.4f} bits")
print(f"Entropy of a biased coin (0.9):  {entropy_biased_coin:.4f} bits")
print(f"Entropy of a deterministic coin: {entropy_deterministic:.4f} bits")

# Binary entropy curve H(p) over [0, 1]
p_values = np.linspace(0.0, 1.0, 101)
entropies = [calculate_entropy([p, 1.0 - p]) for p in p_values]

plt.figure(figsize=(8, 5))
plt.plot(p_values, entropies, linewidth=2)
plt.title('Binary Entropy Function H(p)')
plt.xlabel('Probability of positive outcome (p)')
plt.ylabel('Entropy (bits)')
plt.grid(True)
plt.show()
  • Cross-Entropy: H(P,Q)=−∑iP(xi)log⁡Q(xi)=H(P)+DKL(P∥Q)H(P, Q) = -\sum_i P(x_i)\log Q(x_i) = H(P) + D_{\text{KL}}(P \| Q), the primary classification loss function in neural networks and logistic regression.
  • KL Divergence: DKL(P∥Q)=∑iP(xi)log⁡P(xi)Q(xi)≥0D_{\text{KL}}(P \| Q) = \sum_i P(x_i)\log \frac{P(x_i)}{Q(x_i)} \ge 0, measuring extra encoding cost when using distribution QQ instead of true distribution PP.
  • Information Gain: Reduction in label entropy after splitting a dataset on feature AA: IG(Y,A)=H(Y)−H(Y∣A)\text{IG}(Y, A) = H(Y) - H(Y \mid A), used alongside Gini impurity to build decision trees.
  • Differential Entropy: The continuous analog −∫p(x)log⁡p(x) dx-\int p(x)\log p(x)\,dx, which unlike discrete entropy can take negative values (e.g., for tightly concentrated continuous distributions).
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.