Track I · ML Fundamentals · 05/09

일반화Generalization

test 오차를 편향²·분산·잡음으로 정확히 분해하고, L2 정규화(=가우시안 사전분포의 MAP)·early stopping·교차검증이 그 균형을 어떻게 옮기는지 유도한다. 매개변수가 데이터보다 많아질 때 test 오차가 다시 내려가는 double descent를 직접 계산해 본다.Decompose the test error exactly into bias², variance and noise, and derive how L2 regularisation (= MAP with a Gaussian prior), early stopping and cross-validation shift that balance. Then compute double descent yourself, where the test error falls again once there are more parameters than data points.

40 분min bias-variance · ridge · weight decay · MAP · early stopping · cross-validation · double descent · overparameterization 먼저 볼 것:Before this: 학습이란 무엇인가What is learning?, 선형 모델Linear models

In the first lesson we only described in words the tug-of-war “a big model inflates the estimation error, a small one the approximation error”. This lesson turns it into an exact equation. Next it derives the knobs that shift that balance (regularisation, early stopping, cross-validation), and finally it looks at where that classical picture breaks: the regime with more parameters than data points. Today’s neural networks and LLMs all live there.

The bias–variance decomposition

The setting: a true function ff, observations y=f(x)+εy = f(x) + \varepsilon with E[ε]=0\mathbb{E}[\varepsilon] = 0 and Var⁡[ε]=σ2\operatorname{Var}[\varepsilon] = \sigma^2. The training set D\mathcal{D} is a random variable, and so is the predictor f^D\hat f_{\mathcal D} learned from it. At a fixed input xx, average the expected squared error on a new observation yy over both D\mathcal D and ε\varepsilon. Write the average predictor as fˉ(x)=ED[f^D(x)]\bar f(x) = \mathbb{E}_{\mathcal D}[\hat f_{\mathcal D}(x)]; adding and subtracting gives

y−f^D(x)=ε⏟noise+(f(x)−fˉ(x))⏟bias+(fˉ(x)−f^D(x))⏟fluctuation.y - \hat f_{\mathcal D}(x) = \underbrace{\varepsilon}_{\text{noise}} + \underbrace{\big(f(x) - \bar f(x)\big)}_{\text{bias}} + \underbrace{\big(\bar f(x) - \hat f_{\mathcal D}(x)\big)}_{\text{fluctuation}}.

Square and take expectations and all the cross terms vanish: ε\varepsilon is the noise of the new observation, so it is independent of D\mathcal D and has mean 0; the fluctuation term averages to 0 under ED\mathbb{E}_{\mathcal D} by definition; and the bias term is constant with respect to D\mathcal D. What remains is

ED,ε[(y−f^D(x))2]=σ2⏟irreducible noise+(f(x)−fˉ(x))2⏟bias2+ED[(f^D(x)−fˉ(x))2]⏟variance.\mathbb{E}_{\mathcal D, \varepsilon}\big[(y - \hat f_{\mathcal D}(x))^2\big] = \underbrace{\sigma^2}_{\text{irreducible noise}} + \underbrace{\big(f(x) - \bar f(x)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}_{\mathcal D}\big[(\hat f_{\mathcal D}(x) - \bar f(x))^2\big]}_{\text{variance}}.
  • Bias: how wrong even the predictor averaged over infinitely many redrawn datasets is. Large when the hypothesis class is too small or the regularisation too strong.
  • Variance: how much the predictor wobbles when the dataset changes. Large when the model is big and the data scarce.
  • Noise: no model can remove it. It is the same thing as H(p)H(p) in the previous lesson and the σ2\sigma^2 floor in the first lesson.

This decomposition is this clean only for the squared loss. The 0–1 loss and cross-entropy have similar decompositions, but their terms do not simply add up. Still, the intuition “wrong on average vs. wobbling from sample to sample” carries over unchanged.

첫 레슨에서 우리는 “모델이 크면 추정 오차가, 작으면 근사 오차가 커진다”는 줄다리기를 말로만 했다. 이 레슨은 그것을 정확한 등식으로 만든다. 그다음 그 균형을 옮기는 손잡이들(정규화, early stopping, 교차검증)을 유도하고, 마지막으로 그 고전적 그림이 깨지는 곳, 즉 매개변수가 데이터보다 많은 영역을 본다. 오늘날의 신경망과 LLM은 모두 그 영역에 산다.

편향–분산 분해

설정은 이렇다. 참 함수 ff, 관측 y=f(x)+εy = f(x) + \varepsilon, E[ε]=0\mathbb{E}[\varepsilon] = 0, Var⁡[ε]=σ2\operatorname{Var}[\varepsilon] = \sigma^2. 훈련 집합 D\mathcal{D}는 확률변수이고, 거기서 학습한 예측기 f^D\hat f_{\mathcal D}도 확률변수다. 고정된 입력 xx에서 새로운 관측 yy에 대한 기대 제곱 오차를 D\mathcal D와 ε\varepsilon 모두에 대해 평균 내자. 평균 예측기를 fˉ(x)=ED[f^D(x)]\bar f(x) = \mathbb{E}_{\mathcal D}[\hat f_{\mathcal D}(x)]라 두고 더하고 빼면

y−f^D(x)=ε⏟잡음+(f(x)−fˉ(x))⏟편향+(fˉ(x)−f^D(x))⏟요동.y - \hat f_{\mathcal D}(x) = \underbrace{\varepsilon}_{\text{잡음}} + \underbrace{\big(f(x) - \bar f(x)\big)}_{\text{편향}} + \underbrace{\big(\bar f(x) - \hat f_{\mathcal D}(x)\big)}_{\text{요동}}.

