본문 바로가기
AI

딥러닝 소프트맥스 함수 완벽 정리: 정의, 수식, 예제까지

by markbyun 2025. 4. 23.

소프트맥스(Softmax)란?

Softmax는 실수 벡터(로짓)를 예측 클래스에 대한 확률 분포로 변환하는 수학적 함수입니다. 주로 분류 모델의 출력층, 특히 다중 클래스 분류 문제에서 사용됩니다.

수학적 정의

실수 벡터 $z = [z_1, z_2, ..., z_K]$가 주어지면, 소프트맥스 함수는 벡터 $\sigma(z)$를 출력합니다. 여기서:

$\sigma(Z_i)=\frac{e^{z_i}}{\sum_{j=1}^{K}e^{z_j}} \text{(for i=1, ..., K)}$

각 요소 $\sigma(z_i) \in (0, 1)$이며, 모든 요소의 합은 1입니다: $\sum_{i=1}^K \sigma(z_i) = 1$.


소프트맥스를 사용하는 이유

  • 로짓(raw score)을 확률로 변환해줍니다.
  • 모델이 예측에 대해 신뢰도(confidence)를 부여할 수 있게 합니다.
  • 미분 가능하여 학습 시 그래디언트 기반 최적화가 가능합니다.

모델 성능에 미치는 영향

분류 정확도

교차 엔트로피 손실 함수와 함께 사용하면, 잘못된 예측에 더 큰 페널티를 부여하여 딥러닝 모델을 효과적으로 학습시킬 수 있습니다. 이는 더 나은 수렴성과 향상된 분류 정확도를 제공합니다 ([Goodfellow et al., 2016]).

과신 및 보정

소프트맥스는 작은 로짓 차이를 확률상 큰 차이로 증폭시킬 수 있습니다. 이는 결정적인 예측에는 유리하지만, 모델이 불확실할 때는 과신(overconfidence)으로 이어질 수 있습니다. 이러한 경우에는 레이블 스무딩, 온도 조절(temperature scaling), 베이지안 모델링 등의 기법이 도움이 됩니다 ([Guo et al., 2017]).


파이썬으로 직접 구현하기

import numpy as np

def softmax(logits):
    """Compute softmax values for each set of scores in logits."""
    exp_shifted = np.exp(logits - np.max(logits))  # for numerical stability
    return exp_shifted / np.sum(exp_shifted)

# Test Cases
assert np.allclose(softmax([1.0, 2.0, 3.0]), 
                   [0.09003057, 0.24472847, 0.66524096], atol=1e-6)

assert np.allclose(np.sum(softmax([2.0, 2.0, 2.0])), 1.0)
assert np.all(softmax([5, 1, -2]) > 0)

print("All tests passed!")

PyTorch에서의 Softmax

PyTorch에서는 torch.nn.functional.softmax를 모델 정의와 평가 시에 자주 사용합니다. 사용 방법은 다음과 같습니다:

import torch
import torch.nn.functional as F

# Logits from model output
logits = torch.tensor([1.0, 2.0, 3.0])
probs = F.softmax(logits, dim=0)

print(probs)  # Tensor with probabilities summing to 1

모델 내에서의 사용 예:

import torch.nn as nn

class MyClassifier(nn.Module):
    def __init__(self, input_dim, output_dim):
        super().__init__()
        self.linear = nn.Linear(input_dim, output_dim)

    def forward(self, x):
        logits = self.linear(x)
        return F.softmax(logits, dim=1)

중요: 실제로는 nn.CrossEntropyLoss를 사용하기 전에 softmax를 적용하지 마세요. 이 손실 함수는 내부적으로 softmax를 포함하고 있어 수치적으로 더 안정적입니다.


참고문헌

  • Goodfellow, I., Bengio, Y., & Courville, A. $\text{(2016)}$. Deep Learning. MIT Press. Section 6.2 – Output Units
  • Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. $\text{(2017)}$. On Calibration of Modern Neural Networks. ICML. [Paper Link]
  • Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. [Chapter 4 – Probabilistic Generative Models]