🤖 AI/ML

Loss Function

Loss Function

A function that measures the difference between model predictions and actual values. MSE, Cross-Entropy, and others. The optimization target of training.

📖 Detailed Explanation

A Loss Function is a function that quantifies the difference between a model's predicted values and the actual ground truth. The smaller this value, the closer the model's predictions are to the correct answers. The training process of machine learning is, in the end, an optimization problem of finding the parameters that minimize this loss function.

The loss function is chosen differently depending on the type of problem. For regression problems, MSE (Mean Squared Error), MAE (Mean Absolute Error), Huber Loss, and others are used. For classification problems, Cross-Entropy Loss is the standard, with Binary Cross-Entropy used for binary classification and Categorical Cross-Entropy used for multi-class classification.

The characteristics of the loss function have a major impact on training. MSE applies a larger penalty to large errors, making it sensitive to outliers. MAE applies the same weight to all errors, making it robust to outliers. Cross-Entropy measures the difference between probability distributions and applies a large penalty to incorrect predictions whose probability is close to 0.

Advanced loss functions are also widely used. Focal Loss reduces the loss of easy samples to focus on hard samples. Contrastive Loss and Triplet Loss are used for embedding learning. Dice Loss addresses the class imbalance problem in Segmentation. In practice, multiple loss functions are sometimes combined using a weighted sum.

Code Example

An example of using various loss functions and implementing custom ones in PyTorch.

import torch
import torch.nn as nn
import torch.nn.functional as F

# ===== 회귀 손실 함수 =====
mse_loss = nn.MSELoss()
mae_loss = nn.L1Loss()
huber_loss = nn.HuberLoss(delta=1.0)

pred = torch.tensor([2.5, 0.0, 2.1, 7.8])
target = torch.tensor([3.0, -0.5, 2.0, 7.5])

print(f"MSE Loss: {mse_loss(pred, target):.4f}")  # 0.1275
print(f"MAE Loss: {mae_loss(pred, target):.4f}")  # 0.3250

# ===== 분류 손실 함수 =====
ce_loss = nn.CrossEntropyLoss()
bce_loss = nn.BCEWithLogitsLoss()

# 다중 분류: logits (B, C) vs labels (B,)
logits = torch.tensor([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]])
labels = torch.tensor([0, 1])
print(f"CrossEntropy: {ce_loss(logits, labels):.4f}")

# 이진 분류: logits (B,) vs labels (B,)
logits_binary = torch.tensor([0.9, -0.5, 0.3])
labels_binary = torch.tensor([1.0, 0.0, 1.0])
print(f"BCE: {bce_loss(logits_binary, labels_binary):.4f}")

# ===== Focal Loss 구현 =====
class FocalLoss(nn.Module):
    def __init__(self, alpha=1, gamma=2):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, inputs, targets):
        ce_loss = F.cross_entropy(inputs, targets, reduction='none')
        pt = torch.exp(-ce_loss)  # 정답 확률
        focal_loss = self.alpha * (1 - pt) ** self.gamma * ce_loss
        return focal_loss.mean()

# ===== Label Smoothing =====
ce_smooth = nn.CrossEntropyLoss(label_smoothing=0.1)

# ===== 가중 손실 함수 조합 =====
class CombinedLoss(nn.Module):
    def __init__(self, alpha=0.5):
        super().__init__()
        self.alpha = alpha
        self.ce = nn.CrossEntropyLoss()
        self.dice = DiceLoss()  # 커스텀 구현 필요

    def forward(self, pred, target):
        return self.alpha * self.ce(pred, target) + (1-self.alpha) * self.dice(pred, target)

Performance & Cost

Loss Function Applications Advantages Cautions
MSE (L2) Regression Mathematically easy to handle Sensitive to outliers
MAE (L1) Regression Robust to outliers Not differentiable at 0
Cross-Entropy Classification Probabilistic interpretation possible Vulnerable to class imbalance
Focal Loss Object Detection Effective for imbalanced data Requires gamma tuning
Dice Loss Segmentation Directly optimizes IoU Sensitive to batch size

🗣️ Say It Like This in Practice

"After switching to Focal Loss because of severe class imbalance, the Recall of the minority class went up by 20%. I set gamma=2."

In English, you would say "Switching to Focal Loss improved minority class recall by 20%". Terms such as "loss landscape", "loss curve", and "training loss vs validation loss" are also frequently used. During training, you would say "the loss is going down/has plateaued/has diverged".

⚠️ Common Mistakes & Cautions

  • 1. NaN occurrence: If log(0) or division by zero occurs, the result becomes NaN. Add a small epsilon or use clamp.
  • 2. Confusion over reduction mode: The learning rate scale varies depending on which of 'mean', 'sum', and 'none' you use.
  • 3. Duplicate Softmax: CrossEntropyLoss includes log_softmax internally. You must not apply softmax to the input again.
  • 4. Mismatch between loss function and evaluation metric: If you train with Cross-Entropy and evaluate with F1-Score, the optimal points may differ.
  • 5. Weight scale: When combining multiple losses, differing scales cause the result to be biased toward one side. Normalize them or use dynamic weights.

🔗 Related Terms

📚 Learn More