제곱해서 기댓값을 취하면 교차항이 모두 사라진다. ε\varepsilon은 새 관측의 잡음이라 D\mathcal D와 독립이고 평균이 0이며, 요동 항은 정의상 ED\mathbb{E}_{\mathcal D}로 평균 내면 0이고, 편향 항은 D\mathcal D에 대해 상수이기 때문이다. 남는 것은

ED,ε[(y−f^D(x))2]=σ2⏟줄일 수 없는 잡음+(f(x)−fˉ(x))2⏟편향2+ED[(f^D(x)−fˉ(x))2]⏟분산.\mathbb{E}_{\mathcal D, \varepsilon}\big[(y - \hat f_{\mathcal D}(x))^2\big] = \underbrace{\sigma^2}_{\text{줄일 수 없는 잡음}} + \underbrace{\big(f(x) - \bar f(x)\big)^2}_{\text{편향}^2} + \underbrace{\mathbb{E}_{\mathcal D}\big[(\hat f_{\mathcal D}(x) - \bar f(x))^2\big]}_{\text{분산}}.
  • 편향(bias): 데이터를 무한히 다시 뽑아 평균 낸 예측기조차 틀리는 정도. 가설 집합이 너무 작거나 정규화가 너무 셀 때 크다.
  • 분산(variance): 데이터셋을 바꿀 때 예측기가 흔들리는 정도. 모델이 크고 데이터가 적을 때 크다.
  • 잡음: 어떤 모델로도 없앨 수 없다. 이전 레슨의 H(p)H(p), 첫 레슨의 σ2\sigma^2 바닥과 같은 것이다.

이 분해는 제곱 손실에서만 이렇게 깔끔하다. 0–1 손실이나 cross-entropy에도 비슷한 분해가 있지만 항들이 더해지는 꼴이 아니다. 그래도 “평균적으로 틀림 vs 표본에 따라 흔들림”이라는 직관은 그대로 쓸 수 있다.

We draw 40 fresh training sets of size n and fit each with ridge regression (24 Gaussian basis functions). The thin red lines are the individual fits, the thick line is their mean, and the dashed line is the true function. Shrink λ and the fits swing about independently (variance↑). Grow λ and they all look alike, but their mean drifts away from the true function (bias↑). In the right-hand curve there is a λ where their sum is smallest. Grow n and the whole variance curve drops, so a smaller λ becomes optimal. 크기 n인 훈련 집합을 40번 새로 뽑아 각각 ridge 회귀(가우시안 기저 24개)로 맞췄다. 빨간 가는 선이 각 적합, 굵은 선이 그 평균, 점선이 참 함수다. λ를 줄이면 적합들이 제각각 출렁인다(분산↑). λ를 키우면 모두 비슷해지지만 평균이 참 함수에서 멀어진다(편향↑). 오른쪽 곡선에서 둘의 합이 최소가 되는 λ가 있다. n을 키우면 분산 곡선 전체가 내려가 더 작은 λ가 최적이 된다.
  1. Lower log₁₀ λ to −4 and the thin red lines each run wild. Their mean (the thick line), on the other hand, is very close to the true function. Low bias, high variance.
  2. Raise log₁₀ λ to 2 and every fit becomes nearly the same flat curve. Low variance, high bias.
  3. In between, around λ ≈ 1, the black curve (bias² + variance + σ²) is at its minimum. Watch how the proportions of the three components change in the bar below.
  4. Raise n to 100 and the whole variance curve drops and the optimal λ moves left. The more data, the less regularisation is needed.

L2 regularisation = a Gaussian prior

Let us see what λ really is. Ridge regression minimises 12∥Xθ−y∥2+λ2∥θ∥2\frac12\|X\theta - y\|^2 + \frac\lambda2\|\theta\|^2, with closed-form solution θ^λ=(X⊤X+λI)−1X⊤y\hat\theta_\lambda = (X^\top X + \lambda I)^{-1}X^\top y.

Through the spectrum you can see exactly what it does. Writing X=USV⊤X = U S V^\top (SVD, singular values sis_i),

Xθ^λ=∑iui si2si2+λ ui⊤y.X\hat\theta_\lambda = \sum_i u_i \,\frac{s_i^2}{s_i^2 + \lambda}\, u_i^\top y .

Least squares (λ=0\lambda = 0) uses the component along each direction as is, while ridge multiplies by si2/(si2+λ)s_i^2/(s_i^2 + \lambda), pressing toward 0 the directions the data says little about (small sis_i). The coefficients in those directions were the ones swinging wildly with the noise, so this is a trade: accept a little bias to cut the variance a lot.

Probabilistically, this term is a prior. Put the prior θ∼N(0,τ2I)\theta \sim \mathcal N(0, \tau^2 I) on the likelihood y∣X,θ∼N(Xθ,σ2I)y \mid X, \theta \sim \mathcal N(X\theta, \sigma^2 I) and maximise the posterior (MAP, maximum a posteriori):

−log⁡p(θ∣D)=12σ2∥Xθ−y∥2+12τ2∥θ∥2+const⟹λ=σ2τ2.-\log p(\theta \mid \mathcal D) = \frac{1}{2\sigma^2}\|X\theta - y\|^2 + \frac{1}{2\tau^2}\|\theta\|^2 + \text{const} \quad\Longrightarrow\quad \lambda = \frac{\sigma^2}{\tau^2}.

Just as MSE was a Gaussian likelihood in the previous lesson, the L2 term is the Gaussian belief “θ is probably near 0”. The larger the noise and the stronger the prior belief (the smaller τ\tau), the larger λ. By the same logic, a Laplace prior gives L1 (the lasso).

Through gradient descent, the L2 term shrinks the weights by a fixed fraction every step.

θ←θ−η(∇L(θ)+λθ)=(1−ηλ) θ−η∇L(θ)\theta \leftarrow \theta - \eta\big(\nabla L(\theta) + \lambda\theta\big) = (1 - \eta\lambda)\,\theta - \eta\nabla L(\theta)

