Track I · ML Fundamentals · 04/09

선형 모델Linear models

선형회귀·로지스틱 회귀·softmax 회귀를 하나의 틀(특징 위의 선형 logit + 확률 모델)로 보고, cross-entropy의 기울기가 왜 항상 "예측 − 정답"인지 유도한다. 온도와 logit 크기가 확신도만 바꾸는 이유, 그리고 LLM의 LM head가 곧 softmax 회귀라는 점을 설명할 수 있게 된다.View linear, logistic and softmax regression in one frame (a linear logit on features plus a probability model) and derive why the cross-entropy gradient is always "prediction − target". You will be able to explain why temperature and logit scale change only confidence, and why an LLM's LM head is softmax regression.

35 분min linear regression · logistic regression · softmax · cross-entropy gradient · decision boundary · temperature · feature map 먼저 볼 것:Before this: 경사하강법Gradient descent, 확률로 보는 손실Losses through probability

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 hh, 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.

ModelOutputProbability modelLoss (NLL)Gradient w.r.t. the logit
Linear regressionz=θ⊤x∈Rz = \theta^\top x \in \mathbb{R}N(y;z,σ2)\mathcal N(y; z, \sigma^2)12(z−y)2\tfrac12(z - y)^2z−yz - y
Logistic regressionz=w⊤xz = w^\top x, p=σ(z)p = \sigma(z)Bernoulli(p)\text{Bernoulli}(p)−ylog⁡p−(1−y)log⁡(1−p)-y\log p - (1-y)\log(1-p)p−yp - y
Softmax regressionz=Wx∈RKz = Wx \in \mathbb{R}^K, p=softmax(z)p = \text{softmax}(z)Categorical(p)\text{Categorical}(p)−log⁡py-\log p_yp−eyp - e_y

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 θ\theta by appending a constant 1 to xx.

Linear regression

The gradient of R^(θ)=12n∥Xθ−y∥2\hat R(\theta) = \frac{1}{2n}\|X\theta - y\|^2 is 1nX⊤(Xθ−y)\frac1n X^\top(X\theta - y), the average over samples of “(prediction − target) × input”. Setting it to 0 gives the normal equations X⊤Xθ=X⊤yX^\top X\theta = X^\top y from the first lesson.

Solved by gradient descent, the Hessian is H=1nX⊤XH = \frac1n X^\top X, the second-moment matrix of the inputs. Applying the results of the gradient descent lesson directly, the learning rate must be below 2/λmax⁡(H)2/\lambda_{\max}(H) and the convergence speed is set by κ(H)\kappa(H). If the input features have very different scales (say, height in cm and income in won), κ\kappa 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 z=w⊤xz = w^\top x directly as a probability. We squash it into (0,1)(0, 1) with the sigmoid.

p=σ(z)=11+e−z,z=log⁡p1−pp = \sigma(z) = \frac{1}{1 + e^{-z}}, \qquad z = \log\frac{p}{1-p}

The second equation is the key to interpretation: the logit zz is the log-odds. Logistic regression is the model “the log-odds are linear in the input”. Increasing the input xjx_j by 1 multiplies the odds by ewje^{w_j}.

Let us find the gradient. The derivative of the sigmoid is σ′(z)=σ(z)(1−σ(z))=p(1−p)\sigma'(z) = \sigma(z)(1 - \sigma(z)) = p(1-p). Differentiating the loss ℓ=−ylog⁡p−(1−y)log⁡(1−p)\ell = -y\log p - (1-y)\log(1-p) with respect to zz,

∂ℓ∂z=−yp p(1−p)+1−y1−p p(1−p)=−y(1−p)+(1−y)p=p−y.\frac{\partial \ell}{\partial z} = -\frac{y}{p}\,p(1-p) + \frac{1-y}{1-p}\,p(1-p) = -y(1-p) + (1-y)p = p - y.

