🤖 AI/ML

Cross-Entropy

Cross-Entropy

A loss function for classification problems. Measures the difference between predicted probabilities and the actual distribution.

📖 Detailed Explanation

Cross-Entropy is a concept from information theory that measures the difference between two probability distributions. In machine learning, it is used to quantify the difference between the probability distribution predicted by a model and the actual ground-truth distribution, and it underlies the most widely used loss functions for classification problems.

Claude Shannon, the founder of information theory, established the concept of entropy in 1948, and cross-entropy later developed as a way to measure the "information difference" between two distributions. As it came to be widely applied to neural network training from the 1990s onward, it became a core tool of deep learning.

Mathematically, cross-entropy H(p,q) is defined as -sum(p(x) * log(q(x))). Here p is the true distribution (ground truth) and q is the predicted distribution. The value gets smaller the more the prediction matches the ground truth, and larger the more it is wrong. Due to the nature of the log function, it imposes a large penalty on confidently wrong predictions (a wrong answer with 0.99 probability).

In practice, cross-entropy is used in nearly every classification task, including image classification, next-token prediction in natural language processing, and recommendation systems. Language models such as GPT are trained by minimizing the cross-entropy of next-token prediction. The average cross-entropy is also converted to perplexity to compare model performance.

💻 Code Example

import numpy as np
import torch
import torch.nn.functional as F

# NumPy로 직접 구현
def cross_entropy_numpy(y_true, y_pred, epsilon=1e-15):
    """
    y_true: 원-핫 인코딩된 실제 레이블 (batch_size, num_classes)
    y_pred: 예측 확률 분포 (batch_size, num_classes)
    """
    # 수치 안정성을 위해 클리핑
    y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
    # 교차 엔트로피 계산
    ce = -np.sum(y_true * np.log(y_pred), axis=1)
    return np.mean(ce)

# 예제: 3개 클래스 분류
y_true = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])  # 정답
y_pred_good = np.array([[0.9, 0.05, 0.05], [0.1, 0.8, 0.1], [0.1, 0.1, 0.8]])  # 좋은 예측
y_pred_bad = np.array([[0.3, 0.4, 0.3], [0.4, 0.3, 0.3], [0.3, 0.3, 0.4]])   # 나쁜 예측

print(f"좋은 예측의 CE: {cross_entropy_numpy(y_true, y_pred_good):.4f}")  # ~0.18
print(f"나쁜 예측의 CE: {cross_entropy_numpy(y_true, y_pred_bad):.4f}")   # ~1.10

# PyTorch에서 사용
logits = torch.tensor([[2.0, 0.5, 0.3], [0.2, 2.5, 0.3], [0.1, 0.2, 2.8]])
targets = torch.tensor([0, 1, 2])  # 클래스 인덱스

# CrossEntropyLoss는 softmax + NLL을 결합
loss = F.cross_entropy(logits, targets)
print(f"\nPyTorch CE Loss: {loss.item():.4f}")

# Perplexity 변환 (언어 모델 평가 시 사용)
perplexity = torch.exp(loss)
print(f"Perplexity: {perplexity.item():.4f}")

🗣️ Say It Like This in Practice

In a model training meeting

"The training loss won't go below 0.5; a cross-entropy of 0.5 means a perplexity of about 1.65. In a 3-class classification, the perplexity of random guessing is 3, so the model is learning. But if there is a class imbalance problem, try applying weighted cross-entropy."

In a technical interview

"The reason we use cross-entropy instead of MSE for classification is the vanishing gradient problem. The derivative of MSE becomes very small when the prediction is close to 0 or 1, whereas cross-entropy maintains a gradient proportional to how wrong the prediction is. That's why training is much faster and more stable."

In a code review

"You applied softmax first here and then passed it into cross_entropy_loss, but PyTorch's CrossEntropyLoss applies log_softmax internally. Softmax gets applied twice, which can cause numerical instability. Pass the logits in directly."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1.
Numerical instability (the log(0) problem)

When a predicted probability is close to 0, log(0) produces -inf. PyTorch's built-in functions handle this automatically, but in your own implementation you must add an epsilon (e.g., 1e-15) or clip.

2.
Ignoring class imbalance

With imbalanced data at a 1:100 ratio, using plain cross-entropy produces a model that predicts only the majority class. Give a higher weight to the minority class with the class_weight parameter, or use Focal Loss.

3.
Confusing Binary vs Categorical

Mixing BCELoss (Binary Cross-Entropy) and CrossEntropyLoss in binary classification causes dimension errors. Use BCEWithLogitsLoss for 2 classes and CrossEntropyLoss for 3 or more.

🔗 Related Terms

📚 Learn More