Hence the name weight decay. With SGD, L2 regularisation and weight decay are the same thing, but with optimisers that scale the gradient differently per coordinate, like Adam, the two diverge. That is why AdamW exists; we look at it closely in the optimizers lesson.

Early stopping is regularisation too

Stopping gradient descent partway instead of running it to the end has the same effect. Run least squares from θ0=0\theta_0 = 0 for tt steps with learning rate η\eta and the component along each singular direction converges independently (exactly the eigen-decomposition of the gradient descent lesson). Putting it together,

Xθt=∑iui [1−(1−ηsi2)t]⏟≈ 1−e−ηtsi2 ui⊤y.X\theta_t = \sum_i u_i\, \underbrace{\big[1 - (1 - \eta s_i^2)^t\big]}_{\approx\, 1 - e^{-\eta t s_i^2}}\, u_i^\top y .

It has the same shape as the ridge filter si2/(si2+λ)s_i^2/(s_i^2 + \lambda). Directions with large sis_i quickly approach 1, and directions with small sis_i stay near 0. Both switch from 0 to 1 around si2≈λ≈1/(ηt)s_i^2 \approx \lambda \approx 1/(\eta t). In other words, the training time tt plays roughly the role of 1/λ1/\lambda. Early stopping — halting when the validation error starts to rise — amounts to choosing λ from data.

Cross-validation

λ (or model size, or number of training steps) must ultimately be chosen from data. When data is scarce and setting aside a separate validation set feels wasteful, use k-fold cross-validation. Split the data into kk pieces, hold out one piece at a time for validation while training on the rest, and average the kk validation errors. Every point is used for validation exactly once. With k=nk = n it is leave-one-out.

Watch out for two things. First, preprocessing (standardisation, feature selection) is part of learning too, so it must be fit within each fold only. Computing the mean and variance on the whole dataset and then splitting leaks information from the validation piece. Second, the CV score after choosing hyperparameters by CV is itself optimistic. If you need an honest performance estimate, keep one more test set outside, or use nested CV.

NumPy Bias–variance decomposition and 5-fold cross-validation
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x)
sigma, n = 0.3, 25
centers = np.linspace(0, 1, 24)

def phi(x, s=0.1):                                # bias + 24 Gaussian basis functions
    return np.c_[np.ones(len(x)), np.exp(-(x[:, None] - centers) ** 2 / (2 * s * s))]

def ridge(x, y, lam):
    P = phi(x)
    return np.linalg.solve(P.T @ P + lam * np.eye(P.shape[1]), P.T @ y)

def sample(n):
    x = rng.uniform(0, 1, n)
    return x, f(x) + sigma * rng.normal(size=n)

# ---- bias–variance decomposition: draw 200 fresh datasets from the same distribution and fit each ----
xg = np.linspace(0, 1, 200)
datasets = [sample(n) for _ in range(200)]
lams = 10.0 ** np.arange(-4, 2.01, 0.5)
print("log10 λ    bias²    var     bias²+var+σ²   (directly measured test MSE)")
for lam in lams:
    F = np.array([phi(xg) @ ridge(x, y, lam) for x, y in datasets])   # (200, len(xg))
    bias2 = np.mean((F.mean(0) - f(xg)) ** 2)
    var = np.mean(F.var(0))
    y_new = f(xg) + sigma * rng.normal(size=F.shape)                   # fresh noise
    test = np.mean((F - y_new) ** 2)
    print(f"{np.log10(lam):+5.1f}   {bias2:7.4f}  {var:7.4f}   {bias2 + var + sigma**2:7.4f}       {test:7.4f}")

# ---- choose λ on a single dataset with 5-fold cross-validation ----
x, y = datasets[0]
folds = np.array_split(rng.permutation(n), 5)
def cv_error(lam):
    errs = []
    for k in range(5):
        va = folds[k]; trn = np.concatenate([folds[j] for j in range(5) if j != k])
        w = ridge(x[trn], y[trn], lam)
        errs.append(np.mean((phi(x[va]) @ w - y[va]) ** 2))
    return np.mean(errs)
cv = [cv_error(l) for l in lams]
print(f"\nlog10 λ chosen by CV = {np.log10(lams[int(np.argmin(cv))]):+.1f}   (CV MSE {min(cv):.3f})")
 

The last column (test MSE measured directly with fresh noise) matches the third column (bias² + variance + σ²) to the second decimal place — confirmation that the decomposition is an equation, not an approximation. CV run on just one dataset also picks something near the true optimum (log₁₀ λ ≈ 0).

확인 문제Check yourself

In ridge regression, what generally happens as λ increases?

λ pulls every dataset’s solution toward 0 in the same way. The solutions become more alike, so the variance falls; the average solution moves away from the true function, so the bias grows. The noise σ2\sigma^2 is a property of the data and no λ changes it.

Where the classical picture breaks: double descent

By the bias–variance story, if you keep growing the model the variance grows and the test error should only go up. Yet modern neural networks have far more parameters than data points, memorise the training data perfectly (sometimes even random labels, Zhang et al. 2017), and still generalise well. Belkin et al. (2019) put the two in one picture. As model size grows, the test error traces the classical U, then spikes at the point where the model can just interpolate the training data (the interpolation threshold), and comes down again beyond it. This is double descent.

The simplest reproduction is random-feature regression. Build pp ReLU features of an input x∈R10x \in \mathbb R^{10} with fixed random weights (ϕj(x)=max⁡(0,wj⊤x)/p\phi_j(x) = \max(0, w_j^\top x)/\sqrt p) and learn only a linear regression on top. For p<np < n it is ordinary least squares. For p>np > n the equation Φθ=y\Phi\theta = y has infinitely many solutions, so we pick the one with the smallest norm.

θ^=Φ⊤(ΦΦ⊤)−1y=Φ+y\hat\theta = \Phi^\top(\Phi\Phi^\top)^{-1} y = \Phi^{+} y

Compared with the closed-form ridge solution, this is the λ→0+\lambda \to 0^+ limit. Thanks to the identity (Φ⊤Φ+λI)−1Φ⊤=Φ⊤(ΦΦ⊤+λI)−1(\Phi^\top\Phi + \lambda I)^{-1}\Phi^\top = \Phi^\top(\Phi\Phi^\top + \lambda I)^{-1}, the same formula connects the two regimes.

  1. log₁₀ λ = −4로 내리면 빨간 가는 선들이 제각각 날뛴다. 평균(굵은 선)은 오히려 참 함수에 아주 가깝다. 편향은 작고 분산이 크다.
  2. log₁₀ λ = 2로 올리면 모든 적합이 거의 같은 평평한 곡선이 된다. 분산은 작고 편향이 크다.
  3. 그 사이 λ ≈ 1 근처에서 검은 곡선(편향² + 분산 + σ²)이 최소다. 아래 막대에서 세 성분의 비율이 바뀌는 것을 보자.
  4. n을 100으로 올리면 분산 곡선이 통째로 내려가고 최적 λ가 왼쪽으로 옮겨 간다. 데이터가 많을수록 정규화가 덜 필요하다.

L2 정규화 = 가우시안 사전분포

λ의 정체를 보자. ridge 회귀는 12∥Xθ−y∥2+λ2∥θ∥2\frac12\|X\theta - y\|^2 + \frac\lambda2\|\theta\|^2를 최소화하고 닫힌 해는 θ^λ=(X⊤X+λI)−1X⊤y\hat\theta_\lambda = (X^\top X + \lambda I)^{-1}X^\top y다.

스펙트럼으로 보면 무엇을 하는지 정확히 보인다. X=USV⊤X = U S V^\top(SVD, 특이값 sis_i)라 쓰면

Xθ^λ=∑iui si2si2+λ ui⊤y.X\hat\theta_\lambda = \sum_i u_i \,\frac{s_i^2}{s_i^2 + \lambda}\, u_i^\top y .

최소제곱(λ=0\lambda = 0)은 각 방향의 성분을 그대로 쓰는데, ridge는 si2/(si2+λ)s_i^2/(s_i^2 + \lambda)를 곱해 데이터가 적게 말해 주는 방향(작은 sis_i)을 0 쪽으로 누른다. 그 방향의 계수는 잡음에 크게 흔들리는 방향이었으니, 약간의 편향을 받고 분산을 크게 줄이는 거래다.

확률로 보면 이 항은 사전분포다. 우도 y∣X,θ∼N(Xθ,σ2I)y \mid X, \theta \sim \mathcal N(X\theta, \sigma^2 I)에 사전분포 θ∼N(0,τ2I)\theta \sim \mathcal N(0, \tau^2 I)를 놓고 사후분포를 최대화(MAP, maximum a posteriori)하면

−log⁡p(θ∣D)=12σ2∥Xθ−y∥2+12τ2∥θ∥2+const⟹λ=σ2τ2.-\log p(\theta \mid \mathcal D) = \frac{1}{2\sigma^2}\|X\theta - y\|^2 + \frac{1}{2\tau^2}\|\theta\|^2 + \text{const} \quad\Longrightarrow\quad \lambda = \frac{\sigma^2}{\tau^2}.

이전 레슨에서 MSE가 가우시안 우도였듯이, L2 항은 “θ는 0 근처에 있을 것”이라는 가우시안 믿음이다. 잡음이 클수록, 사전 믿음이 강할수록(τ\tau가 작을수록) λ가 커진다. 같은 논리로 라플라스 사전분포는 L1(lasso)을 준다.

경사하강법으로 보면 L2 항은 매 step 가중치를 일정 비율 줄인다.

θ←θ−η(∇L(θ)+λθ)=(1−ηλ) θ−η∇L(θ)\theta \leftarrow \theta - \eta\big(\nabla L(\theta) + \lambda\theta\big) = (1 - \eta\lambda)\,\theta - \eta\nabla L(\theta)

그래서 weight decay라고 부른다. SGD에서는 L2 정규화와 weight decay가 같은 것이지만, Adam처럼 기울기를 좌표마다 다르게 스케일하는 옵티마이저에서는 둘이 갈라진다. 이것이 AdamW가 생긴 이유이고 옵티마이저 레슨에서 자세히 본다.

Early stopping도 정규화다

경사하강법을 끝까지 돌리지 않고 중간에 멈추는 것도 같은 효과를 낸다. 최소제곱을 θ0=0\theta_0 = 0에서 학습률 η\eta로 tt step 돌리면, 각 특이 방향의 성분은 독립적으로 수렴한다(경사하강법 레슨의 고유분해 그대로). 정리하면

Xθt=∑iui [1−(1−ηsi2)t]⏟≈ 1−e−ηtsi2 ui⊤y.X\theta_t = \sum_i u_i\, \underbrace{\big[1 - (1 - \eta s_i^2)^t\big]}_{\approx\, 1 - e^{-\eta t s_i^2}}\, u_i^\top y .

ridge의 필터 si2/(si2+λ)s_i^2/(s_i^2 + \lambda)와 모양이 같다. 큰 sis_i 방향은 빨리 1에 가까워지고 작은 sis_i 방향은 거의 0에 머문다. 둘 다 si2≈λ≈1/(ηt)s_i^2 \approx \lambda \approx 1/(\eta t) 근처에서 0에서 1로 넘어간다. 즉 학습 시간 tt는 대략 1/λ1/\lambda 역할을 한다. validation 오차가 오르기 시작할 때 멈추는 early stopping은 λ를 데이터로 고르는 것과 같은 일이다.

