Linear models may look like an old topic, but the last layer of a deep learning model is almost always a linear model. What dozens of Transformer layers do is, in the end, build a good feature vector , and the LM head that picks the next token on top of it is exactly this lesson’s softmax regression. So if you understand the gradient, temperature and logit scale of softmax regression precisely, you can read off directly what SFT and RL updates do to the logits.
The three models share one frame.
| Model | Output | Probability model | Loss (NLL) | Gradient w.r.t. the logit |
|---|---|---|---|---|
| Linear regression | ||||
| Logistic regression | , | |||
| Softmax regression | , |
The last column is the hero of this lesson. In all three cases the gradient is “prediction − target”. This is no coincidence: all three distributions are in the exponential family and each uses its “canonical” link function. We derive them one by one below. For convenience the bias is folded into by appending a constant 1 to .
Linear regression
The gradient of is , the average over samples of “(prediction − target) × input”. Setting it to 0 gives the normal equations from the first lesson.
Solved by gradient descent, the Hessian is , the second-moment matrix of the inputs. Applying the results of the gradient descent lesson directly, the learning rate must be below and the convergence speed is set by . If the input features have very different scales (say, height in cm and income in won), grows and learning slows down. That is why standardising the features (mean 0, variance 1) matters, and it is also one of the jobs normalisation layers (LayerNorm and others) do in deep learning.
Logistic regression
In binary classification we cannot use directly as a probability. We squash it into with the sigmoid.
The second equation is the key to interpretation: the logit is the log-odds. Logistic regression is the model “the log-odds are linear in the input”. Increasing the input by 1 multiplies the odds by .
Let us find the gradient. The derivative of the sigmoid is . Differentiating the loss with respect to ,
The cancels cleanly. By the chain rule, . Had we put an MSE on the sigmoid output, a factor would remain in the gradient, and the gradient would vanish when is near 0 or 1 — a situation where the model cannot learn even though it is badly wrong. With cross-entropy, the log exactly cancels the saturation of the sigmoid.
The Hessian is , so the loss is convex: any local minimum is the global minimum. There is no closed-form solution, though, so iterative methods (GD, Newton’s method) are used.
Softmax regression
With classes we make logits. ; the -th row of is the “score vector” of class .
The derivative falls straight out of the second form (subtract the correct logit, add the log-sum-exp). Since ,
How to read it: the logit of the correct class goes up by , and every other logit goes down by its own probability . If the model is already confidently right (), the update is almost 0.
Several properties follow directly from this formula.
- Shift invariance: adding the same constant to every logit leaves unchanged. That is why implementations first compute to prevent overflow (the log-sum-exp trick). For the same reason one of the rows is redundant, and with , , which is the same as logistic regression.
- Decision boundaries: the boundary between classes and is , i.e. the hyperplane . Each class’s region is an intersection of half-spaces, hence a convex polytope. A linear model cannot produce non-convex regions (XOR, rings).
- Linear in the features: if we feed a fixed feature map instead of , the model is still linear in . The boundary is a hyperplane in -space but a curve in the original -space. Neural networks learn this itself (Track II).
Temperature and logit scale
Consider , the logits divided by a temperature . As it becomes one-hot with all mass on the argmax; as it becomes uniform. But the argmax does not depend on . Temperature changes only confidence, not the decision boundary.
Seen the other way, scaling by is the same as lowering the temperature to . ‖W‖ is the model’s confidence. Saying that ‖W‖ grows without bound on separable data means the boundary stays almost fixed while confidence grows indefinitely. Both the tendency of neural networks to be overconfident (miscalibrated) and temperature scaling (Guo et al., 2017), which recalibrates a trained model by fitting a single temperature, come from this observation.
In a picture
선형 모델은 낡은 주제처럼 보이지만, 딥러닝 모델의 마지막 층은 거의 언제나 선형 모델이다. 수십 층의 Transformer가 하는 일은 결국 좋은 특징 벡터 를 만드는 것이고, 그 위에서 다음 토큰을 고르는 LM head는 이 레슨의 softmax 회귀 그 자체다. 그러니 softmax 회귀의 기울기, 온도, logit 크기를 정확히 이해해 두면 SFT와 RL의 업데이트가 logit에 무슨 일을 하는지 바로 읽힌다.
세 모델은 같은 틀을 공유한다.
| 모델 | 출력 | 확률 모델 | 손실 (NLL) | logit에 대한 기울기 |
|---|---|---|---|---|
| 선형회귀 | ||||
| 로지스틱 회귀 | , | |||
| softmax 회귀 | , |
마지막 열이 이 레슨의 주인공이다. 세 경우 모두 기울기가 “예측 − 정답” 이다. 우연이 아니다. 이 세 분포가 모두 지수족(exponential family)이고 각자의 “정준(canonical)” 연결함수를 썼기 때문이다. 아래에서 하나씩 유도한다. 편의상 bias는 에 상수 1을 붙여 안에 넣는다.
선형회귀
의 기울기는 , 즉 표본별 “(예측 − 정답) × 입력”의 평균이다. 0으로 놓으면 첫 레슨의 정규방정식 가 나온다.
경사하강법으로 풀면 Hessian이 , 즉 입력의 2차 모멘트 행렬이다. 경사하강법 레슨의 결과를 그대로 쓰면 학습률은 미만이어야 하고, 수렴 속도는 가 정한다. 입력 특징의 스케일이 크게 다르면(예: 키는 cm, 소득은 원) 가 커져 학습이 느려진다. 특징을 표준화(평균 0, 분산 1)하는 전처리가 그래서 중요하고, 딥러닝에서 정규화 층(LayerNorm 등)이 하는 역할 중 하나도 이것이다.
로지스틱 회귀
이진 분류에서 를 그대로 확률로 쓸 수는 없다. sigmoid로 에 눌러 넣는다.
둘째 식이 해석의 열쇠다. logit 는 log-odds다. 로지스틱 회귀는 “log-odds가 입력에 대해 선형”이라는 모델이다. 입력 가 1 늘면 odds가 배가 된다.
기울기를 구하자. sigmoid의 도함수는 다. 손실 를 로 미분하면
가 깔끔하게 지워진다. 연쇄법칙으로 . MSE를 sigmoid 출력에 붙였다면 기울기에 가 남아 가 0이나 1 근처에서 기울기가 사라졌을 것이다. 크게 틀렸는데도 배우지 못하는 상황이다. cross-entropy는 log가 sigmoid의 포화를 정확히 상쇄한다.
Hessian은 이므로 손실은 볼록하다. 국소 최소가 곧 전역 최소다. 다만 닫힌 해는 없어서 반복법(GD, 뉴턴법)을 쓴다.
Softmax 회귀
클래스가 개면 logit을 개 만든다. , 의 번째 행 가 클래스 의 “점수 벡터”다.
두 번째 꼴(정답 logit을 빼고 log-sum-exp를 더함)에서 미분이 바로 나온다. 이므로
읽는 법: 정답 클래스의 logit은 만큼 올라가고, 나머지 클래스의 logit은 각자의 확률 만큼 내려간다. 이미 맞게 확신하고 있으면() 업데이트는 거의 0이다.
몇 가지 성질이 이 식에서 바로 나온다.
- 이동 불변성: 모든 logit에 같은 상수 를 더해도 는 그대로다. 그래서 구현할 때 를 먼저 빼서 overflow를 막는다(log-sum-exp trick). 같은 이유로 개의 행 중 하나는 군더더기이고, 이면 로 로지스틱 회귀와 같아진다.
- 결정 경계: 클래스 와 의 경계는 , 즉 인 초평면이다. 각 클래스의 영역은 반공간들의 교집합이라 볼록 다면체다. 선형 모델로는 볼록하지 않은 영역(XOR, 고리)을 만들 수 없다.
- 특징에 대해 선형: 대신 고정된 특징 를 넣으면 모델은 여전히 에 대해 선형이다. 경계는 공간에서 초평면이지만 원래 공간에서는 곡선이다. 신경망은 이 자체를 학습한다(Track II).
온도와 logit 크기
logit을 온도 으로 나눈 를 생각하자. 이면 argmax에 질량이 몰린 원-핫, 이면 균등분포가 된다. 그런데 argmax는 와 무관하다. 즉 온도는 결정 경계를 바꾸지 않고 확신도만 바꾼다.
거꾸로 보면 를 배 하는 것은 온도를 로 낮추는 것과 같다. ‖W‖가 곧 모델의 확신도다. 분리 가능한 데이터에서 ‖W‖가 끝없이 커진다는 말은, 경계는 거의 그대로인데 확신만 무한히 강해진다는 뜻이다. 신경망이 과도하게 확신하는(miscalibrated) 경향과, 학습 후에 온도 하나만 맞춰 보정하는 temperature scaling(Guo et al., 2017)이 모두 이 관찰에서 나온다.
그림으로
- On “Three blobs”, as training proceeds the boundaries settle quickly but ‖W‖ and the colour intensity keep growing. The loss keeps falling after the boundaries are nearly fixed because confidence is growing.
- Lower the temperature T to 0.1 and every region darkens; raise it to 10 and they fade to white. The boundary lines do not move by a single pixel.
- Press “XOR” and accuracy stalls around 50%. Switch the features to “quadratic” and the term solves it right away. “Ring” is solved by the terms.
- Raise λ to 0.01 or more and ‖W‖ stops at a finite value and the colours fade. L2 regularisation puts a ceiling on confidence.
- Pick a class with the A, B, C buttons and click the canvas to add points. Drop one point of another class deep inside a class’s region and see how much that single point drags the boundary.
Implementing it
First we solve linear regression with the normal equations and with gradient descent and compare. The feature scales are deliberately set to 1 : 3 : 0.3 to inflate the condition number.
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 3
X = np.c_[rng.normal(size=(n, d)) * [1.0, 3.0, 0.3], np.ones(n)] # last column = bias
theta_true = np.array([2.0, -1.0, 0.5, 0.3])
y = X @ theta_true + 0.1 * rng.normal(size=n)
theta_ne = np.linalg.solve(X.T @ X, X.T @ y) # normal equations
H = X.T @ X / n # Hessian of (1/2n)||Xθ−y||²
lam = np.linalg.eigvalsh(H)
lr = 1.0 / lam.max()
theta = np.zeros(d + 1)
for t in range(500):
theta -= lr * X.T @ (X @ theta - y) / n # gradient = mean of (pred − target)·x
print("normal equations:", np.round(theta_ne, 4))
print("GD 500 steps:", np.round(theta, 4), f" (κ = {lam.max()/lam.min():.0f})")Only the coefficient of the scale-0.3 feature (the third) has not fully converged yet — exactly the gradient descent lesson’s story that the gentle direction is slow.
Logistic regression uses the gradient , and we check that the analytic gradient is right with central differences. It is a habit worth having every time you implement a new loss.
def sigmoid(z):
return 0.5 * (1 + np.tanh(0.5 * z)) # equals 1/(1+e^-z), without overflow
def logistic_loss_grad(w, X, y):
z = X @ w
p = sigmoid(z)
# −[y log p + (1−y) log(1−p)] = softplus(z) − y z (numerically stable form)
loss = np.mean(np.logaddexp(0, z) - y * z)
grad = X.T @ (p - y) / len(y) # mean of (p − y) x
return loss, grad
def grad_check(f, w, eps=1e-6):
"""Approximate the gradient by central differences (f(w+ε)−f(w−ε))/2ε and compare with the analytic one."""
_, g = f(w)
g_num = np.zeros_like(w)
for i in range(w.size):
e = np.zeros_like(w); e.flat[i] = eps
g_num.flat[i] = (f(w + e)[0] - f(w - e)[0]) / (2 * eps)
return np.max(np.abs(g - g_num)) / (np.max(np.abs(g)) + 1e-12)
# two overlapping blobs (not separable)
n2 = 200
Xb = np.r_[rng.normal([-1, -0.5], 1.0, size=(n2 // 2, 2)), rng.normal([1, 0.8], 1.0, size=(n2 // 2, 2))]
Xb = np.c_[Xb, np.ones(n2)]
yb = np.r_[np.zeros(n2 // 2), np.ones(n2 // 2)]
w = rng.normal(size=3) * 0.1
f = lambda w: logistic_loss_grad(w, Xb, yb)
print(f"[logistic] gradient check relative error = {grad_check(f, w):.2e}")
for t in range(2001):
loss, g = f(w)
w -= 0.5 * g
if t % 500 == 0:
acc = np.mean((Xb @ w > 0) == yb)
print(f" step {t:4d} loss {loss:.4f} acc {acc:.3f} w={np.round(w, 3)}")On overlapping data, converges to a finite value. Switch to separable data and the story changes.
Xs = np.c_[np.r_[rng.normal([-2, 0], 0.5, size=(50, 2)), rng.normal([2, 0.5], 0.5, size=(50, 2))], np.ones(100)]
ys = np.r_[np.zeros(50), np.ones(50)]
w = np.zeros(3)
for t in range(1, 20001):
loss, g = logistic_loss_grad(w, Xs, ys)
w -= 1.0 * g
if t in (10, 100, 1000, 10000, 20000):
u = w[:2] / np.linalg.norm(w[:2])
print(f"step {t:6d} loss {loss:.2e} ||w|| {np.linalg.norm(w[:2]):5.2f} direction {np.round(u, 3)}")Every time the step count grows 10×, ‖w‖ grows by an almost constant amount ( growth). The direction slowly gathers toward one place (the max-margin direction).
For softmax regression the gradient matrix is a single line, . To form you do not need to build a one-hot matrix; just subtract 1 at the position of the correct class.
def log_softmax(Z):
Z = Z - Z.max(axis=1, keepdims=True) # shift invariance → no overflow
return Z - np.log(np.exp(Z).sum(axis=1, keepdims=True))
def softmax_loss_grad(W, X, y, lam=0.0):
n = len(y)
logP = log_softmax(X @ W) # (n, K)
loss = -logP[np.arange(n), y].mean() + 0.5 * lam * np.sum(W[:-1] ** 2)
G = np.exp(logP) # p
G[np.arange(n), y] -= 1 # p − onehot(y) = ∂ℓ/∂z
grad = X.T @ G / n
grad[:-1] += lam * W[:-1] # the bias row is not regularised
return loss, grad
K = 3
centers = np.array([[-1.4, 0.9], [1.5, 0.7], [0.1, -1.2]])
yc = np.repeat(np.arange(K), 60)
Xc = centers[yc] + 0.6 * rng.normal(size=(len(yc), 2))
Xc = np.c_[Xc, np.ones(len(yc))] # (n, 3), last column = bias
W = rng.normal(size=(3, K)) * 0.1 # (d, K): here z = x @ W
f = lambda W: softmax_loss_grad(W, Xc, yc, lam=1e-3)
print(f"[softmax] gradient check relative error = {grad_check(f, W):.2e}")
for t in range(1501):
loss, g = f(W)
W -= 0.5 * g
if t % 500 == 0:
acc = np.mean((Xc @ W).argmax(1) == yc)
print(f" step {t:4d} loss {loss:.4f} acc {acc:.3f}")
z = Xc[:1] @ W # logits of the first sample
print("\nlogit:", np.round(z, 2), " → same probabilities after +100:",
np.allclose(np.exp(log_softmax(z)), np.exp(log_softmax(z + 100))))
for T in [0.25, 1.0, 4.0]:
p = np.exp(log_softmax(z / T))[0]
print(f"T={T:<4} p={np.round(p, 3)} argmax={p.argmax()}")In PyTorch, F.cross_entropy computes log-softmax and NLL in one go, in a numerically stable way. Do not pass probabilities you have already put through softmax — pass the logits.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
K, d = 3, 2
centers = torch.tensor([[-1.4, 0.9], [1.5, 0.7], [0.1, -1.2]])
y = torch.arange(K).repeat_interleave(60)
X = centers[y] + 0.6 * torch.randn(len(y), d)
model = torch.nn.Linear(d, K) # z = W x + b
opt = torch.optim.SGD(model.parameters(), lr=0.5)
for step in range(1501):
logits = model(X) # (n, K) — values before softmax
loss = F.cross_entropy(logits, y) # = mean(-log_softmax(logits)[y])
opt.zero_grad()
loss.backward()
opt.step()
# check that the logit gradient from autograd is (p − onehot)/n
logits = model(X).detach().requires_grad_()
F.cross_entropy(logits, y).backward()
manual = (logits.softmax(-1) - F.one_hot(y, K).float()) / len(y)
print(loss.item(), torch.allclose(logits.grad, manual, atol=1e-7))The softmax output is p = (0.7, 0.2, 0.1) and the correct answer is the second class. What is the gradient of the cross-entropy loss with respect to the logits z?
. Gradient descent moves against the gradient, so the correct logit goes up in proportion to 0.8 and each wrong logit goes down in proportion to its probability. The gradient always sums to 0 (shift invariance).
You divide all logits of a trained classifier by T = 2 and recompute the probabilities. What changes?
The argmax of equals the argmax of , so the decision boundary and accuracy stay the same. What changes is the sharpness of the probabilities, and therefore the NLL (cross-entropy) value and the calibration. Choosing the that minimises the validation-set NLL is temperature scaling.
Summary
- Linear, logistic and softmax regression share one frame — “linear logit + probability model + NLL” — and in every case the gradient with respect to the logit is prediction − target.
- The logistic loss is convex, but on separable data there is no minimiser: ‖w‖ → ∞ and the direction tends to the max margin.
- Softmax is shift-invariant, and its decision boundaries are the hyperplanes . Nonlinear boundaries come from the features .
- Temperature and ‖W‖ change only confidence, never the argmax.
- The LM head is softmax regression. The SFT gradient is ; the policy gradient is that multiplied by the advantage.
- “세 덩어리”에서 학습이 진행되면 경계는 금방 자리를 잡는데 ‖W‖와 색의 진하기는 계속 늘어난다. 경계가 거의 고정된 뒤에도 loss가 줄어드는 것은 확신이 커지기 때문이다.
- 온도 T를 0.1로 내리면 영역이 모두 진해지고, 10으로 올리면 하얗게 빠진다. 경계선은 한 픽셀도 움직이지 않는다.
- “XOR”을 누르면 정확도가 50% 근처에서 멈춘다. 특징을 “이차”로 바꾸면 항 덕분에 바로 풀린다. “고리”는 항으로 풀린다.
- λ를 0.01 이상으로 올리면 ‖W‖가 유한한 값에서 멈추고 색이 옅어진다. L2 정규화는 확신에 상한을 건다.
- A, B, C 버튼으로 클래스를 고르고 캔버스를 클릭해 점을 더해 보자. 한 클래스 영역 깊숙이 다른 클래스 점을 하나 넣으면, 그 점 하나가 경계를 얼마나 끌어당기는지 볼 수 있다.
직접 구현하기
먼저 선형회귀를 정규방정식과 경사하강법으로 풀어 비교한다. 특징 스케일을 일부러 1 : 3 : 0.3으로 달리해 조건수를 키웠다.
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 3
X = np.c_[rng.normal(size=(n, d)) * [1.0, 3.0, 0.3], np.ones(n)] # 마지막 열 = bias
theta_true = np.array([2.0, -1.0, 0.5, 0.3])
y = X @ theta_true + 0.1 * rng.normal(size=n)
theta_ne = np.linalg.solve(X.T @ X, X.T @ y) # 정규방정식
H = X.T @ X / n # (1/2n)||Xθ−y||² 의 Hessian
lam = np.linalg.eigvalsh(H)
lr = 1.0 / lam.max()
theta = np.zeros(d + 1)
for t in range(500):
theta -= lr * X.T @ (X @ theta - y) / n # 기울기 = 평균 (예측−정답)·x
print("정규방정식:", np.round(theta_ne, 4))
print("GD 500 step:", np.round(theta, 4), f" (κ = {lam.max()/lam.min():.0f})")스케일 0.3짜리 특징의 계수(셋째)만 아직 덜 수렴했다. 완만한 방향이 느리다는 경사하강법 레슨의 이야기 그대로다.
로지스틱 회귀는 기울기 를 쓰고, 해석적 기울기가 맞는지 중심 차분으로 검사한다. 새 손실을 구현할 때마다 해 볼 가치가 있는 습관이다.
def sigmoid(z):
return 0.5 * (1 + np.tanh(0.5 * z)) # 1/(1+e^-z) 와 같고 overflow 없음
def logistic_loss_grad(w, X, y):
z = X @ w
p = sigmoid(z)
# −[y log p + (1−y) log(1−p)] = softplus(z) − y z (수치적으로 안정한 꼴)
loss = np.mean(np.logaddexp(0, z) - y * z)
grad = X.T @ (p - y) / len(y) # (p − y) x 의 평균
return loss, grad
def grad_check(f, w, eps=1e-6):
"""중심 차분 (f(w+ε)−f(w−ε))/2ε 로 기울기를 근사해 해석적 기울기와 비교한다."""
_, g = f(w)
g_num = np.zeros_like(w)
for i in range(w.size):
e = np.zeros_like(w); e.flat[i] = eps
g_num.flat[i] = (f(w + e)[0] - f(w - e)[0]) / (2 * eps)
return np.max(np.abs(g - g_num)) / (np.max(np.abs(g)) + 1e-12)
# 겹치는 두 덩어리 (분리 불가능)
n2 = 200
Xb = np.r_[rng.normal([-1, -0.5], 1.0, size=(n2 // 2, 2)), rng.normal([1, 0.8], 1.0, size=(n2 // 2, 2))]
Xb = np.c_[Xb, np.ones(n2)]
yb = np.r_[np.zeros(n2 // 2), np.ones(n2 // 2)]
w = rng.normal(size=3) * 0.1
f = lambda w: logistic_loss_grad(w, Xb, yb)
print(f"[logistic] 기울기 검사 상대오차 = {grad_check(f, w):.2e}")
for t in range(2001):
loss, g = f(w)
w -= 0.5 * g
if t % 500 == 0:
acc = np.mean((Xb @ w > 0) == yb)
print(f" step {t:4d} loss {loss:.4f} acc {acc:.3f} w={np.round(w, 3)}")겹치는 데이터에서는 가 유한한 값으로 수렴한다. 분리 가능한 데이터로 바꾸면 이야기가 달라진다.
Xs = np.c_[np.r_[rng.normal([-2, 0], 0.5, size=(50, 2)), rng.normal([2, 0.5], 0.5, size=(50, 2))], np.ones(100)]
ys = np.r_[np.zeros(50), np.ones(50)]
w = np.zeros(3)
for t in range(1, 20001):
loss, g = logistic_loss_grad(w, Xs, ys)
w -= 1.0 * g
if t in (10, 100, 1000, 10000, 20000):
u = w[:2] / np.linalg.norm(w[:2])
print(f"step {t:6d} loss {loss:.2e} ||w|| {np.linalg.norm(w[:2]):5.2f} 방향 {np.round(u, 3)}")step이 10배 늘 때마다 ‖w‖가 거의 일정한 양만큼 늘어난다( 성장). 방향은 천천히 한 곳(최대 마진 방향)으로 모인다.
Softmax 회귀는 기울기 행렬이 한 줄이다. 를 만들 때 원-핫 행렬을 따로 만들 필요 없이 정답 위치에서 1을 빼면 된다.
def log_softmax(Z):
Z = Z - Z.max(axis=1, keepdims=True) # 이동 불변성 → overflow 방지
return Z - np.log(np.exp(Z).sum(axis=1, keepdims=True))
def softmax_loss_grad(W, X, y, lam=0.0):
n = len(y)
logP = log_softmax(X @ W) # (n, K)
loss = -logP[np.arange(n), y].mean() + 0.5 * lam * np.sum(W[:-1] ** 2)
G = np.exp(logP) # p
G[np.arange(n), y] -= 1 # p − onehot(y) = ∂ℓ/∂z
grad = X.T @ G / n
grad[:-1] += lam * W[:-1] # bias 행은 정규화하지 않는다
return loss, grad
K = 3
centers = np.array([[-1.4, 0.9], [1.5, 0.7], [0.1, -1.2]])
yc = np.repeat(np.arange(K), 60)
Xc = centers[yc] + 0.6 * rng.normal(size=(len(yc), 2))
Xc = np.c_[Xc, np.ones(len(yc))] # (n, 3), 마지막 열 = bias
W = rng.normal(size=(3, K)) * 0.1 # (d, K): 여기서는 z = x @ W
f = lambda W: softmax_loss_grad(W, Xc, yc, lam=1e-3)
print(f"[softmax] 기울기 검사 상대오차 = {grad_check(f, W):.2e}")
for t in range(1501):
loss, g = f(W)
W -= 0.5 * g
if t % 500 == 0:
acc = np.mean((Xc @ W).argmax(1) == yc)
print(f" step {t:4d} loss {loss:.4f} acc {acc:.3f}")
z = Xc[:1] @ W # 첫 표본의 logit
print("\nlogit:", np.round(z, 2), " → +100 해도 같은 확률:",
np.allclose(np.exp(log_softmax(z)), np.exp(log_softmax(z + 100))))
for T in [0.25, 1.0, 4.0]:
p = np.exp(log_softmax(z / T))[0]
print(f"T={T:<4} p={np.round(p, 3)} argmax={p.argmax()}")PyTorch에서는 F.cross_entropy가 log-softmax와 NLL을 한 번에, 수치적으로 안정하게 계산한다. softmax를 먼저 취한 확률을 넣으면 안 된다. logit을 넣는다.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
K, d = 3, 2
centers = torch.tensor([[-1.4, 0.9], [1.5, 0.7], [0.1, -1.2]])
y = torch.arange(K).repeat_interleave(60)
X = centers[y] + 0.6 * torch.randn(len(y), d)
model = torch.nn.Linear(d, K) # z = W x + b
opt = torch.optim.SGD(model.parameters(), lr=0.5)
for step in range(1501):
logits = model(X) # (n, K) — softmax를 취하지 않은 값
loss = F.cross_entropy(logits, y) # = mean(-log_softmax(logits)[y])
opt.zero_grad()
loss.backward()
opt.step()
# autograd가 구한 logit 기울기가 (p − onehot)/n 인지 확인
logits = model(X).detach().requires_grad_()
F.cross_entropy(logits, y).backward()
manual = (logits.softmax(-1) - F.one_hot(y, K).float()) / len(y)
print(loss.item(), torch.allclose(logits.grad, manual, atol=1e-7))softmax 출력이 p = (0.7, 0.2, 0.1)이고 정답이 두 번째 클래스다. cross-entropy 손실의 logit z에 대한 기울기는?
. 경사하강법은 기울기의 반대로 가므로 정답 logit은 0.8에 비례해 올라가고, 오답 logit은 각자의 확률에 비례해 내려간다. 기울기의 합은 항상 0이다(이동 불변성).
학습이 끝난 분류기의 모든 logit을 T = 2로 나누어 확률을 다시 계산했다. 무엇이 바뀌는가?
의 argmax는 의 argmax와 같으니 결정 경계와 정확도는 그대로다. 바뀌는 것은 확률의 날카로움이고, 그래서 NLL(cross-entropy) 값과 보정(calibration)이 바뀐다. 검증 집합의 NLL을 최소화하는 를 고르는 것이 temperature scaling이다.
정리
- 선형회귀·로지스틱·softmax 회귀는 “선형 logit + 확률 모델 + NLL”이라는 같은 틀이고, logit에 대한 기울기는 모두 예측 − 정답이다.
- 로지스틱 손실은 볼록하지만 분리 가능한 데이터에서는 최소점이 없고 ‖w‖ → ∞, 방향은 최대 마진으로 간다.
- softmax는 이동 불변이고 결정 경계는 인 초평면들이다. 비선형 경계는 특징 에서 나온다.
- 온도와 ‖W‖는 확신도만 바꾸고 argmax는 바꾸지 않는다.
- LM head는 softmax 회귀다. SFT 기울기는 , 정책 경사는 그것에 advantage를 곱한 것이다.
더 읽을거리Further reading
- Bishop, Pattern Recognition and Machine Learning §3.1, §4.3 (Springer, 2006) — 선형 기저함수 모델, 로지스틱·softmax 회귀와 그 기울기·Hessian.Linear basis-function models, logistic and softmax regression with their gradients and Hessians.
- Hastie, Tibshirani, Friedman, The Elements of Statistical Learning Ch. 3–4 (2nd ed., 2009) — 최소제곱의 기하학과 선형 분류기의 고전적 정리.The geometry of least squares and the classic treatment of linear classifiers.
- Murphy, Probabilistic Machine Learning: An Introduction, Ch. 10–11 (MIT Press, 2022) — 로지스틱 회귀와 선형회귀를 같은 확률적 틀로 다룬다.Treats logistic and linear regression in the same probabilistic framework.
- Soudry, Hoffer, Nacson, Gunasekar, Srebro, The Implicit Bias of Gradient Descent on Separable Data (JMLR 2018) — 분리 가능한 데이터에서 로지스틱 회귀의 ‖w‖는 log t로 커지고 방향은 최대 마진 해로 수렴한다.On separable data the ‖w‖ of logistic regression grows like log t while its direction converges to the max-margin solution.
- Guo, Pleiss, Sun, Weinberger, On Calibration of Modern Neural Networks (ICML 2017) — 온도 하나로 logit을 나누는 temperature scaling이 보정(calibration)을 크게 개선한다.Temperature scaling — dividing the logits by a single temperature — greatly improves calibration.
- Hinton, Vinyals, Dean, Distilling the Knowledge in a Neural Network (2015) — softmax 온도를 올려 교사의 "어두운 지식"을 드러내는 증류.Distillation that raises the softmax temperature to reveal the teacher's "dark knowledge".