The p(1−p)p(1-p) cancels cleanly. By the chain rule, ∇wℓ=(p−y) x\nabla_w \ell = (p - y)\,x. Had we put an MSE on the sigmoid output, a factor p(1−p)p(1-p) would remain in the gradient, and the gradient would vanish when pp 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 ∇w2R^=1n∑ipi(1−pi) xixi⊤⪰0\nabla^2_w \hat R = \frac1n\sum_i p_i(1-p_i)\,x_i x_i^\top \succeq 0, 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 KK classes we make KK logits. z=Wxz = Wx; the kk-th row wkw_k of W∈RK×dW \in \mathbb{R}^{K \times d} is the “score vector” of class kk.

pk=softmax(z)k=ezk∑jezj,ℓ=−log⁡py=−zy+log⁡∑jezjp_k = \text{softmax}(z)_k = \frac{e^{z_k}}{\sum_{j} e^{z_j}}, \qquad \ell = -\log p_y = -z_y + \log\sum_j e^{z_j}

The derivative falls straight out of the second form (subtract the correct logit, add the log-sum-exp). Since ∂∂zklog⁡∑jezj=ezk∑jezj=pk\frac{\partial}{\partial z_k}\log\sum_j e^{z_j} = \frac{e^{z_k}}{\sum_j e^{z_j}} = p_k,

∂ℓ∂zk=pk−1[k=y],∇zℓ=p−ey,∇Wℓ=(p−ey) x⊤.\frac{\partial \ell}{\partial z_k} = p_k - \mathbb{1}[k = y], \qquad \nabla_z \ell = p - e_y, \qquad \nabla_W \ell = (p - e_y)\, x^\top.

How to read it: the logit of the correct class goes up by 1−py1 - p_y, and every other logit goes down by its own probability pkp_k. If the model is already confidently right (py≈1p_y \approx 1), the update is almost 0.

Several properties follow directly from this formula.

  • Shift invariance: adding the same constant cc to every logit leaves pp unchanged. That is why implementations first compute z−max⁡kzkz - \max_k z_k to prevent overflow (the log-sum-exp trick). For the same reason one of the KK rows is redundant, and with K=2K = 2, p1=σ(z1−z2)p_1 = \sigma(z_1 - z_2), which is the same as logistic regression.
  • Decision boundaries: the boundary between classes ii and jj is zi=zjz_i = z_j, i.e. the hyperplane (wi−wj)⊤x=0(w_i - w_j)^\top x = 0. 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 ϕ(x)\phi(x) instead of xx, the model is still linear in ϕ\phi. The boundary is a hyperplane in ϕ\phi-space but a curve in the original xx-space. Neural networks learn this ϕ\phi itself (Track II).

Temperature and logit scale

Consider softmax(z/T)\text{softmax}(z/T), the logits divided by a temperature T>0T > 0. As T→0T \to 0 it becomes one-hot with all mass on the argmax; as T→∞T \to \infty it becomes uniform. But the argmax does not depend on TT. Temperature changes only confidence, not the decision boundary.

Seen the other way, scaling WW by cc is the same as lowering the temperature to 1/c1/c. ‖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가 하는 일은 결국 좋은 특징 벡터 hh를 만드는 것이고, 그 위에서 다음 토큰을 고르는 LM head는 이 레슨의 softmax 회귀 그 자체다. 그러니 softmax 회귀의 기울기, 온도, logit 크기를 정확히 이해해 두면 SFT와 RL의 업데이트가 logit에 무슨 일을 하는지 바로 읽힌다.

세 모델은 같은 틀을 공유한다.

모델출력확률 모델손실 (NLL)logit에 대한 기울기
선형회귀z=θ⊤x∈Rz = \theta^\top x \in \mathbb{R}N(y;z,σ2)\mathcal N(y; z, \sigma^2)12(z−y)2\tfrac12(z - y)^2z−yz - y
로지스틱 회귀z=w⊤xz = w^\top x, p=σ(z)p = \sigma(z)Bernoulli(p)\text{Bernoulli}(p)−ylog⁡p−(1−y)log⁡(1−p)-y\log p - (1-y)\log(1-p)p−yp - y
softmax 회귀z=Wx∈RKz = Wx \in \mathbb{R}^K, p=softmax(z)p = \text{softmax}(z)Categorical(p)\text{Categorical}(p)−log⁡py-\log p_yp−eyp - e_y