교차검증

λ(혹은 모델 크기, 학습 step 수)는 결국 데이터로 골라야 한다. 데이터가 적어 validation 집합을 따로 떼기 아까우면 k-fold 교차검증(cross-validation) 을 쓴다. 데이터를 kk조각으로 나누고, 한 조각씩 돌아가며 검증용으로 빼고 나머지로 학습해 kk개의 검증 오차를 평균 낸다. 모든 점이 정확히 한 번씩 검증에 쓰인다. k=nk = n이면 leave-one-out이다.

두 가지를 조심한다. 첫째, 전처리(표준화, 특징 선택)도 학습의 일부이므로 fold 안에서만 맞춰야 한다. 전체 데이터로 평균·분산을 구하고 나누면 검증 조각의 정보가 샌다. 둘째, CV로 하이퍼파라미터를 고른 뒤의 CV 점수는 그 자체로 낙관적이다. 정직한 성능 추정이 필요하면 바깥에 test 집합을 하나 더 두거나 중첩(nested) CV를 쓴다.

NumPy 편향–분산 분해와 5-fold 교차검증
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x)
sigma, n = 0.3, 25
centers = np.linspace(0, 1, 24)

def phi(x, s=0.1):                                # bias + 가우시안 기저 24개
    return np.c_[np.ones(len(x)), np.exp(-(x[:, None] - centers) ** 2 / (2 * s * s))]

def ridge(x, y, lam):
    P = phi(x)
    return np.linalg.solve(P.T @ P + lam * np.eye(P.shape[1]), P.T @ y)

def sample(n):
    x = rng.uniform(0, 1, n)
    return x, f(x) + sigma * rng.normal(size=n)

# ---- 편향–분산 분해: 같은 분포에서 데이터셋 200개를 새로 뽑아 각각 적합 ----
xg = np.linspace(0, 1, 200)
datasets = [sample(n) for _ in range(200)]
lams = 10.0 ** np.arange(-4, 2.01, 0.5)
print("log10 λ    bias²    var     bias²+var+σ²   (직접 잰 test MSE)")
for lam in lams:
    F = np.array([phi(xg) @ ridge(x, y, lam) for x, y in datasets])   # (200, len(xg))
    bias2 = np.mean((F.mean(0) - f(xg)) ** 2)
    var = np.mean(F.var(0))
    y_new = f(xg) + sigma * rng.normal(size=F.shape)                   # 새 잡음
    test = np.mean((F - y_new) ** 2)
    print(f"{np.log10(lam):+5.1f}   {bias2:7.4f}  {var:7.4f}   {bias2 + var + sigma**2:7.4f}       {test:7.4f}")

# ---- 5-fold 교차검증으로 데이터셋 하나에서 λ 고르기 ----
x, y = datasets[0]
folds = np.array_split(rng.permutation(n), 5)
def cv_error(lam):
    errs = []
    for k in range(5):
        va = folds[k]; trn = np.concatenate([folds[j] for j in range(5) if j != k])
        w = ridge(x[trn], y[trn], lam)
        errs.append(np.mean((phi(x[va]) @ w - y[va]) ** 2))
    return np.mean(errs)
cv = [cv_error(l) for l in lams]
print(f"\nCV가 고른 log10 λ = {np.log10(lams[int(np.argmin(cv))]):+.1f}   (CV MSE {min(cv):.3f})")
 

마지막 열(새 잡음으로 직접 잰 test MSE)이 셋째 열(편향² + 분산 + σ²)과 소수점 둘째 자리까지 맞는다. 분해가 근사가 아니라 등식이라는 확인이다. 데이터셋 하나만 가지고 한 CV도 진짜 최적(log₁₀ λ ≈ 0) 근처를 고른다.

확인 문제Check yourself

ridge 회귀에서 λ를 키울 때 일반적으로 일어나는 일은?

λ는 모든 데이터셋의 해를 0 쪽으로 똑같이 끌어당긴다. 해들이 서로 비슷해지니 분산은 줄고, 평균 해가 참 함수에서 멀어지니 편향은 는다. 잡음 σ2\sigma^2은 데이터의 성질이라 어떤 λ로도 바뀌지 않는다.

고전적 그림이 깨지는 곳: double descent

편향–분산 이야기를 따르면 모델을 계속 키우면 분산이 커져 test 오차가 오르기만 해야 한다. 그런데 현대 신경망은 매개변수가 데이터보다 훨씬 많고, 훈련 데이터를(때로는 무작위 레이블까지, Zhang et al. 2017) 완벽히 외우면서도 잘 일반화한다. Belkin et al.(2019)은 이 둘을 한 그림에 놓았다. 모델 크기를 늘리면 test 오차가 고전적인 U자를 그리다가, 훈련 데이터를 딱 보간할 수 있게 되는 지점(interpolation threshold)에서 치솟고, 그 너머에서 다시 내려간다. 이것이 double descent다.

가장 단순한 재현은 무작위 특징 회귀다. 입력 x∈R10x \in \mathbb R^{10}에 고정된 무작위 가중치로 ReLU 특징 pp개를 만들고(ϕj(x)=max⁡(0,wj⊤x)/p\phi_j(x) = \max(0, w_j^\top x)/\sqrt p), 그 위에서 선형회귀만 학습한다. p<np < n이면 보통 최소제곱이다. p>np > n이면 방정식 Φθ=y\Phi\theta = y의 해가 무수히 많으므로 그중 노름이 가장 작은 해를 고른다.

θ^=Φ⊤(ΦΦ⊤)−1y=Φ+y\hat\theta = \Phi^\top(\Phi\Phi^\top)^{-1} y = \Phi^{+} y

