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 , observations with and . The training set is a random variable, and so is the predictor learned from it. At a fixed input , average the expected squared error on a new observation over both and . Write the average predictor as ; adding and subtracting gives
Square and take expectations and all the cross terms vanish: is the noise of the new observation, so it is independent of and has mean 0; the fluctuation term averages to 0 under by definition; and the bias term is constant with respect to . What remains is
- 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 in the previous lesson and the 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은 모두 그 영역에 산다.
편향–분산 분해
설정은 이렇다. 참 함수 , 관측 , , . 훈련 집합 는 확률변수이고, 거기서 학습한 예측기 도 확률변수다. 고정된 입력 에서 새로운 관측 에 대한 기대 제곱 오차를 와 모두에 대해 평균 내자. 평균 예측기를 라 두고 더하고 빼면
제곱해서 기댓값을 취하면 교차항이 모두 사라진다. 은 새 관측의 잡음이라 와 독립이고 평균이 0이며, 요동 항은 정의상 로 평균 내면 0이고, 편향 항은 에 대해 상수이기 때문이다. 남는 것은
- 편향(bias): 데이터를 무한히 다시 뽑아 평균 낸 예측기조차 틀리는 정도. 가설 집합이 너무 작거나 정규화가 너무 셀 때 크다.
- 분산(variance): 데이터셋을 바꿀 때 예측기가 흔들리는 정도. 모델이 크고 데이터가 적을 때 크다.
- 잡음: 어떤 모델로도 없앨 수 없다. 이전 레슨의 , 첫 레슨의 바닥과 같은 것이다.
이 분해는 제곱 손실에서만 이렇게 깔끔하다. 0–1 손실이나 cross-entropy에도 비슷한 분해가 있지만 항들이 더해지는 꼴이 아니다. 그래도 “평균적으로 틀림 vs 표본에 따라 흔들림”이라는 직관은 그대로 쓸 수 있다.
- 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.
- Raise log₁₀ λ to 2 and every fit becomes nearly the same flat curve. Low variance, high bias.
- 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.
- 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 , with closed-form solution .
Through the spectrum you can see exactly what it does. Writing (SVD, singular values ),
Least squares () uses the component along each direction as is, while ridge multiplies by , pressing toward 0 the directions the data says little about (small ). 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 on the likelihood and maximise the posterior (MAP, maximum a posteriori):
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 ), 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.
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 for steps with learning rate and the component along each singular direction converges independently (exactly the eigen-decomposition of the gradient descent lesson). Putting it together,
It has the same shape as the ridge filter . Directions with large quickly approach 1, and directions with small stay near 0. Both switch from 0 to 1 around . In other words, the training time plays roughly the role of . 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 pieces, hold out one piece at a time for validation while training on the rest, and average the validation errors. Every point is used for validation exactly once. With 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.
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).
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 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 ReLU features of an input with fixed random weights () and learn only a linear regression on top. For it is ordinary least squares. For the equation has infinitely many solutions, so we pick the one with the smallest norm.
Compared with the closed-form ridge solution, this is the limit. Thanks to the identity , the same formula connects the two regimes.
- log₁₀ λ = −4로 내리면 빨간 가는 선들이 제각각 날뛴다. 평균(굵은 선)은 오히려 참 함수에 아주 가깝다. 편향은 작고 분산이 크다.
- log₁₀ λ = 2로 올리면 모든 적합이 거의 같은 평평한 곡선이 된다. 분산은 작고 편향이 크다.
- 그 사이 λ ≈ 1 근처에서 검은 곡선(편향² + 분산 + σ²)이 최소다. 아래 막대에서 세 성분의 비율이 바뀌는 것을 보자.
- n을 100으로 올리면 분산 곡선이 통째로 내려가고 최적 λ가 왼쪽으로 옮겨 간다. 데이터가 많을수록 정규화가 덜 필요하다.
L2 정규화 = 가우시안 사전분포
λ의 정체를 보자. ridge 회귀는 를 최소화하고 닫힌 해는 다.
스펙트럼으로 보면 무엇을 하는지 정확히 보인다. (SVD, 특이값 )라 쓰면
최소제곱()은 각 방향의 성분을 그대로 쓰는데, ridge는 를 곱해 데이터가 적게 말해 주는 방향(작은 )을 0 쪽으로 누른다. 그 방향의 계수는 잡음에 크게 흔들리는 방향이었으니, 약간의 편향을 받고 분산을 크게 줄이는 거래다.
확률로 보면 이 항은 사전분포다. 우도 에 사전분포 를 놓고 사후분포를 최대화(MAP, maximum a posteriori)하면
이전 레슨에서 MSE가 가우시안 우도였듯이, L2 항은 “θ는 0 근처에 있을 것”이라는 가우시안 믿음이다. 잡음이 클수록, 사전 믿음이 강할수록(가 작을수록) λ가 커진다. 같은 논리로 라플라스 사전분포는 L1(lasso)을 준다.
경사하강법으로 보면 L2 항은 매 step 가중치를 일정 비율 줄인다.
그래서 weight decay라고 부른다. SGD에서는 L2 정규화와 weight decay가 같은 것이지만, Adam처럼 기울기를 좌표마다 다르게 스케일하는 옵티마이저에서는 둘이 갈라진다. 이것이 AdamW가 생긴 이유이고 옵티마이저 레슨에서 자세히 본다.
Early stopping도 정규화다
경사하강법을 끝까지 돌리지 않고 중간에 멈추는 것도 같은 효과를 낸다. 최소제곱을 에서 학습률 로 step 돌리면, 각 특이 방향의 성분은 독립적으로 수렴한다(경사하강법 레슨의 고유분해 그대로). 정리하면
ridge의 필터 와 모양이 같다. 큰 방향은 빨리 1에 가까워지고 작은 방향은 거의 0에 머문다. 둘 다 근처에서 0에서 1로 넘어간다. 즉 학습 시간 는 대략 역할을 한다. validation 오차가 오르기 시작할 때 멈추는 early stopping은 λ를 데이터로 고르는 것과 같은 일이다.
교차검증
λ(혹은 모델 크기, 학습 step 수)는 결국 데이터로 골라야 한다. 데이터가 적어 validation 집합을 따로 떼기 아까우면 k-fold 교차검증(cross-validation) 을 쓴다. 데이터를 조각으로 나누고, 한 조각씩 돌아가며 검증용으로 빼고 나머지로 학습해 개의 검증 오차를 평균 낸다. 모든 점이 정확히 한 번씩 검증에 쓰인다. 이면 leave-one-out이다.
두 가지를 조심한다. 첫째, 전처리(표준화, 특징 선택)도 학습의 일부이므로 fold 안에서만 맞춰야 한다. 전체 데이터로 평균·분산을 구하고 나누면 검증 조각의 정보가 샌다. 둘째, CV로 하이퍼파라미터를 고른 뒤의 CV 점수는 그 자체로 낙관적이다. 정직한 성능 추정이 필요하면 바깥에 test 집합을 하나 더 두거나 중첩(nested) CV를 쓴다.
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) 근처를 고른다.
ridge 회귀에서 λ를 키울 때 일반적으로 일어나는 일은?
λ는 모든 데이터셋의 해를 0 쪽으로 똑같이 끌어당긴다. 해들이 서로 비슷해지니 분산은 줄고, 평균 해가 참 함수에서 멀어지니 편향은 는다. 잡음 은 데이터의 성질이라 어떤 λ로도 바뀌지 않는다.
고전적 그림이 깨지는 곳: double descent
편향–분산 이야기를 따르면 모델을 계속 키우면 분산이 커져 test 오차가 오르기만 해야 한다. 그런데 현대 신경망은 매개변수가 데이터보다 훨씬 많고, 훈련 데이터를(때로는 무작위 레이블까지, Zhang et al. 2017) 완벽히 외우면서도 잘 일반화한다. Belkin et al.(2019)은 이 둘을 한 그림에 놓았다. 모델 크기를 늘리면 test 오차가 고전적인 U자를 그리다가, 훈련 데이터를 딱 보간할 수 있게 되는 지점(interpolation threshold)에서 치솟고, 그 너머에서 다시 내려간다. 이것이 double descent다.
가장 단순한 재현은 무작위 특징 회귀다. 입력 에 고정된 무작위 가중치로 ReLU 특징 개를 만들고(), 그 위에서 선형회귀만 학습한다. 이면 보통 최소제곱이다. 이면 방정식 의 해가 무수히 많으므로 그중 노름이 가장 작은 해를 고른다.
ridge의 닫힌 해와 비교하면 이것은 극한이다. 이라는 항등식 덕분에 같은 식이 두 영역을 잇는다.
- 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.
- Increase p to 600 and the train error stays at 0 while the test error goes lower than the classical optimum (green dot).
- Right: at p = n the smallest singular value of (teal) is almost 0 and ‖θ‖ (purple) peaks.
- Raise the ridge λ to about 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 , is square and there is only one interpolating solution, . Random square matrices tend to have a smallest singular value very close to 0. Even a small component of the noise in along that direction is amplified by into .
To memorise the noise exactly, the model has to use huge coefficients, and those huge coefficients produce nonsense on new inputs. When is sufficiently larger than , there are infinitely many interpolating solutions, and the min-norm solution picks the “tamest” among them. The more features, the further 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 , the gradient descent update always lies in the row space of . So 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.
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”).
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 , where interpolation first becomes possible, is nearly square and its smallest singular value is close to 0, so the noise is amplified by . For 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 + bias² + variance. It is an exact equation, down to the third term.
- L2/ridge reduces variance by pressing small-singular-value directions by . Probabilistically it is MAP with a Gaussian prior (); in GD it is weight decay.
- Early stopping is a filter similar to ridge with . Choose λ or the stopping point by cross-validation.
- In random-feature, min-norm regression the test error spikes at (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 .
- 왼쪽 빨간 곡선이 p ≈ 20에서 한 번 바닥을 찍고(고전적 최적, 검은 점), p = n = 40에서 수십 배로 치솟는다. 바로 그 지점에서 파란 train 오차가 0이 된다.
- p를 600까지 늘리면 train 오차는 계속 0인데 test 오차는 고전적 최적보다 더 낮아진다(초록 점).
- 오른쪽: p = n에서 의 최소 특이값(청록)이 거의 0이고 ‖θ‖(보라)가 봉우리를 이룬다.
- ridge λ를 정도로 올리면 봉우리가 사라진다. σ를 0으로 내려도 봉우리가 크게 줄어든다. n을 바꾸면 봉우리가 새 n으로 따라간다.
왜 p = n에서 터지는가
이면 는 정사각 행렬이고 보간 해는 하나뿐이다. 무작위 정사각 행렬은 최소 특이값이 0에 매우 가까운 경향이 있다. 의 잡음 성분 이 그 방향으로 조금만 있어도 에 배로 증폭되어 들어간다.
모델은 잡음을 정확히 외우기 위해 거대한 계수를 써야 하고, 그 거대한 계수가 새 입력에서 엉뚱한 값을 만든다. 가 보다 충분히 크면 보간 해가 무수히 많아지고, 최소 노름 해는 그중 가장 “얌전한” 것을 고른다. 특징이 많을수록 이 0에서 멀어지고(오른쪽 그림), 잡음을 외우는 비용이 많은 방향으로 얇게 퍼진다. 이것이 양성 과적합(benign overfitting) 의 직관이다. 다만 공짜는 아니다. Bartlett et al.(2020)이 보였듯 이것은 특징 공분산의 스펙트럼이 특정 조건을 만족할 때 성립하고, 저차원 입력에서 잡음을 보간하면 대개 해롭다.
경사하강법은 최소 노름 해를 고른다
실전에서 최소 노름 해를 명시적으로 계산하지 않는데도 이 이야기가 의미 있는 이유가 있다. 에서 출발한 경사하강법의 업데이트는 로, 언제나 의 행공간(row space) 안에 있다. 그러니 도 영원히 행공간 안에 있고, 수렴하면 보간 해 중 행공간에 있는 유일한 해, 곧 최소 노름 해에 도달한다. 정규화 항이 없어도 알고리즘 자체가 특정 해를 선호하는 암묵적 정규화(implicit regularization) 다. 선형 모델 레슨에서 로지스틱 회귀가 최대 마진 방향으로 가던 것과 같은 계열의 현상이다.
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를 완화할 수 있다”고 보인 것과 같은 결론이다).
무작위 특징 회귀에서 n = 100개의 데이터에 최소 노름 최소제곱을 쓴다. 정규화 없이 test 오차가 가장 크게 튈 가능성이 높은 특징 수 p는?
보간이 처음으로 가능해지는 에서 가 정사각에 가깝고 최소 특이값이 0에 가까워 잡음이 배로 증폭된다. 에서는 최소 노름 해가 잡음을 여러 방향으로 얇게 퍼뜨려 오차가 다시 내려간다.
정리
- 제곱 손실의 기대 test 오차 = 잡음 + 편향² + 분산. 셋째 항까지 정확한 등식이다.
- L2/ridge는 작은 특이값 방향을 로 눌러 분산을 줄인다. 확률적으로는 가우시안 사전분포의 MAP(), GD에서는 weight decay다.
- early stopping은 인 ridge와 비슷한 필터다. λ나 멈출 시점은 교차검증으로 고른다.
- 무작위 특징·최소 노름 회귀에서 test 오차는 에서 치솟고(최소 특이값 → 0) 그 너머에서 다시 내려간다. GD는 정규화 없이도 최소 노름 해를 고른다.
- 사전학습은 데이터가 풍부한 영역, 사후학습은 과적합이 현실인 영역이다. KL 페널티는 를 중심으로 한 사전분포다.
더 읽을거리Further reading
- Bishop, Pattern Recognition and Machine Learning §3.2 (Springer, 2006) — 가우시안 기저 24개 + ridge로 편향–분산을 보이는 그림 3.5–3.6. 이 레슨 첫 그림의 원형.Figures 3.5–3.6, showing bias–variance with 24 Gaussian basis functions plus ridge. The model for this lesson's first figure.
- Hastie, Tibshirani, Friedman, The Elements of Statistical Learning Ch. 7 (2nd ed., 2009) — 편향–분산, 교차검증, 모델 선택의 표준 레퍼런스.The standard reference on bias–variance, cross-validation and model selection.
- Belkin, Hsu, Ma, Mandal, Reconciling modern machine-learning practice and the classical bias–variance trade-off (PNAS 2019) — double descent라는 이름과 그림을 정착시킨 논문. 무작위 특징 모델로 보인다.The paper that established the name and the picture of double descent, shown with random-feature models.
- Nakkiran, Kaplun, Bansal, Yang, Barak, Sutskever, Deep Double Descent: Where Bigger Models and More Data Hurt (ICLR 2020) — 모델 크기·epoch·표본 수 방향의 double descent를 딥넷에서 체계적으로 관찰.Systematic observation of double descent in deep nets along model size, epochs and sample count.
- Hastie, Montanari, Rosset, Tibshirani, Surprises in High-Dimensional Ridgeless Least Squares Interpolation (Annals of Statistics, 2022) — 최소 노름 보간의 test 오차를 정확히 계산. p/n = 1에서의 발산과 그 너머의 감소.Computes the test error of min-norm interpolation exactly: the blow-up at p/n = 1 and the decrease beyond it.
- Bartlett, Long, Lugosi, Tsigler, Benign Overfitting in Linear Regression (PNAS 2020) — 잡음을 완벽히 보간하고도 잘 일반화하는 조건을 공분산 스펙트럼으로 규정.Characterises, through the covariance spectrum, when a model can interpolate noise perfectly and still generalise well.
- Zhang, Bengio, Hardt, Recht, Vinyals, Understanding deep learning requires rethinking generalization (ICLR 2017) — 신경망이 무작위 레이블도 외울 수 있다는 실험. 고전적 복잡도 경계의 한계를 드러냈다.The experiment showing neural networks can memorise even random labels; it exposed the limits of classical complexity bounds.
- Muennighoff et al., Scaling Data-Constrained Language Models (NeurIPS 2023) — 데이터를 몇 epoch 반복해도 되는가. LLM 사전학습에서의 "과적합" 질문.How many epochs can data be repeated? The "overfitting" question in LLM pre-training.
- Nakkiran, Venkat, Kakade, Ma, Optimal Regularization Can Mitigate Double Descent (ICLR 2021) — 최적으로 조정한 ridge 정규화가 double descent의 봉우리를 없앤다는 결과.Shows that optimally tuned ridge regularisation removes the double-descent peak.