마지막 열이 이 레슨의 주인공이다. 세 경우 모두 기울기가 “예측 − 정답” 이다. 우연이 아니다. 이 세 분포가 모두 지수족(exponential family)이고 각자의 “정준(canonical)” 연결함수를 썼기 때문이다. 아래에서 하나씩 유도한다. 편의상 bias는 xx에 상수 1을 붙여 θ\theta 안에 넣는다.

선형회귀

R^(θ)=12n∥Xθ−y∥2\hat R(\theta) = \frac{1}{2n}\|X\theta - y\|^2의 기울기는 1nX⊤(Xθ−y)\frac1n X^\top(X\theta - y), 즉 표본별 “(예측 − 정답) × 입력”의 평균이다. 0으로 놓으면 첫 레슨의 정규방정식 X⊤Xθ=X⊤yX^\top X\theta = X^\top y가 나온다.

경사하강법으로 풀면 Hessian이 H=1nX⊤XH = \frac1n X^\top X, 즉 입력의 2차 모멘트 행렬이다. 경사하강법 레슨의 결과를 그대로 쓰면 학습률은 2/λmax⁡(H)2/\lambda_{\max}(H) 미만이어야 하고, 수렴 속도는 κ(H)\kappa(H)가 정한다. 입력 특징의 스케일이 크게 다르면(예: 키는 cm, 소득은 원) κ\kappa가 커져 학습이 느려진다. 특징을 표준화(평균 0, 분산 1)하는 전처리가 그래서 중요하고, 딥러닝에서 정규화 층(LayerNorm 등)이 하는 역할 중 하나도 이것이다.

로지스틱 회귀

이진 분류에서 z=w⊤xz = w^\top x를 그대로 확률로 쓸 수는 없다. sigmoid로 (0,1)(0, 1)에 눌러 넣는다.

p=σ(z)=11+e−z,z=log⁡p1−pp = \sigma(z) = \frac{1}{1 + e^{-z}}, \qquad z = \log\frac{p}{1-p}

둘째 식이 해석의 열쇠다. logit zz는 log-odds다. 로지스틱 회귀는 “log-odds가 입력에 대해 선형”이라는 모델이다. 입력 xjx_j가 1 늘면 odds가 ewje^{w_j}배가 된다.

기울기를 구하자. sigmoid의 도함수는 σ′(z)=σ(z)(1−σ(z))=p(1−p)\sigma'(z) = \sigma(z)(1 - \sigma(z)) = p(1-p)다. 손실 ℓ=−ylog⁡p−(1−y)log⁡(1−p)\ell = -y\log p - (1-y)\log(1-p)를 zz로 미분하면

∂ℓ∂z=−yp p(1−p)+1−y1−p p(1−p)=−y(1−p)+(1−y)p=p−y.\frac{\partial \ell}{\partial z} = -\frac{y}{p}\,p(1-p) + \frac{1-y}{1-p}\,p(1-p) = -y(1-p) + (1-y)p = p - y.

p(1−p)p(1-p)가 깔끔하게 지워진다. 연쇄법칙으로 ∇wℓ=(p−y) x\nabla_w \ell = (p - y)\,x. MSE를 sigmoid 출력에 붙였다면 기울기에 p(1−p)p(1-p)가 남아 pp가 0이나 1 근처에서 기울기가 사라졌을 것이다. 크게 틀렸는데도 배우지 못하는 상황이다. cross-entropy는 log가 sigmoid의 포화를 정확히 상쇄한다.

Hessian은 ∇w2R^=1n∑ipi(1−pi) xixi⊤⪰0\nabla^2_w \hat R = \frac1n\sum_i p_i(1-p_i)\,x_i x_i^\top \succeq 0이므로 손실은 볼록하다. 국소 최소가 곧 전역 최소다. 다만 닫힌 해는 없어서 반복법(GD, 뉴턴법)을 쓴다.

Softmax 회귀

클래스가 KK개면 logit을 KK개 만든다. z=Wxz = Wx, W∈RK×dW \in \mathbb{R}^{K \times d}의 kk번째 행 wkw_k가 클래스 kk의 “점수 벡터”다.

pk=softmax(z)k=ezk∑jezj,ℓ=−log⁡py=−zy+log⁡∑jezjp_k = \text{softmax}(z)_k = \frac{e^{z_k}}{\sum_{j} e^{z_j}}, \qquad \ell = -\log p_y = -z_y + \log\sum_j e^{z_j}

두 번째 꼴(정답 logit을 빼고 log-sum-exp를 더함)에서 미분이 바로 나온다. ∂∂zklog⁡∑jezj=ezk∑jezj=pk\frac{\partial}{\partial z_k}\log\sum_j e^{z_j} = \frac{e^{z_k}}{\sum_j e^{z_j}} = p_k이므로

∂ℓ∂zk=pk−1[k=y],∇zℓ=p−ey,∇Wℓ=(p−ey) x⊤.\frac{\partial \ell}{\partial z_k} = p_k - \mathbb{1}[k = y], \qquad \nabla_z \ell = p - e_y, \qquad \nabla_W \ell = (p - e_y)\, x^\top.

읽는 법: 정답 클래스의 logit은 1−py1 - p_y만큼 올라가고, 나머지 클래스의 logit은 각자의 확률 pkp_k만큼 내려간다. 이미 맞게 확신하고 있으면(py≈1p_y \approx 1) 업데이트는 거의 0이다.

몇 가지 성질이 이 식에서 바로 나온다.

  • 이동 불변성: 모든 logit에 같은 상수 cc를 더해도 pp는 그대로다. 그래서 구현할 때 z−max⁡kzkz - \max_k z_k를 먼저 빼서 overflow를 막는다(log-sum-exp trick). 같은 이유로 KK개의 행 중 하나는 군더더기이고, K=2K = 2이면 p1=σ(z1−z2)p_1 = \sigma(z_1 - z_2)로 로지스틱 회귀와 같아진다.
  • 결정 경계: 클래스 ii와 jj의 경계는 zi=zjz_i = z_j, 즉 (wi−wj)⊤x=0(w_i - w_j)^\top x = 0인 초평면이다. 각 클래스의 영역은 반공간들의 교집합이라 볼록 다면체다. 선형 모델로는 볼록하지 않은 영역(XOR, 고리)을 만들 수 없다.
  • 특징에 대해 선형: xx 대신 고정된 특징 ϕ(x)\phi(x)를 넣으면 모델은 여전히 ϕ\phi에 대해 선형이다. 경계는 ϕ\phi 공간에서 초평면이지만 원래 xx 공간에서는 곡선이다. 신경망은 이 ϕ\phi 자체를 학습한다(Track II).

온도와 logit 크기

logit을 온도 T>0T > 0으로 나눈 softmax(z/T)\text{softmax}(z/T)를 생각하자. T→0T \to 0이면 argmax에 질량이 몰린 원-핫, T→∞T \to \infty이면 균등분포가 된다. 그런데 argmax는 TT와 무관하다. 즉 온도는 결정 경계를 바꾸지 않고 확신도만 바꾼다.

거꾸로 보면 WW를 cc배 하는 것은 온도를 1/c1/c로 낮추는 것과 같다. ‖W‖가 곧 모델의 확신도다. 분리 가능한 데이터에서 ‖W‖가 끝없이 커진다는 말은, 경계는 거의 그대로인데 확신만 무한히 강해진다는 뜻이다. 신경망이 과도하게 확신하는(miscalibrated) 경향과, 학습 후에 온도 하나만 맞춰 보정하는 temperature scaling(Guo et al., 2017)이 모두 이 관찰에서 나온다.

그림으로

