1.3.19Probability & Statistics

Cross-entropy concept

2,164 words10 min readdifficulty · medium

Overview

Cross-entropy measures the difference between two probability distributions by quantifying how many bits (on average) we need to encode samples from one distribution if we wrongly assume another distribution. It's the workhorse loss function for classification in machine learning because it directly penalizes confident wrong predictions.

Why it matters: Cross-entropy bridges information theory and machine learning. It tells us "how surprised" we are when reality doesn't match our model's beliefs.


[!intuition] The Core Idea

Imagine you're a weather forecaster. Every day you predict rain probability, and nature reveals the truth.

  • If you say 90% rain and it rains → small surprise (you were confident and correct)
  • If you say 10% rain and it rains → huge surprise (you were confident and wrong)

Cross-entropy is the average surprise your predictions cause, weighted by what actually happens. The better your predictions match reality, the lower the cross-entropy.

Key insight: Cross-entropy = "How many extra bits am I wasting by using the wrong probability distribution?"


[!definition] Mathematical Definition

Given:

  • p(x)p(x) = true probability distribution (reality, ground truth)
  • q(x)q(x) = predicted probability distribution (model's belief)

The cross-entropy from pp to qq is:

H(p,q)=xp(x)logq(x)H(p, q) = -\sum_{x} p(x) \log q(x)

For continuous distributions:

H(p,q)=p(x)logq(x)dxH(p, q) = -\int p(x) \log q(x) \, dx

Units: bits (if log=log2\log = \log_2) or nats (if log=ln\log = \ln). In ML we use natural log.


[!formula] Derivation from First Principles

Step 1: Shannon Entropy (Self-Information)

Question: How surprised am I when event xx with probability p(x)p(x) occurs?

Answer: The surprise (self-information) is:

I(x)=logp(x)I(x) = -\log p(x)

Why this formula?

  • Rare events (p(x)p(x) small) → large surprise
  • Certain events (p(x)=1p(x) = 1) → zero surprise
  • Independent events should have additive surprise: I(x,y)=I(x)+I(y)I(x, y) = I(x) + I(y), which means we need log\log

Expected surprise when sampling from p(x)p(x):

H(p)=xp(x)logp(x)H(p) = -\sum_{x} p(x) \log p(x)

This is the Shannon entropy of pp — the minimum average bits needed to encode samples from pp if we know pp perfectly.


Step 2: What If We Use the Wrong Code?

Suppose reality follows p(x)p(x) but we design our encoding assuming distribution q(x)q(x).

  • We assign code length logq(x)-\log q(x) to event xx (optimal for qq)
  • But events occur with frequency p(x)p(x)
  • Average code length = xp(x)logq(x)-\sum_{x} p(x) \log q(x)

This is cross-entropy H(p,q)H(p, q) — the average bits we actually use with the wrong distribution.

Why this step? Cross-entropy tells us the cost of being wrong. If q=pq = p, we use the minimum possible bits. Any deviation from pp wastes bits.


Step 3: Connection to KL Divergence

The extra bits wasted by using qq instead of pp:

DKL(pq)=H(p,q)H(p)=xp(x)logq(x)p(x)D_{KL}(p \parallel q) = H(p, q) - H(p) = -\sum_{x} p(x) \log \frac{q(x)}{p(x)}

This is the Kullback-Leibler divergence.

Key relationship:

H(p,q)=H(p)+DKL(pq)H(p, q) = H(p) + D_{KL}(p \parallel q)

  • H(p)H(p) = irreducible uncertainty (entropy of truth)
  • DKL(pq)D_{KL}(p \parallel q) = extra cost from model mismatch

Why minimize cross-entropy in ML? Since H(p)H(p) is fixed (we can't change reality), minimizing H(p,q)H(p, q) is equivalent to minimizing DKL(pq)D_{KL}(p \parallel q) — making our model match reality.


[!example] Example 1: Binary Classification (Coin Flip)

Setup: True distribution: coin lands heads with p=0.7p = 0.7. Model predicts q=0.8q = 0.8.

Truth: p(heads)=0.7p(\text{heads}) = 0.7, p(tails)=0.3p(\text{tails}) = 0.3

Model: q(heads)=0.8q(\text{heads}) = 0.8, q(tails)=0.2q(\text{tails}) = 0.2

Cross-entropy:

H(p,q)=[0.7log(0.8)+0.3log(0.2)]H(p, q) = -[0.7 \log(0.8) + 0.3 \log(0.2)]

Why this step? We weight each outcome by its true probability pp, not the model's belief qq. Reality determines how often each surprise occurs.

H(p,q)=[0.7×(0.223)+0.3×(1.609)]H(p, q) = -[0.7 \times (-0.223) + 0.3 \times (-1.609)] =[0.1560.483]=0.639 nats= -[-0.156 - 0.483] = 0.639 \text{ nats}

Compare to entropy of truth:

H(p)=[0.7log(0.7)+0.3log(0.3)]=0.611 natsH(p) = -[0.7 \log(0.7) + 0.3 \log(0.3)] = 0.611 \text{ nats}

Wasted bits: DKL=0.6390.611=0.028D_{KL} = 0.639 - 0.611 = 0.028 nats.

Interpretation: Our model is slightly overconfident in heads, causing small information loss.


[!example] Example 2: Multiclass Classification (3 classes)

Setup: Image classification — cat, dog, bird.

Truth (one-hot): p=[1,0,0]p = [1, 0, 0] (it's definitely a cat)

Model predicts: q=[0.7,0.2,0.1]q = [0.7, 0.2, 0.1]

Cross-entropy:

H(p,q)=[1×log(0.7)+0×log(0.2)+0×log(0.1)]H(p, q) = -[1 \times \log(0.7) + 0 \times \log(0.2) + 0 \times \log(0.1)]

Why zero out the other terms? Because p(dog)=p(bird)=0p(\text{dog}) = p(\text{bird}) = 0 — these classes don't occur in this sample. We only care about the probability assigned to what actually happened.

H(p,q)=log(0.7)=0.357 natsH(p, q) = -\log(0.7) = 0.357 \text{ nats}

What if model predicted q=[0.1,0.8,0.1]q = [0.1, 0.8, 0.1] (wrong class)?

H(p,q)=log(0.1)=2.303 natsH(p, q) = -\log(0.1) = 2.303 \text{ nats}

Why the huge jump? Cross-entropy heavily penalizes confident wrong predictions. Model was 80% sure it was a dog, but it was a cat — massive surprise.

Figure — Cross-entropy concept

[!example] Example 3: Why Not Mean Squared Error?

Question: Why use cross-entropy for classification instead of MSE?

Setup: Binary classification, true label y=1y = 1 (positive class).

Model outputs: y^=0.1\hat{y} = 0.1 (predicts negative).

MSE: LMSE=(10.1)2=0.81L_{MSE} = (1 - 0.1)^2 = 0.81

Cross-entropy: LCE=log(0.1)=2.303L_{CE} = -\log(0.1) = 2.303

Why this difference matters:

If model improves to y^=0.2\hat{y} = 0.2:

  • MSE: (10.2)2=0.64(1 - 0.2)^2 = 0.64 → decrease of 0.170.17
  • Cross-entropy: log(0.2)=1.609-\log(0.2) = 1.609 → decrease of 0.6940.694

Why cross-entropy is better: It gives stronger gradient signal when the model is confidently wrong. MSE gradient is linear in error; cross-entropy gradient is inversely proportional to the predicted probability, so wrong predictions get corrected faster.


[!mistake] Common Pitfalls

Mistake 1: "Cross-entropy is just negative log probability"

Why it feels right: In practice, we write loss = -log(p_correct_class), which looks like we're ignoring the sum.

Why it's incomplete: That's only true when the true distribution is one-hot (hard labels). The full definition sums over all outcomes weighted by p(x)p(x).

The fix:

  • One-hot ppH(p,q)=logq(ytrue)H(p,q) = -\log q(y_{\text{true}}) (all other terms vanish)
  • Soft labels ppH(p,q)=ipilogqiH(p,q) = -\sum_i p_i \log q_i (all terms matter)

When it matters: Label smoothing, knowledge distillation, multi-label classification.


Mistake 2: "Minimizing cross-entropy = minimizing entropy"

Why it feels right: Both have "entropy" in the name and use log-\log.

Why it's wrong:

  • H(p)H(p) = entropy of true distribution (fixed, doesn't depend on model)
  • H(p,q)H(p, q) = cross-entropy (depends on model's qq)

The fix: You minimize H(p,q)H(p, q) by adjusting qq to match pp. Since H(p,q)=H(p)+DKL(pq)H(p, q) = H(p) + D_{KL}(p \parallel q) and H(p)H(p) is constant, you're really minimizing DKL(pq)D_{KL}(p \parallel q).


Mistake 3: "Cross-entropy is symmetric"

Why it feels right: Both pp and qq appear in the formula.

Why it's wrong: H(p,q)H(q,p)H(p, q) \neq H(q, p) in general.

Proof: H(p,q)=p(x)logq(x)H(p, q) = -\sum p(x) \log q(x) H(q,p)=q(x)logp(x)H(q, p) = -\sum q(x) \log p(x)

Different weights, different sums.

The fix: Cross-entropy measures "surprise when reality is pp but we assume qq". Swapping them asks a different question. Always keep pp as ground truth, qq as model.


[!recall]- Feynman Explanation (ELI12)

Imagine you're playing a guessing game. Every round, I secretly pick a colored ball from a bag (maybe 70% red, 30% blue). You have to guess the color before I show you.

Now, you get points based on how confident you were:

  • If you say "90% sure it's red" and it IS red → you get lots of points (you were right and confident!)
  • If you say "90% sure it's red" and it's BLUE → you lose TONS of points (you were wrong and super confident)

Cross-entropy is like keeping track of your average point loss over many rounds. If your guesses match the true bag contents (70% red), you lose very few points. If you always guess 50-50 when the bag is actually 70-30, you lose more points because you're surprised more often.

In machine learning, the model is you guessing, and reality is the bag. We train the model to minimize cross-entropy = minimize average surprise = make better guesses that match reality!


[!mnemonic] Memory Aid

CROSS = Compare Reality's Occurrence to System's Speculation

  • Compare: Two distributions
  • Reality: True p(x)p(x) (ground truth)
  • Occurrence: Weighted by true probabilities
  • System: Model's predicted q(x)q(x)
  • Surprise: logq(x)-\log q(x) (information content)

Formula mnemonic: "People Love Quality" → p(x)logq(x)p(x) \log q(x) summed with a negative sign.


Connections

  • Shannon Entropy — cross-entropy generalizes self-entropy when pqp \neq q
  • KL DivergenceH(p,q)=H(p)+DKL(pq)H(p,q) = H(p) + D_{KL}(p \parallel q)
  • Softmax Function — converts logits to probabilities qq for cross-entropy loss
  • Logistic Regression — binary cross-entropy is its loss function
  • Categorical Cross-Entropy — multiclass extension used in neural networks
  • Label Smoothing — regularization technique that modifies pp to prevent overconfidence
  • Maximum Likelihood Estimation — minimizing cross-entropy = maximizing likelihood
  • Mutual Information — related measure of shared information between variables

Flashcards

What does cross-entropy measure?
The average number of bits needed to encode samples from distribution pp using a code optimized for distribution qq; equivalently, the "surprise" when reality is pp but we assume qq.
Formula for cross-entropy H(p,q)H(p,q)?
H(p,q)=xp(x)logq(x)H(p, q) = -\sum_{x} p(x) \log q(x) (discrete) or p(x)logq(x)dx-\int p(x) \log q(x) dx (continuous).
Why use log-\log in cross-entropy?
Because surprise (self-information) is inversely related to probability: rare events are more surprising. Log ensures additive property for independent events.
Relationship between cross-entropy and KL divergence?
H(p,q)=H(p)+DKL(pq)H(p, q) = H(p) + D_{KL}(p \parallel q), where H(p)H(p) is entropy of true distribution and DKLD_{KL} is the extra bits wasted by using qq instead of pp.
Why minimize cross-entropy in classification?
Because H(p)H(p) (true distribution's entropy) is fixed, minimizing H(p,q)H(p,q) is equivalent to minimizing DKL(pq)D_{KL}(p \parallel q), making the model match reality.
Cross-entropy for one-hot true label yy and predicted probabilities qq?
H(p,q)=logqyH(p, q) = -\log q_y (only the predicted probability of the true class matters; other terms vanish because pi=0p_i = 0 for iyi \neq y).
Why is cross-entropy better than MSE for classification?
Cross-entropy has stronger gradients when confidently wrong (gradient 1/q\propto 1/q vs. MSE's linear gradient), leading to faster correction of mistakes.
Is cross-entropy symmetric?
No. H(p,q)H(q,p)H(p, q) \neq H(q, p) in general because they weight by different distributions (pp vs. qq). Always use pp = ground truth, qq = model.
What happens to cross-entropy as qq approaches pp?
H(p,q)H(p)H(p, q) \to H(p) (the entropy of the true distribution), and DKL(pq)0D_{KL}(p \parallel q) \to 0. This is the minimum achievable cross-entropy.
Why does cross-entropy explode when q(x)0q(x) \to 0 for xx where p(x)>0p(x) > 0?
Because log(q(x))-\log(q(x)) \to \infty as q(x)0q(x) \to 0. The model assigns near-zero probability to something that actually happens — infinite surprise.

Concept Map

expected value

additivity needs

min bits knowing p

wrong code -log q

weights frequency

H p,q minus H p

irreducible part

extra wasted bits

penalizes wrong predictions

min when q = p

Surprise -log p x

Shannon Entropy H p

Logarithm

Cross-Entropy H p,q

Predicted dist q x

True dist p x

KL Divergence

H p,q = H p + KL

Classification Loss

Optimal Model

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Cross-entropy samajhne ke liye ek simple example hai. Maan lo aap ek weather forecaster ho. Har din aap predict karte ho ki baarish hogi ya nahi, probability ke sath. Agar aap kehte ho "90% chance hai baarish ka" aur sach mein baarish hoti hai, toh aapka prediction acha tha - kam surprise hua. Lekin agar aap kehte ho "10% chance hai" aur baarish ho jati hai, toh bahut bada surprise hua - aap confident the galat direction mein!

Cross-entropy basically yahi measure karta hai: average surprise kitna hai jab reality (true distribution p) aapke belief (predicted distribution q) se match nahi karta. Formula hai H(p,q) = -Σ p(x) log(q(x)). Matlab true probability p(x) se weight karke, har outcome ka predicted probability q(x) ka log lete hain. Jitna zyada match hoga p aur q mein, utna kam cross-entropy.

Machine learning mein, classification tasks ke liye cross-entropy sabse popular loss function hai. Kyon? Kyunki yeh confident galat predictions ko bahut heavily penalize karta hai. Agar aapka neural network 95% confident hai ki image mein dog hai, lekin actually cat hai, toh cross-entropy loss bahut high hoga - model ko strong sign

Go deeper — visual, from zero

Test yourself — Probability & Statistics

Connections