πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Entropy

Information TheoryEntropy🟒 Free Lesson

Advertisement

Entropy


Historical Context


Core Definitions


Key Formulas


Properties and Theorems


Worked Examples


Python Implementation

import numpy as np
from collections import Counter

def entropy(probs):
    """Compute Shannon entropy in bits from a probability distribution."""
    probs = np.array(probs)
    probs = probs[probs > 0]  # Avoid log(0)
    return -np.sum(probs * np.log2(probs))

def entropy_from_samples(samples):
    """Estimate entropy from a list of samples."""
    counter = Counter(samples)
    total = len(samples)
    probs = np.array([count / total for count in counter.values()])
    return entropy(probs)

def joint_entropy(joint_probs):
    """Compute joint entropy from a 2D joint probability matrix."""
    flat = joint_probs.flatten()
    return entropy(flat)

def conditional_entropy(joint_probs):
    """Compute H(Y|X) from a joint probability matrix."""
    h_y_given_x = 0.0
    for i in range(joint_probs.shape[0]):
        p_x = joint_probs[i].sum()
        if p_x > 0:
            h_y_given_x += p_x * entropy(joint_probs[i] / p_x)
    return h_y_given_x

# --- Examples ---
# Fair coin
print(f"Fair coin: {entropy([0.5, 0.5]):.3f} bits")          # 1.000

# Biased coin
print(f"Biased (0.9,0.1): {entropy([0.9, 0.1]):.3f} bits")  # 0.469

# Fair die
print(f"Fair die: {entropy([1/6]*6):.3f} bits")              # 2.585

# Loaded die
loaded = [1/2, 1/4, 1/8, 1/16, 1/32, 1/32]
print(f"Loaded die: {entropy(loaded):.3f} bits")              # 1.938

# Joint entropy example
joint = np.array([[0.4, 0.1], [0.1, 0.4]])
print(f"Joint entropy: {joint_entropy(joint):.3f} bits")      # 1.722
print(f"Conditional H(Y|X): {conditional_entropy(joint):.3f}")  # 0.722

# Entropy from samples
np.random.seed(42)
samples = np.random.choice(['A', 'B', 'C', 'D'], size=10000, p=[0.5, 0.25, 0.125, 0.125])
print(f"Estimated entropy: {entropy_from_samples(samples):.3f}")  # ~1.75

Applications in AI/ML


Common Mistakes

MistakeWhy It's WrongCorrect Approach
Using without specifying baseUnits depend on baseUse for bits, for nats
Forgetting conventionCauses NaN errorsFilter zero probabilities before computing
Confusing entropy with informationEntropy is expected information, not instantaneousEntropy averages over all outcomes
Assuming entropy is always positive for continuous RVsDifferential entropy can be negativeDifferential entropy is not directly comparable
Treating conditional entropy as "entropy minus something"Use the chain rule:

Interview Questions

Q1: Why does a fair coin have maximum entropy? A: A fair coin has for both outcomes, which maximizes subject to . This is proven by Jensen's inequality or Lagrange multipliers.

Q2: Can entropy be negative? A: Discrete entropy always. Differential entropy can be negative (e.g., a very concentrated Gaussian with small variance).

Q3: What's the relationship between entropy and compression? A: Shannon's source coding theorem: you cannot compress below bits per symbol losslessly. Entropy is the theoretical minimum average code length.

Q4: How is entropy used in decision trees? A: Information gain measures how much a feature reduces uncertainty. The feature with highest IG is selected for splitting.

Q5: Why use instead of ? A: gives entropy in bits, which is intuitive for binary decisions. gives nats. The choice doesn't affect which distribution has higher entropy, only the units.


Practice Problems


Quick Reference

QuantityFormulaUnits
Shannon Entropybits
Joint Entropybits
Conditional Entropybits
Max Entropybits
Information Gainbits

Relationship to Other Quantities


Common Confusions


Cross-References

  • 082 - Mutual Information β€” β€” measures shared information between variables.
  • 083 - KL Divergence: β€” measures distribution mismatch.
  • 084 - Cross-Entropy β€” β€” used as loss in classification.
  • 085 - Applications β€” Information gain in decision trees, feature selection with MI, VAE loss functions.

Summary

Need Expert Mathematics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement