🤖 AI/ML

Loss Function

Loss Function

Measures the difference between prediction and actual value. MSE, Cross-Entropy. The target of optimization.

📖 Detailed Explanation

A loss function is a function that quantifies the difference between a model's predicted value and the actual ground truth. In machine learning and deep learning, the goal of model training is to minimize the value of this loss function, and optimization algorithms (SGD, Adam, etc.) accomplish this.

The history of the loss function dates back to the method of least squares in statistics (1805, Legendre). In modern deep learning, various loss functions are used depending on the type of problem, and choosing an appropriate loss function has a decisive impact on model performance.

For regression problems, MSE (Mean Squared Error), MAE (Mean Absolute Error), and Huber Loss are used. For classification problems, Cross-Entropy Loss, Binary Cross-Entropy, and Focal Loss are used. A loss function must be differentiable so that the model can be trained through backpropagation.

In practice, the loss function is a key metric for monitoring model training. Overfitting is detected through training/validation loss graphs, and for multiple objectives, several loss functions are combined as a weighted sum. Optimization aligned with business goals is also possible with custom loss functions.

💻 Code Example

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

# ===== 회귀 문제 손실 함수 =====
y_true = torch.tensor([3.0, -0.5, 2.0, 7.0])
y_pred = torch.tensor([2.5, 0.0, 2.0, 8.0])

# MSE: Mean Squared Error (평균 제곱 오차)
mse_loss = nn.MSELoss()
print(f"MSE Loss: {mse_loss(y_pred, y_true):.4f}")  # 0.3750

# MAE: Mean Absolute Error (평균 절대 오차)
mae_loss = nn.L1Loss()
print(f"MAE Loss: {mae_loss(y_pred, y_true):.4f}")  # 0.5000

# Huber Loss: MSE와 MAE의 장점 결합 (이상치에 강건)
huber_loss = nn.HuberLoss(delta=1.0)
print(f"Huber Loss: {huber_loss(y_pred, y_true):.4f}")

# ===== 분류 문제 손실 함수 =====
# 이진 분류
y_true_binary = torch.tensor([1.0, 0.0, 1.0, 0.0])
y_pred_logits = torch.tensor([0.9, -0.5, 0.8, -1.0])

bce_loss = nn.BCEWithLogitsLoss()
print(f"Binary CE Loss: {bce_loss(y_pred_logits, y_true_binary):.4f}")

# 다중 클래스 분류
y_true_class = torch.tensor([0, 2, 1])  # 클래스 인덱스
y_pred_logits = torch.tensor([
    [2.0, 0.5, 0.3],   # 클래스 0 예측
    [0.1, 0.2, 3.0],   # 클래스 2 예측
    [0.5, 2.5, 0.1]    # 클래스 1 예측
])

ce_loss = nn.CrossEntropyLoss()
print(f"Cross-Entropy Loss: {ce_loss(y_pred_logits, y_true_class):.4f}")

# ===== 커스텀 손실 함수 =====
class FocalLoss(nn.Module):
    """클래스 불균형 문제에 효과적인 Focal Loss"""
    def __init__(self, alpha=0.25, gamma=2.0):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, inputs, targets):
        bce = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none')
        pt = torch.exp(-bce)
        focal_loss = self.alpha * (1 - pt) ** self.gamma * bce
        return focal_loss.mean()

focal = FocalLoss()
print(f"Focal Loss: {focal(y_pred_logits[:, 0], y_true_binary[:3]):.4f}")

🗣️ Say It Like This in Practice

💬 In a Meeting
"The training loss converged to 0.5 at epoch 10, but the validation loss is no longer decreasing from 0.8. It looks like a sign of overfitting, so we should apply Early Stopping or increase Dropout."
💬 In an Interview
"The reason for using Cross-Entropy instead of MSE for classification problems is that it better measures the difference between probability distributions. With MSE, the gradient gets smaller as the prediction approaches the correct answer, but with CE, a larger penalty is given when the probability is low, so training is faster."
💬 In a Technical Discussion
"For problems with severe class imbalance, such as fraud detection, using Focal Loss or Weighted Cross-Entropy, which assigns class weights, is effective. Setting gamma=2 reduces the influence of easy samples and focuses on hard samples."

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

⚠️ Common Mistakes & Cautions

❌
Using MSE for Classification

If you use MSE for a classification problem, the probability output can fall outside the [0,1] range, and training is also slow. You should use Cross-Entropy for classification.

✅
The Right Choice

Use MSE/MAE for regression and CE for classification as the default. If there are many outliers, consider Huber Loss; for class imbalance, consider Focal Loss or applying weights.

🔗 Related Terms

📚 Learn More