클릭하면 추가:Click to add: |
step 0 loss – 정확도accuracy – ‖W‖ – 평균 max p (온도 T)mean max p (temp. T) –
The colour intensity is the highest probability the model assigns at that location, and the black boundary is where the argmax changes. On "XOR" or "Ring", no combination of straight lines separates the classes with linear features. Switch the features to "quadratic" and the same linear model draws curved boundaries (the model is linear only in its features). If the data is separable the loss keeps falling and ‖W‖ grows without bound; raising λ stops it. The temperature T only divides the logits by T, so the boundary stays put and only the colour intensity (confidence) changes. 색의 진하기는 그 위치에서 모델이 가장 높게 준 확률이고, 검은 경계선은 argmax가 바뀌는 곳이다. "XOR"이나 "고리"에서 선형 특징으로는 어떤 직선 조합으로도 분리되지 않는다. 특징을 "이차"로 바꾸면 같은 선형 모델이 곡선 경계를 그린다(모델은 특징에 대해서만 선형이다). 데이터가 분리 가능하면 loss는 계속 줄고 ‖W‖는 끝없이 커진다. λ를 올리면 멈춘다. 온도 T는 logit을 T로 나눌 뿐이라 경계선은 그대로이고 색의 진하기(확신도)만 바뀐다.
  1. 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.
  2. 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.
  3. Press “XOR” and accuracy stalls around 50%. Switch the features to “quadratic” and the x1x2x_1x_2 term solves it right away. “Ring” is solved by the x12+x22x_1^2 + x_2^2 terms.
  4. Raise λ to 0.01 or more and ‖W‖ stops at a finite value and the colours fade. L2 regularisation puts a ceiling on confidence.
  5. 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.

NumPy Linear regression: normal equations vs gradient descent
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 (p−y)x(p - y)x, 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.

NumPy Logistic regression + gradient check
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, ww converges to a finite value. Switch to separable data and the story changes.

NumPy Separable data: ‖w‖ grows like log t
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 (log⁡t\log t growth). The direction slowly gathers toward one place (the max-margin direction).

For softmax regression the gradient matrix is a single line, X⊤(P−Y)/nX^\top(P - Y)/n. To form P−YP - Y you do not need to build a one-hot matrix; just subtract 1 at the position of the correct class.

NumPy Softmax regression + gradient check + temperature
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.

PyTorch PyTorch: softmax regression 로컬에서 실행run locally (pip install torch)
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))
 
확인 문제Check yourself

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?

∇zℓ=p−ey=(0.7,0.2,0.1)−(0,1,0)=(0.7,−0.8,0.1)\nabla_z \ell = p - e_y = (0.7, 0.2, 0.1) - (0, 1, 0) = (0.7, -0.8, 0.1). 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).

확인 문제Check yourself

You divide all logits of a trained classifier by T = 2 and recompute the probabilities. What changes?

The argmax of z/Tz/T equals the argmax of zz, 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 TT 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 (wi−wj)⊤x=0(w_i - w_j)^\top x = 0. Nonlinear boundaries come from the features ϕ(x)\phi(x).
  • Temperature and ‖W‖ change only confidence, never the argmax.
  • The LM head is softmax regression. The SFT gradient is p−eyp - e_y; the policy gradient is that multiplied by the advantage.
  1. “세 덩어리”에서 학습이 진행되면 경계는 금방 자리를 잡는데 ‖W‖와 색의 진하기는 계속 늘어난다. 경계가 거의 고정된 뒤에도 loss가 줄어드는 것은 확신이 커지기 때문이다.
  2. 온도 T를 0.1로 내리면 영역이 모두 진해지고, 10으로 올리면 하얗게 빠진다. 경계선은 한 픽셀도 움직이지 않는다.
  3. “XOR”을 누르면 정확도가 50% 근처에서 멈춘다. 특징을 “이차”로 바꾸면 x1x2x_1x_2 항 덕분에 바로 풀린다. “고리”는 x12+x22x_1^2 + x_2^2 항으로 풀린다.
  4. λ를 0.01 이상으로 올리면 ‖W‖가 유한한 값에서 멈추고 색이 옅어진다. L2 정규화는 확신에 상한을 건다.
  5. A, B, C 버튼으로 클래스를 고르고 캔버스를 클릭해 점을 더해 보자. 한 클래스 영역 깊숙이 다른 클래스 점을 하나 넣으면, 그 점 하나가 경계를 얼마나 끌어당기는지 볼 수 있다.