ridge의 닫힌 해와 비교하면 이것은 λ→0+\lambda \to 0^+ 극한이다. (Φ⊤Φ+λI)−1Φ⊤=Φ⊤(ΦΦ⊤+λI)−1(\Phi^\top\Phi + \lambda I)^{-1}\Phi^\top = \Phi^\top(\Phi\Phi^\top + \lambda I)^{-1}이라는 항등식 덕분에 같은 식이 두 영역을 잇는다.

고전적 최적classical optimum – p = n 에서at p = n – p = 600 에서at p = 600 –
Input x ∈ ℝ¹⁰, features are random ReLUs φj(x) = max(0, wjᵀx)/√p, and learning is min-norm least squares (λ = 0). We plot the test error (median over 8 random feature draws) as the number of features p grows. At p = n (vertical dashed line) the test error spikes; beyond it, even though the training error is 0, it comes back down and ends up below the classical optimum. Right: at exactly that point the smallest singular value of Φ goes to 0 and ‖θ‖ explodes. Raise λ and the peak disappears. Also check that lowering σ to 0 almost removes the peak: the peak is the cost of interpolating noise. 입력 x ∈ ℝ¹⁰, 특징은 무작위 ReLU φj(x) = max(0, wjᵀx)/√p, 학습은 최소 노름 최소제곱(λ = 0). 특징 p개를 늘려 가며 test 오차(8개 무작위 특징의 중앙값)를 그렸다. p = n(세로 점선)에서 test 오차가 치솟고, 그 너머에서는 훈련 오차가 0인데도 다시 내려가 고전적 최적보다 낮아진다. 오른쪽: 바로 그 지점에서 Φ의 최소 특이값이 0으로 가고 ‖θ‖가 폭발한다. λ를 올리면 봉우리가 사라진다. σ를 0으로 내리면 봉우리가 거의 없어지는 것도 확인해 보자. 봉우리는 잡음을 보간하는 비용이다.
  1. The red curve on the left bottoms out once at p ≈ 20 (the classical optimum, black dot) and then spikes tens of times higher at p = n = 40. At exactly that point the blue train error hits 0.
  2. Increase p to 600 and the train error stays at 0 while the test error goes lower than the classical optimum (green dot).
  3. Right: at p = n the smallest singular value of Φ\Phi (teal) is almost 0 and ‖θ‖ (purple) peaks.
  4. Raise the ridge λ to about 10−210^{-2} and the peak disappears. Lowering σ to 0 also shrinks the peak a lot. Change n and the peak follows to the new n.

Why it blows up at p = n

When p=np = n, Φ\Phi is square and there is only one interpolating solution, θ=Φ−1y\theta = \Phi^{-1}y. Random square matrices tend to have a smallest singular value very close to 0. Even a small component of the noise ε\varepsilon in yy along that direction is amplified by 1/smin⁡1/s_{\min} into θ\theta.

∥θ∥2=∑i(ui⊤y)2si2  ≥  (umin⁡⊤y)2smin⁡2,umin⁡:the left singular vector for the smallest singular value of Φ\|\theta\|^2 = \sum_i \frac{(u_i^\top y)^2}{s_i^2} \;\ge\; \frac{(u_{\min}^\top y)^2}{s_{\min}^2}, \qquad u_{\min}: \text{the left singular vector for the smallest singular value of } \Phi

To memorise the noise exactly, the model has to use huge coefficients, and those huge coefficients produce nonsense on new inputs. When pp is sufficiently larger than nn, there are infinitely many interpolating solutions, and the min-norm solution picks the “tamest” among them. The more features, the further smin⁡s_{\min} moves away from 0 (right-hand plot), and the cost of memorising the noise is spread thinly over many directions. This is the intuition behind benign overfitting. It is not free, though. As Bartlett et al. (2020) showed, it holds when the spectrum of the feature covariance satisfies particular conditions; interpolating noise with low-dimensional inputs is usually harmful.

Gradient descent picks the min-norm solution

There is a reason this story matters even though in practice nobody computes the min-norm solution explicitly. Starting from θ0=0\theta_0 = 0, the gradient descent update −η Φ⊤(Φθ−y)-\eta\,\Phi^\top(\Phi\theta - y) always lies in the row space of Φ\Phi. So θt\theta_t stays in the row space forever, and when it converges it reaches the unique interpolating solution in the row space — the min-norm solution. Even with no regularisation term, the algorithm itself prefers a particular solution: this is implicit regularization. It is the same family of phenomena as logistic regression heading toward the max-margin direction in the linear models lesson.

NumPy Double descent: random ReLU features + min-norm least squares
import time
t0 = time.time()
rng = np.random.default_rng(0)
d, n, sigma = 10, 40, 0.3
beta = rng.normal(size=d) / np.sqrt(d)

def target(X):                                     # linear + a little nonlinearity
    return X @ beta + 0.5 * np.tanh(X[:, 0] * X[:, 1])

X_tr = rng.normal(size=(n, d));    y_tr = target(X_tr) + sigma * rng.normal(size=n)
X_te = rng.normal(size=(1000, d)); y_te = target(X_te)

def relu_features(X, W):
    return np.maximum(0, X @ W) / np.sqrt(W.shape[1])

def ridge_fit(Phi, y, lam=0.0):
    m, p = Phi.shape
    if p <= m:   # underparameterised: θ = (ΦᵀΦ + λI)⁻¹ Φᵀy
        return np.linalg.solve(Phi.T @ Phi + (lam + 1e-12) * np.eye(p), Phi.T @ y)
    # overparameterised: θ = Φᵀ(ΦΦᵀ + λI)⁻¹ y   (as λ→0, the smallest-norm interpolating solution)
    return Phi.T @ np.linalg.solve(Phi @ Phi.T + (lam + 1e-12) * np.eye(m), y)

