Definition

In bits use , in nats . , maximized at uniform (), zero for a point mass. The decomposition that ties everything together:

so minimizing cross-entropy over minimizes the KL to , because is a constant of the data (KL Divergence). With one-hot labels and cross-entropy is the KL.

For classification with target and prediction ,

the negative log-likelihood of the correct class, gradient (Cross-Entropy Gradient).

Conditional and joint versions: , and the chain rule . Differential entropy for continuous replaces the sum by an integral and can be negative; a Gaussian has , the maximum for a given variance.

From scratch

import numpy as np
 
def entropy(p, base=np.e):
    p = p[p > 0]
    return float(-(p * np.log(p)).sum() / np.log(base))
 
def cross_entropy_from_logits(logits, y_idx):          # stable, no log(softmax)
    m = logits.max(axis=-1, keepdims=True)
    lse = m.squeeze(-1) + np.log(np.exp(logits - m).sum(axis=-1))
    return float(np.mean(lse - logits[np.arange(len(y_idx)), y_idx]))
 
def entropy_from_logits(logits):                       # per-row predictive entropy
    m = logits.max(axis=-1, keepdims=True)
    logp = logits - m - np.log(np.exp(logits - m).sum(axis=-1, keepdims=True))
    return -(np.exp(logp) * logp).sum(axis=-1)

Notes

  • Compute from logits via log-sum-exp; log(p) with a clamped epsilon is a silent accuracy bug.
  • is asymmetric and ; only is a property of one distribution.
  • Predictive entropy is the standard cheap uncertainty signal (high entropy means the model is unsure).
  • Exponentiating mean cross-entropy gives Perplexity, the language-modeling unit.