직접 구현하기

먼저 선형회귀를 정규방정식과 경사하강법으로 풀어 비교한다. 특징 스케일을 일부러 1 : 3 : 0.3으로 달리해 조건수를 키웠다.

NumPy 선형회귀: 정규방정식 vs 경사하강법
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짜리 특징의 계수(셋째)만 아직 덜 수렴했다. 완만한 방향이 느리다는 경사하강법 레슨의 이야기 그대로다.

로지스틱 회귀는 기울기 (p−y)x(p - y)x를 쓰고, 해석적 기울기가 맞는지 중심 차분으로 검사한다. 새 손실을 구현할 때마다 해 볼 가치가 있는 습관이다.

NumPy 로지스틱 회귀 + 기울기 검사
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)}")
 

겹치는 데이터에서는 ww가 유한한 값으로 수렴한다. 분리 가능한 데이터로 바꾸면 이야기가 달라진다.

NumPy 분리 가능한 데이터: ‖w‖는 log t로 자란다
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‖가 거의 일정한 양만큼 늘어난다(log⁡t\log t 성장). 방향은 천천히 한 곳(최대 마진 방향)으로 모인다.

Softmax 회귀는 기울기 행렬이 X⊤(P−Y)/nX^\top(P - Y)/n 한 줄이다. P−YP - Y를 만들 때 원-핫 행렬을 따로 만들 필요 없이 정답 위치에서 1을 빼면 된다.

NumPy Softmax 회귀 + 기울기 검사 + 온도
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을 넣는다.

PyTorch PyTorch: softmax 회귀 로컬에서 실행run locally (pip install torch)
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))
 
확인 문제Check yourself

softmax 출력이 p = (0.7, 0.2, 0.1)이고 정답이 두 번째 클래스다. cross-entropy 손실의 logit z에 대한 기울기는?

∇zℓ=p−ey=(0.7,0.2,0.1)−(0,1,0)=(0.7,−0.8,0.1)\nabla_z \ell = p - e_y = (0.7, 0.2, 0.1) - (0, 1, 0) = (0.7, -0.8, 0.1). 경사하강법은 기울기의 반대로 가므로 정답 logit은 0.8에 비례해 올라가고, 오답 logit은 각자의 확률에 비례해 내려간다. 기울기의 합은 항상 0이다(이동 불변성).

확인 문제Check yourself

학습이 끝난 분류기의 모든 logit을 T = 2로 나누어 확률을 다시 계산했다. 무엇이 바뀌는가?

z/Tz/T의 argmax는 zz의 argmax와 같으니 결정 경계와 정확도는 그대로다. 바뀌는 것은 확률의 날카로움이고, 그래서 NLL(cross-entropy) 값과 보정(calibration)이 바뀐다. 검증 집합의 NLL을 최소화하는 TT를 고르는 것이 temperature scaling이다.

정리

  • 선형회귀·로지스틱·softmax 회귀는 “선형 logit + 확률 모델 + NLL”이라는 같은 틀이고, logit에 대한 기울기는 모두 예측 − 정답이다.
  • 로지스틱 손실은 볼록하지만 분리 가능한 데이터에서는 최소점이 없고 ‖w‖ → ∞, 방향은 최대 마진으로 간다.
  • softmax는 이동 불변이고 결정 경계는 (wi−wj)⊤x=0(w_i - w_j)^\top x = 0인 초평면들이다. 비선형 경계는 특징 ϕ(x)\phi(x)에서 나온다.
  • 온도와 ‖W‖는 확신도만 바꾸고 argmax는 바꾸지 않는다.
  • LM head는 softmax 회귀다. SFT 기울기는 p−eyp - e_y, 정책 경사는 그것에 advantage를 곱한 것이다.

더 읽을거리Further reading