Cross-Entropy Loss
Historical Context
Core Definitions
Key Formulas
Properties and Theorems
Worked Examples
Python Implementation
import numpy as np
def binary_cross_entropy(y_true, y_pred):
"""Compute binary cross-entropy loss."""
y_pred = np.clip(y_pred, 1e-7, 1 - 1e-7)
return -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))
def categorical_cross_entropy(y_true, y_pred):
"""Compute categorical cross-entropy loss."""
y_pred = np.clip(y_pred, 1e-7, 1 - 1 - 1e-7) # Fix: should be 1 - 1e-7
return -np.mean(np.sum(y_true * np.log(y_pred), axis=1))
def sparse_categorical_cross_entropy(y_true, y_pred):
"""Compute cross-entropy for integer labels."""
y_pred = np.clip(y_pred, 1e-7, 1 - 1e-7)
N = y_true.shape[0]
return -np.mean(np.log(y_pred[np.arange(N), y_true]))
def softmax(z):
"""Numerically stable softmax."""
z_shifted = z - np.max(z, axis=-1, keepdims=True)
exp_z = np.exp(z_shifted)
return exp_z / np.sum(exp_z, axis=-1, keepdims=True)
def cross_entropy_with_logits(y_true, logits):
"""Compute CE directly from logits (more numerically stable)."""
probs = softmax(logits)
N = y_true.shape[0]
return -np.mean(np.sum(y_true * np.log(probs), axis=1))
# --- Examples ---
# Binary CE
y_true = np.array([1, 0, 1, 1])
y_pred = np.array([0.9, 0.1, 0.8, 0.7])
print(f"BCE: {binary_cross_entropy(y_true, y_pred):.4f}")
# Categorical CE
y_true = np.array([[1, 0, 0], [0, 1, 0]])
y_pred = np.array([[0.7, 0.2, 0.1], [0.1, 0.8, 0.1]])
print(f"CE: {categorical_cross_entropy(y_true, y_pred):.4f}")
# Sparse CE
y_true = np.array([0, 1])
y_pred = np.array([[0.7, 0.2, 0.1], [0.1, 0.8, 0.1]])
print(f"Sparse CE: {sparse_categorical_cross_entropy(y_true, y_pred):.4f}")
# Logits
logits = np.array([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]])
y_true = np.array([[1, 0, 0], [0, 1, 0]])
print(f"CE from logits: {cross_entropy_with_logits(y_true, logits):.4f}")
Why Cross-Entropy for Classification?
Common Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
| Using MSE for classification | Poor gradients, non-convex | Use cross-entropy loss |
| Forgetting to clip predictions | log(0) = -∞ causes NaN | Clip to [ε, 1-ε] |
| Applying CE to regression | CE is for discrete distributions | Use MSE or MAE for regression |
| Not using softmax before CE | Raw logits aren't probabilities | Apply softmax or use logits directly |
| Ignoring class imbalance | CE treats all classes equally | Use weighted CE or focal loss |
| Confusing BCE with Categorical CE | BCE is for binary, CE for multi-class | Match loss to problem type |
Interview Questions
Q1: Why not use MSE for classification? A: MSE + sigmoid has vanishing gradients when the model is confidently wrong (saturation region). CE + softmax has gradient which doesn't saturate. Also, CE is convex for linear models while MSE is not.
Q2: What's the connection between CE and MLE? A: Minimizing CE is equivalent to maximizing log-likelihood: . This is exactly the negative log-likelihood.
Q3: How does label smoothing help? A: Label smoothing replaces hard one-hot labels with soft targets: . This prevents overconfident predictions and improves generalization. It's equivalent to adding a regularization term.
Q4: Why is CE called "cross-entropy"? A: It measures the "cross" between two distributions. When , it equals the entropy —the theoretical minimum. When , it's larger by .
Q5: What happens numerically when is very close to 0 or 1? A: . In practice, clip predictions to or compute CE directly from logits using which is numerically stable.
Practice Problems
Advanced Topics
Quick Reference
| Loss Function | Formula | Use Case |
|---|---|---|
| Binary CE | Binary classification | |
| Categorical CE | Multi-class (one-hot) | |
| Sparse CE | where is true class | Multi-class (integer labels) |
| Weighted CE | Imbalanced classes | |
| Focal CE | Hard examples |
Cross-References
- 081 - Entropy — — cross-entropy decomposes into entropy plus KL.
- 082 - Mutual Information — MI is used for feature selection; CE is used for training.
- 083 - KL Divergence: — CE minus entropy equals KL.
- 085 - Applications — Cross-entropy is the loss in classification, knowledge distillation, and language modeling.