Cross-Entropy Loss
Cross-Entropy Loss
A loss function for classification problems. Measures the difference between predicted probabilities and the actual distribution.
Cross-Entropy Loss
A loss function for classification problems. Measures the difference between predicted probabilities and the actual distribution.
Cross-Entropy Loss is a loss function that measures a model's prediction error in classification problems. It calculates the cross-entropy between the probability distribution output by the model and the actual correct answer (one-hot encoding), and updates the model parameters in the direction that minimizes this value.
It has been established as the standard loss function for classification problems since the early days of deep learning. When combined with the Softmax activation function, the derivative becomes simple (y_pred - y_true), and backpropagation is computed efficiently. Thanks to this mathematical convenience, it has been the default choice for neural network classifiers since the 1990s.
Cross-Entropy Loss is divided into binary classification (Binary CE) and multi-class classification (Categorical CE). For binary classification it is calculated as L = -[y*log(p) + (1-y)*log(1-p)], and for multi-class classification as L = -sum(y_i * log(p_i)). PyTorch's CrossEntropyLoss combines LogSoftmax and NLLLoss internally to ensure numerical stability.
In practice, it is used for most classification tasks, such as ImageNet classification, BERT's masked language modeling, and GPT's next-token prediction. Applying Label Smoothing helps prevent overfitting, and transforming it into Focal Loss can address class imbalance problems.
import torch
import torch.nn as nn
import torch.nn.functional as F
# 기본 CrossEntropyLoss 사용
criterion = nn.CrossEntropyLoss()
# 예측 logits (softmax 적용 전)
logits = torch.tensor([
[2.0, 1.0, 0.1], # 클래스 0을 강하게 예측
[0.5, 2.5, 0.3], # 클래스 1을 강하게 예측
[0.2, 0.3, 3.0] # 클래스 2를 강하게 예측
])
# 정답 레이블 (클래스 인덱스)
targets = torch.tensor([0, 1, 2])
# Loss 계산
loss = criterion(logits, targets)
print(f"Cross-Entropy Loss: {loss.item():.4f}") # ~0.36
# 클래스 불균형 해결: 가중치 적용
# 클래스 0:1:2 비율이 1:10:100일 때
class_weights = torch.tensor([100.0, 10.0, 1.0]) # 역비율로 가중치
weighted_criterion = nn.CrossEntropyLoss(weight=class_weights)
weighted_loss = weighted_criterion(logits, targets)
print(f"Weighted CE Loss: {weighted_loss.item():.4f}")
# Label Smoothing 적용 (과적합 방지)
smooth_criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
smooth_loss = smooth_criterion(logits, targets)
print(f"Label Smoothed CE Loss: {smooth_loss.item():.4f}")
# Binary Cross-Entropy (이진 분류)
bce_criterion = nn.BCEWithLogitsLoss()
binary_logits = torch.tensor([1.5, -0.5, 2.0])
binary_targets = torch.tensor([1.0, 0.0, 1.0])
bce_loss = bce_criterion(binary_logits, binary_targets)
print(f"Binary CE Loss: {bce_loss.item():.4f}")
# 실제 학습 루프에서 사용
model = nn.Linear(10, 3) # 입력 10, 출력 3클래스
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 미니배치 학습
x = torch.randn(32, 10) # 배치 크기 32
y = torch.randint(0, 3, (32,)) # 랜덤 레이블
optimizer.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer.step()
print(f"Training Loss: {loss.item():.4f}")
"The training loss keeps decreasing, but the validation loss is going up from 0.8. It's classic overfitting. Let's apply label smoothing of 0.1 or add data augmentation. Reducing the model size is another option."
"The reason you need to pass logits to CrossEntropyLoss is numerical stability. It internally uses the log-sum-exp trick, in which the exponentiation of softmax and the log cancel each other out, which prevents overflow. So you shouldn't apply softmax yourself before passing the values in."
"You missed setting ignore_index=-100 here. Padding tokens are also being included in the loss calculation, which is why training isn't going well. When doing sequence classification in NLP, the padding index must be specified as ignore_index."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
PyTorch's CrossEntropyLoss applies softmax internally. If you apply softmax to the model output first and then pass it into CrossEntropyLoss, you will get incorrect results. Pass the logits directly.
CrossEntropyLoss requires the target to be class indices (Long tensor), while BCELoss requires probabilities (Float tensor). Passing a one-hot encoded target into CrossEntropyLoss will cause an error.
The default reduction='mean' returns the average over the batch. If you need per-sample loss, you must set reduction='none', and when used together with class weights, unintended scaling can occur.