Softmax
Softmax
A function that converts logits into a probability distribution. Used in the output layer of multi-class classification. Normalizes so that all outputs sum to 1.
Softmax
A function that converts logits into a probability distribution. Used in the output layer of multi-class classification. Normalizes so that all outputs sum to 1.
Softmax is an activation function that converts an arbitrary real-valued vector (logits) into a probability distribution. It applies the exponential function (exp) to each element and then divides by the total sum, so that every output lies between 0 and 1 and the outputs sum to exactly 1. Formula: softmax(x_i) = exp(x_i) / sum(exp(x_j))
It was first proposed by Robert Luce in 1959 in a choice model, and John Bridle applied it to neural networks in 1989. As the name "soft" + "max" suggests, it can be viewed as a differentiable (soft) version of argmax. The largest value gets a high probability, while the probabilities of the other classes are also retained.
The key characteristic is the amplification of differences caused by the exponential function. If the logits are [2, 1, 0], softmax gives approximately [0.67, 0.24, 0.09]. The larger the input differences, the closer the output gets to winner-take-all. This characteristic can be adjusted with the Temperature (T) parameter: softmax(x/T)
It is used in multi-class classification (image classification, natural language processing), in computing Attention weights in the Transformer, and in computing next-token probabilities in LLMs. When used together with Cross-Entropy Loss, the gradient is computed cleanly as (prediction - label), which makes training stable.
import numpy as np
import torch
import torch.nn.functional as F
# 1. NumPy로 직접 구현 (수치 안정성 포함)
def softmax_numpy(x):
"""Numerically stable softmax"""
x_max = np.max(x, axis=-1, keepdims=True)
exp_x = np.exp(x - x_max) # overflow 방지
return exp_x / np.sum(exp_x, axis=-1, keepdims=True)
logits = np.array([2.0, 1.0, 0.1])
probs = softmax_numpy(logits)
print(f"로짓: {logits}")
print(f"확률: {probs}") # [0.659, 0.242, 0.099]
print(f"합계: {probs.sum()}") # 1.0
# 2. PyTorch 내장 함수
logits_torch = torch.tensor([2.0, 1.0, 0.1])
probs_torch = F.softmax(logits_torch, dim=-1)
print(f"PyTorch softmax: {probs_torch}")
# 3. Temperature로 분포 조절
def softmax_with_temperature(logits, temperature=1.0):
"""Temperature가 낮을수록 sharp, 높을수록 uniform"""
return F.softmax(logits / temperature, dim=-1)
logits = torch.tensor([3.0, 1.0, 0.5])
print(f"T=0.5 (sharp): {softmax_with_temperature(logits, 0.5)}") # [0.93, 0.05, 0.02]
print(f"T=1.0 (normal): {softmax_with_temperature(logits, 1.0)}") # [0.84, 0.11, 0.05]
print(f"T=2.0 (soft): {softmax_with_temperature(logits, 2.0)}") # [0.65, 0.21, 0.14]
# 4. 분류 모델에서 사용
class Classifier(torch.nn.Module):
def __init__(self, input_dim, num_classes):
super().__init__()
self.linear = torch.nn.Linear(input_dim, num_classes)
def forward(self, x):
logits = self.linear(x)
# 학습 시: CrossEntropyLoss가 내부적으로 softmax 적용
# 추론 시: F.softmax(logits, dim=-1)로 확률 변환
return logits
# CrossEntropyLoss = LogSoftmax + NLLLoss
loss_fn = torch.nn.CrossEntropyLoss()
logits = torch.randn(4, 10) # batch=4, classes=10
labels = torch.randint(0, 10, (4,))
loss = loss_fn(logits, labels) # softmax 내장
"The model output is logits, so you can't interpret it directly. Apply softmax to convert it into probabilities, and then look at the highest class, something like cat 0.85, dog 0.10. At 0.85, it's a high-confidence prediction."
"Softmax converts logits into a probability distribution. It makes values positive with the exponential function and then normalizes them. When used with Cross-Entropy Loss, the gradient simplifies to (prediction - label), so training is stable. Subtracting the max for numerical stability is also important."
"If you set Temperature to 0.7, softmax becomes sharper, so sampling focuses on high-probability tokens. If you need creative output, raising the temperature to around 1.2 flattens the distribution, so a variety of tokens get selected."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
PyTorch's nn.CrossEntropyLoss applies LogSoftmax internally. If you apply softmax to the input beforehand, it is applied twice and training breaks.
exp(1000) becomes inf. Be sure to subtract the max to ensure numerical stability: exp(x - max(x)). Most built-in library functions already handle this.
During training, pass logits directly to CrossEntropyLoss, and convert to probabilities with F.softmax() only at inference time. If you need to adjust Temperature, divide the logits before softmax.