def run(p, lam=0.0, seeds=10):
    te, tr, nrm, smin = [], [], [], []
    for s in range(seeds):
        W = np.random.default_rng(1000 + s).normal(size=(d, p)) / np.sqrt(d)
        Phi = relu_features(X_tr, W)
        th = ridge_fit(Phi, y_tr, lam)
        tr.append(np.mean((Phi @ th - y_tr) ** 2))
        te.append(np.mean((relu_features(X_te, W) @ th - y_te) ** 2))
        nrm.append(np.linalg.norm(th))
        G = Phi.T @ Phi if p <= n else Phi @ Phi.T
        smin.append(np.sqrt(max(np.linalg.eigvalsh(G)[0], 0)))
    return np.median(te), np.median(tr), np.median(nrm), np.median(smin)

print("    p   train MSE   test MSE    ||θ||   σ_min(Φ)      (n = 40, λ = 0)")
for p in [2, 5, 10, 20, 30, 36, 40, 44, 50, 60, 100, 200, 600, 1500]:
    te, tr, nrm, sm = run(p)
    bar = "#" * int(min(40, 10 * (np.log10(te) + 1.5)))
    print(f"{p:5d}   {tr:9.2e}   {te:8.3f}  {nrm:7.1f}   {sm:8.4f}   {bar}")

print("\nwith ridge λ = 1e-2:")
for p in [20, 40, 1500]:
    print(f"  p={p:5d}  test MSE {run(p, lam=1e-2)[0]:.3f}")
print(f"\n({time.time() - t0:.1f}s)")
 

The bar (log scale) dips once at p = 20, stretches all the way out at p = 40, and at p ≥ 600 ends up lower than at the start. A moderate ridge removes the peak and does as well or better at every p (the same conclusion as Nakkiran, Venkat, Kakade & Ma (2020), “Optimal Regularization Can Mitigate Double Descent”).

확인 문제Check yourself

You use min-norm least squares for random-feature regression on n = 100 data points. Without regularisation, at which number of features p is the test error most likely to spike?

At p=n=100p = n = 100, where interpolation first becomes possible, Φ\Phi is nearly square and its smallest singular value is close to 0, so the noise is amplified by 1/smin⁡1/s_{\min}. For p≫np \gg n the min-norm solution spreads the noise thinly across many directions and the error comes back down.

Summary

  • The expected test error under squared loss = noise σ2\sigma^2 + bias² + variance. It is an exact equation, down to the third term.
  • L2/ridge reduces variance by pressing small-singular-value directions by s2/(s2+λ)s^2/(s^2+\lambda). Probabilistically it is MAP with a Gaussian prior (λ=σ2/τ2\lambda = \sigma^2/\tau^2); in GD it is weight decay.
  • Early stopping is a filter similar to ridge with λ≈1/(ηt)\lambda \approx 1/(\eta t). Choose λ or the stopping point by cross-validation.
  • In random-feature, min-norm regression the test error spikes at p=np = n (smallest singular value → 0) and falls again beyond it. GD picks the min-norm solution even without regularisation.
  • Pre-training lives in the data-rich regime; post-training is where overfitting is real. The KL penalty is a prior centred on πref\pi_{\text{ref}}.
  1. 왼쪽 빨간 곡선이 p ≈ 20에서 한 번 바닥을 찍고(고전적 최적, 검은 점), p = n = 40에서 수십 배로 치솟는다. 바로 그 지점에서 파란 train 오차가 0이 된다.
  2. p를 600까지 늘리면 train 오차는 계속 0인데 test 오차는 고전적 최적보다 더 낮아진다(초록 점).
  3. 오른쪽: p = n에서 Φ\Phi의 최소 특이값(청록)이 거의 0이고 ‖θ‖(보라)가 봉우리를 이룬다.
  4. ridge λ를 10−210^{-2} 정도로 올리면 봉우리가 사라진다. σ를 0으로 내려도 봉우리가 크게 줄어든다. n을 바꾸면 봉우리가 새 n으로 따라간다.

왜 p = n에서 터지는가

p=np = n이면 Φ\Phi는 정사각 행렬이고 보간 해는 θ=Φ−1y\theta = \Phi^{-1}y 하나뿐이다. 무작위 정사각 행렬은 최소 특이값이 0에 매우 가까운 경향이 있다. yy의 잡음 성분 ε\varepsilon이 그 방향으로 조금만 있어도 θ\theta에 1/smin⁡1/s_{\min}배로 증폭되어 들어간다.

∥θ∥2=∑i(ui⊤y)2si2  ≥  (umin⁡⊤y)2smin⁡2,umin⁡:Φ의 최소 특이값에 대응하는 왼쪽 특이벡터\|\theta\|^2 = \sum_i \frac{(u_i^\top y)^2}{s_i^2} \;\ge\; \frac{(u_{\min}^\top y)^2}{s_{\min}^2}, \qquad u_{\min}: \Phi\text{의 최소 특이값에 대응하는 왼쪽 특이벡터}

모델은 잡음을 정확히 외우기 위해 거대한 계수를 써야 하고, 그 거대한 계수가 새 입력에서 엉뚱한 값을 만든다. pp가 nn보다 충분히 크면 보간 해가 무수히 많아지고, 최소 노름 해는 그중 가장 “얌전한” 것을 고른다. 특징이 많을수록 smin⁡s_{\min}이 0에서 멀어지고(오른쪽 그림), 잡음을 외우는 비용이 많은 방향으로 얇게 퍼진다. 이것이 양성 과적합(benign overfitting) 의 직관이다. 다만 공짜는 아니다. Bartlett et al.(2020)이 보였듯 이것은 특징 공분산의 스펙트럼이 특정 조건을 만족할 때 성립하고, 저차원 입력에서 잡음을 보간하면 대개 해롭다.

경사하강법은 최소 노름 해를 고른다

실전에서 최소 노름 해를 명시적으로 계산하지 않는데도 이 이야기가 의미 있는 이유가 있다. θ0=0\theta_0 = 0에서 출발한 경사하강법의 업데이트는 −η Φ⊤(Φθ−y)-\eta\,\Phi^\top(\Phi\theta - y)로, 언제나 Φ\Phi의 행공간(row space) 안에 있다. 그러니 θt\theta_t도 영원히 행공간 안에 있고, 수렴하면 보간 해 중 행공간에 있는 유일한 해, 곧 최소 노름 해에 도달한다. 정규화 항이 없어도 알고리즘 자체가 특정 해를 선호하는 암묵적 정규화(implicit regularization) 다. 선형 모델 레슨에서 로지스틱 회귀가 최대 마진 방향으로 가던 것과 같은 계열의 현상이다.

NumPy double descent: 무작위 ReLU 특징 + 최소 노름 최소제곱
import time
t0 = time.time()
rng = np.random.default_rng(0)
d, n, sigma = 10, 40, 0.3
beta = rng.normal(size=d) / np.sqrt(d)

def target(X):                                     # 선형 + 약간의 비선형
    return X @ beta + 0.5 * np.tanh(X[:, 0] * X[:, 1])

X_tr = rng.normal(size=(n, d));    y_tr = target(X_tr) + sigma * rng.normal(size=n)
X_te = rng.normal(size=(1000, d)); y_te = target(X_te)

def relu_features(X, W):
    return np.maximum(0, X @ W) / np.sqrt(W.shape[1])

def ridge_fit(Phi, y, lam=0.0):
    m, p = Phi.shape
    if p <= m:   # 과소매개변수: θ = (ΦᵀΦ + λI)⁻¹ Φᵀy
        return np.linalg.solve(Phi.T @ Phi + (lam + 1e-12) * np.eye(p), Phi.T @ y)
    # 과대매개변수: θ = Φᵀ(ΦΦᵀ + λI)⁻¹ y   (λ→0 이면 보간 해 중 노름이 가장 작은 것)
    return Phi.T @ np.linalg.solve(Phi @ Phi.T + (lam + 1e-12) * np.eye(m), y)

def run(p, lam=0.0, seeds=10):
    te, tr, nrm, smin = [], [], [], []
    for s in range(seeds):
        W = np.random.default_rng(1000 + s).normal(size=(d, p)) / np.sqrt(d)
        Phi = relu_features(X_tr, W)
        th = ridge_fit(Phi, y_tr, lam)
        tr.append(np.mean((Phi @ th - y_tr) ** 2))
        te.append(np.mean((relu_features(X_te, W) @ th - y_te) ** 2))
        nrm.append(np.linalg.norm(th))
        G = Phi.T @ Phi if p <= n else Phi @ Phi.T
        smin.append(np.sqrt(max(np.linalg.eigvalsh(G)[0], 0)))
    return np.median(te), np.median(tr), np.median(nrm), np.median(smin)

print("    p   train MSE   test MSE    ||θ||   σ_min(Φ)      (n = 40, λ = 0)")
for p in [2, 5, 10, 20, 30, 36, 40, 44, 50, 60, 100, 200, 600, 1500]:
    te, tr, nrm, sm = run(p)
    bar = "#" * int(min(40, 10 * (np.log10(te) + 1.5)))
    print(f"{p:5d}   {tr:9.2e}   {te:8.3f}  {nrm:7.1f}   {sm:8.4f}   {bar}")

print("\nridge λ = 1e-2 를 넣으면:")
for p in [20, 40, 1500]:
    print(f"  p={p:5d}  test MSE {run(p, lam=1e-2)[0]:.3f}")
print(f"\n({time.time() - t0:.1f}s)")
 

막대(log 스케일)가 p = 20에서 한 번 낮아졌다가 p = 40에서 끝까지 뻗고, p ≥ 600에서 처음보다 낮아진다. 적당한 ridge는 봉우리를 없애고 모든 p에서 비슷하거나 더 낫다(Nakkiran, Venkat, Kakade & Ma(2020)가 “최적 정규화는 double descent를 완화할 수 있다”고 보인 것과 같은 결론이다).

확인 문제Check yourself

무작위 특징 회귀에서 n = 100개의 데이터에 최소 노름 최소제곱을 쓴다. 정규화 없이 test 오차가 가장 크게 튈 가능성이 높은 특징 수 p는?

보간이 처음으로 가능해지는 p=n=100p = n = 100에서 Φ\Phi가 정사각에 가깝고 최소 특이값이 0에 가까워 잡음이 1/smin⁡1/s_{\min}배로 증폭된다. p≫np \gg n에서는 최소 노름 해가 잡음을 여러 방향으로 얇게 퍼뜨려 오차가 다시 내려간다.

정리

  • 제곱 손실의 기대 test 오차 = 잡음 σ2\sigma^2 + 편향² + 분산. 셋째 항까지 정확한 등식이다.
  • L2/ridge는 작은 특이값 방향을 s2/(s2+λ)s^2/(s^2+\lambda)로 눌러 분산을 줄인다. 확률적으로는 가우시안 사전분포의 MAP(λ=σ2/τ2\lambda = \sigma^2/\tau^2), GD에서는 weight decay다.
  • early stopping은 λ≈1/(ηt)\lambda \approx 1/(\eta t)인 ridge와 비슷한 필터다. λ나 멈출 시점은 교차검증으로 고른다.
  • 무작위 특징·최소 노름 회귀에서 test 오차는 p=np = n에서 치솟고(최소 특이값 → 0) 그 너머에서 다시 내려간다. GD는 정규화 없이도 최소 노름 해를 고른다.
  • 사전학습은 데이터가 풍부한 영역, 사후학습은 과적합이 현실인 영역이다. KL 페널티는 πref\pi_{\text{ref}}를 중심으로 한 사전분포다.

더 읽을거리Further reading