“Training a model” is such a familiar phrase that it is easy to forget its definition. This lesson writes that definition in one line and gets its hands on the trap hidden in it: the number we minimise is not the number we want. Every later lesson (gradient descent, cross-entropy, regularisation, Adam, and even the KL penalty of LLM post-training) is a story about the gap between those two numbers.
Four ingredients
Supervised learning is fixed by four things.
- The data distribution . Pairs of inputs and answers come from it. We do not know ; we only see a sample from it. We assume the samples are independent and identically distributed (i.i.d.).
- The hypothesis class . The collection of functions we are allowed to choose from. “Polynomials of degree at most 3” and “Transformers with this architecture” are both hypothesis classes. A parameter points to one element of it.
- The loss . How wrong a single prediction is. For regression, ; for classification, .
- The optimisation algorithm. The procedure that actually finds a good inside . Gradient descent in the next lesson is the standard example.
Risk and empirical risk
What we really want is the average loss on data we have never seen, the expected risk.
But we do not know , so this expectation cannot be computed. All we can compute is the sample average, the empirical risk.
Empirical risk minimisation (ERM) picks . What the gradient descent lesson calls is exactly this . By the law of large numbers, for any fixed . The problem is that is not fixed. It was chosen by looking at that very sample, so it is biased toward whatever happens to look small on that sample by luck. In general, therefore,
and the difference is called the generalization gap.
As an extreme example, consider a “lookup-table model” that stores the whole training set and returns the stored when it sees the same , and an arbitrary value otherwise. Its training loss is exactly 0, yet it is useless on new inputs. If the hypothesis class is large enough, ERM can always pick such a solution. So the key question becomes: what prevents it?
Example: polynomial regression and least squares
One-dimensional input , true function , observations with . The hypothesis class is polynomials of degree at most .
are the features. The important point is that the model is nonlinear in but linear in . That is why ERM with the squared loss has a closed-form solution. Let the matrix have as its -th row; then
Setting the gradient to 0 gives the normal equations.
For to be invertible there must be at least distinct . Geometrically, is the orthogonal projection of onto the column space of , and the residual is orthogonal to every column (). The Hessian of this loss is , so the condition-number problem from the gradient descent lesson shows up here unchanged. That is why, in practice, one does not solve the normal equations directly but uses QR or SVD.
If , is square and the curve passes exactly through every training point (interpolation). The training loss is 0. Let us see what happens in the figure below.
“모델을 학습시킨다”는 말은 너무 익숙해서 정의를 잊기 쉽다. 이 레슨은 그 정의를 한 줄로 적고, 그 한 줄에 숨은 함정, 즉 우리가 줄이는 숫자와 우리가 원하는 숫자가 다르다는 사실을 손으로 만져 본다. 이후 모든 레슨(경사하강법, cross-entropy, 정규화, Adam, 그리고 LLM 사후학습의 KL 페널티까지)은 이 두 숫자 사이의 간극을 다루는 이야기다.
네 가지 재료
지도학습(supervised learning)은 네 가지로 정해진다.
- 데이터 분포 . 입력과 정답의 쌍 가 여기서 나온다. 우리는 를 모르고, 그 표본 만 본다. 표본들은 서로 독립이고 같은 분포를 따른다고(i.i.d.) 가정한다.
- 가설 집합(hypothesis class) . 우리가 고를 수 있는 함수들의 모음이다. “차수 3 이하 다항식”, “이 구조의 Transformer”가 모두 가설 집합이다. 매개변수 가 그 안의 한 원소를 가리킨다.
- 손실(loss) . 예측 하나가 얼마나 틀렸는지. 회귀라면 , 분류라면 .
- 최적화 알고리즘. 안에서 좋은 를 실제로 찾는 절차. 다음 레슨의 경사하강법이 대표다.
위험과 경험적 위험
우리가 진짜로 원하는 것은 처음 보는 데이터에서의 평균 손실, 곧 기대 위험(expected risk) 이다.
그런데 를 모르니 이 기댓값은 계산할 수 없다. 계산할 수 있는 것은 표본 평균, 경험적 위험(empirical risk) 뿐이다.
경험적 위험 최소화(ERM, empirical risk minimization) 는 를 고르는 것이다. 경사하강법 레슨에서 라고 부른 것이 바로 이 이다. 대수의 법칙에 따라 고정된 하나에 대해서는 이다. 문제는 가 고정되어 있지 않다는 데 있다. 는 바로 그 표본을 보고 골랐으므로, 그 표본에서 운 좋게 작아 보이는 쪽으로 치우쳐 있다. 그래서 일반적으로
이고, 그 차이 를 일반화 간극(generalization gap) 이라 부른다.
극단적인 예로, 훈련 표본을 통째로 저장했다가 똑같은 가 오면 저장된 를, 아니면 아무 값이나 내는 “조회표 모델”을 생각해 보자. 훈련 손실은 정확히 0이지만 새 입력에서는 쓸모가 없다. 가설 집합이 충분히 크면 ERM은 언제든 이런 해를 고를 수 있다. 그러니 무엇이 이를 막는지가 핵심 질문이 된다.
예제: 다항식 회귀와 최소제곱
1-D 입력 , 참 함수 , 관측 , . 가설 집합은 차수 이하 다항식이다.
는 특징(feature) 이다. 모델은 에 대해서는 비선형이지만 에 대해서는 선형이라는 점이 중요하다. 그래서 제곱 손실의 ERM은 닫힌 해를 갖는다. 행렬 의 번째 행을 로 두면
기울기를 0으로 놓으면 정규방정식(normal equations) 이 나온다.
가 가역이려면 서로 다른 가 적어도 개 있어야 한다. 기하학적으로 는 를 의 열공간에 정사영한 것이고, 잔차 는 모든 열과 직교한다(). 이 손실의 Hessian은 다. 경사하강법 레슨에서 본 조건수 문제가 그대로 여기서 나온다. 그래서 실제 계산에서는 정규방정식을 직접 풀지 않고 QR이나 SVD를 쓴다.
이면 는 정사각 행렬이 되고, 곡선은 모든 훈련 점을 정확히 지난다(보간, interpolation). 훈련 손실은 0이다. 아래 그림에서 무슨 일이 생기는지 보자.
- Raise d from 0 → 3 and the train and test errors fall together. Degrees 0 and 1 cannot represent the bends of . This is underfitting.
- Raise d up to n−1 and the train error goes to 0 while the test error grows tens to hundreds of times. The curve swings wildly between the points and ‖θ‖ explodes. This is overfitting.
- In the overfitting regime, drag one point slightly. The whole curve lurches. The model has memorised even the noise in the data.
- Raise n to 30 and the curve behaves itself even at the same d=9. With more data, a large hypothesis class becomes affordable.
Error comes from three places
Measured against the best possible predictor (in this example , with risk ), the excess risk of the we actually obtained splits into three terms (Bottou & Bousquet).
First, notation. is the element of with the smallest expected risk, is the element with the smallest empirical risk (the ERM solution), and is what the optimisation algorithm actually returned. Then the identity
holds (the middle terms cancel).
- Approximation error: . It arises because the hypothesis class cannot represent the true function. It shrinks as grows. d=0, 1 in the figure.
- Estimation error: . It arises because we chose from a finite sample. It grows as grows and shrinks as grows. d=n−1 in the figure.
- Optimization error: . It arises because we do not solve the ERM problem exactly. For least squares there is a closed-form solution, so it is 0, but for neural networks it cannot be ignored.
The tug-of-war between overfitting and underfitting is the balance between the first two terms. The generalization lesson computes it exactly as the bias–variance decomposition.
How large a hypothesis class is fine?
Working out the simplest case turns the intuition “size of the hypothesis class versus amount of data” into a number. Suppose the loss lies in and is finite. For a single fixed , is an average of independent random variables, so Hoeffding’s inequality applies.
was chosen by looking at the data, so this inequality cannot be applied to it directly. Instead we use a union bound so that it holds for every element of at once. The failure probability is at most ; setting this to and solving for gives, with probability at least , for all ,
The gap has the form . The larger the hypothesis class and the less data, the less you should trust the training loss. For models with continuous parameters, an “effective size” such as the VC dimension or Rademacher complexity takes the place of . Modern deep learning, however, often generalises well even with more parameters than data points, so such uniform bounds alone do not explain enough. We return to this puzzle with double descent in the generalization lesson.
Train, validation, test
Estimating requires data that was not used for learning. So we split the data three ways.
| Set | Purpose | Who has effectively “seen” the data |
|---|---|---|
| train | optimise | gradient descent |
| validation | choose hyperparameters such as the degree , learning rate and regularisation strength; early stopping | people and the hyperparameter search |
| test | report final performance; look at it only once | no one |
Choosing hyperparameters by validation performance is itself a kind of ERM. So after dozens of choices, the validation score bends optimistically too. If you keep peeking at the test set while fixing the model, the same thing happens to the test set. This effect is called adaptive overfitting, and it is one reason public benchmarks become less trustworthy over time.
Surrogate losses
In classification, what we really want to reduce is usually the misclassification rate, i.e. the 0–1 loss . But this function has zero gradient with respect to almost everywhere and is discontinuous, so it cannot be optimised by gradient descent. Instead we minimise a surrogate loss that is differentiable and bounds the 0–1 loss from above. Cross-entropy is the most common. Why the surrogate is in particular is explained via maximum likelihood two lessons from now. For now, just remember that this opens one more gap between “what we optimise” and “what we want”.
Implementing it
We run the same experiment as the figure in NumPy. np.linalg.lstsq solves least squares with an SVD-based method instead of the normal equations.
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x) # true function (unknown to the learner)
sigma = 0.25
def make_data(n):
x = rng.uniform(0, 1, n)
return x, f(x) + sigma * rng.normal(size=n)
x_tr, y_tr = make_data(12) # training set: what we get to see
x_te, y_te = make_data(5000) # test set: an estimate of the expected risk R(θ)
def features(x, d):
# [1, t, t², ..., t^d], t = 2x−1 ∈ [−1, 1] (shifting the interval lowers the condition number)
return np.vander(2 * x - 1, d + 1, increasing=True)
def fit(x, y, d):
X = features(x, d)
theta, *_ = np.linalg.lstsq(X, y, rcond=None) # argmin ||Xθ − y||²
return theta
def mse(theta, x, y):
return np.mean((features(x, len(theta) - 1) @ theta - y) ** 2)
print(f"noise floor σ² = {sigma**2:.4f} (no model can push the test MSE below this)\n")
print(" d #param train MSE test MSE ||θ||")
for d in range(0, 12):
theta = fit(x_tr, y_tr, d)
print(f"{d:2d} {d+1:5d} {mse(theta, x_tr, y_tr):9.2e} {mse(theta, x_te, y_te):9.2e} {np.linalg.norm(theta):9.1f}")Around d=3 the test MSE is closest to the noise floor ; at d=11 (= n−1) the train MSE is 0 up to machine precision and the test MSE is hundreds of times larger. Let us also check whether the normal equations really give the same answer, and why they are not used in practice.
for d in [3, 9, 11]:
X = features(x_tr, d)
th_ne = np.linalg.solve(X.T @ X, X.T @ y_tr) # normal equations
th_ls = fit(x_tr, y_tr, d)
print(f"d={d:2d} cond(XᵀX)={np.linalg.cond(X.T @ X):9.2e} "
f"|θ_ne − θ_lstsq| = {np.linalg.norm(th_ne - th_ls):.2e}")Since , the normal equations square the condition number. The growing difference between the two solutions as the degree rises is due to numerical error.
You fit a degree d = 11 polynomial by least squares to n = 12 training points with distinct x. Which of the following is always true?
With parameters and distinct , the Vandermonde matrix is square and invertible. So there is a that solves exactly, and the train error is 0. The test error is usually large, but if there is almost no noise and the true function is smooth it can be small, so “necessarily” does not hold. Lower σ to 0.05 in the figure and check.
Summary
- Learning = data distribution , hypothesis class , loss , optimisation algorithm. What we want is the expected risk ; what we can compute is the empirical risk .
- ERM minimises . Because it was chosen by looking at the data, is an optimistic estimate of .
- Error = approximation (hypothesis class too small) + estimation (too little data) + optimisation (not fully solved). Model size is the tug-of-war between the first two.
- For a finite hypothesis class the generalization gap is of order . Bigger models need more data.
- Hyperparameters by validation, the final report by a test set you look at once. Every time you peek, that set becomes a little more like train.
- d를 0 → 3으로 올리면 train과 test 오차가 함께 떨어진다. 차수 0, 1은 의 굴곡을 표현할 수 없다. 이것이 과소적합(underfitting) 이다.
- d를 n−1까지 올리면 train 오차는 0으로 가는데 test 오차는 수십~수백 배로 커진다. 곡선이 점 사이에서 미친 듯이 출렁이고 ‖θ‖가 폭발한다. 과적합(overfitting) 이다.
- 과적합 상태에서 점 하나를 살짝 끌어 보자. 곡선 전체가 크게 요동친다. 모델이 데이터의 잡음까지 외우고 있기 때문이다.
- n을 30으로 올리면 같은 d=9에서도 곡선이 얌전하다. 데이터가 많으면 큰 가설 집합도 감당할 수 있다.
오차는 세 군데에서 나온다
가능한 최선의 예측기(이 예제에서는 , 위험은 )를 기준으로, 우리가 실제로 얻은 의 초과 위험은 세 항으로 쪼갤 수 있다(Bottou & Bousquet).
기호부터 정하자. 는 안에서 기대 위험이 가장 작은 원소, 는 경험적 위험이 가장 작은 원소(ERM 해), 는 최적화 알고리즘이 실제로 돌려준 값이다. 그러면 항등식
이 성립한다(가운데 항들이 서로 지워진다).
- 근사 오차(approximation): . 가설 집합이 참 함수를 표현하지 못해서 생긴다. 를 키우면 줄어든다. 그림의 d=0, 1.
- 추정 오차(estimation): . 유한한 표본으로 골랐기 때문에 생긴다. 를 키우면 커지고, 을 키우면 줄어든다. 그림의 d=n−1.
- 최적화 오차(optimization): . ERM 문제를 정확히 풀지 못해서 생긴다. 최소제곱은 닫힌 해가 있어 0이지만, 신경망에서는 무시할 수 없다.
과적합–과소적합의 줄다리기는 앞의 두 항 사이의 균형이다. 일반화 레슨에서 이것을 bias–variance 분해로 정확히 계산한다.
얼마나 큰 가설 집합까지 괜찮은가
가장 단순한 경우를 계산해 보면 “가설 집합의 크기 대 데이터의 양”이라는 직관이 숫자로 나온다. 손실이 안에 있고 가 유한하다고 하자. 고정된 하나에 대해 는 독립 확률변수 개의 평균이므로 Hoeffding 부등식이 성립한다.
는 데이터를 보고 고른 것이라 이 부등식을 바로 쓸 수 없다. 대신 의 모든 원소에 대해 동시에 성립하도록 union bound를 쓴다. 실패 확률이 이하이므로, 이것을 로 놓고 에 대해 풀면 확률 이상으로 모든 에 대해
간극은 꼴이다. 가설 집합이 클수록, 데이터가 적을수록 훈련 손실을 덜 믿어야 한다. 연속 매개변수 모델에서는 자리에 VC 차원이나 Rademacher 복잡도 같은 “실효 크기”가 들어간다. 다만 현대 딥러닝은 매개변수가 데이터보다 많아도 잘 일반화하는 경우가 흔해서, 이런 균일 경계만으로는 설명이 부족하다. 이 퍼즐은 일반화 레슨의 double descent에서 다시 다룬다.
훈련·검증·테스트
를 추정하려면 학습에 쓰지 않은 데이터가 필요하다. 그래서 데이터를 셋으로 나눈다.
| 집합 | 용도 | 무엇이 그 데이터를 “본” 셈인가 |
|---|---|---|
| train | 최적화 | 경사하강법 |
| validation | 차수 , 학습률, 정규화 강도 같은 하이퍼파라미터 선택, early stopping | 사람과 하이퍼파라미터 탐색 |
| test | 최종 성능 보고. 한 번만 본다 | 아무도 |
validation 성능을 보고 하이퍼파라미터를 고르는 것도 일종의 ERM이다. 그러니 수십 번 고르고 나면 validation 점수도 낙관적으로 휜다. test 집합을 여러 번 들여다보며 모델을 고치면 같은 일이 test에서 일어난다. 이 효과를 적응적 과적합(adaptive overfitting) 이라 부르고, 공개 벤치마크가 시간이 지나며 덜 믿을 만해지는 이유 중 하나다.
대리 손실
분류에서 정말 줄이고 싶은 것은 보통 오분류율, 즉 0–1 손실 이다. 하지만 이 함수는 에 대해 거의 모든 곳에서 기울기가 0이고 불연속이라 경사하강법으로 최적화할 수 없다. 그래서 미분 가능하고 0–1 손실을 위에서 누르는 대리 손실(surrogate loss) 을 대신 최소화한다. cross-entropy가 가장 대표적이다. 대리 손실이 왜 하필 인지는 다음다음 레슨에서 최대우도로 설명한다. 여기서는 “최적화하는 대상”과 “원하는 것” 사이에 간극이 하나 더 생긴다는 점만 기억하자.
직접 구현하기
그림과 같은 실험을 NumPy로 한다. np.linalg.lstsq는 정규방정식 대신 SVD 기반으로 최소제곱을 푼다.
import numpy as np
rng = np.random.default_rng(0)
f = lambda x: np.sin(2 * np.pi * x) # 참 함수 (학습자는 모른다)
sigma = 0.25
def make_data(n):
x = rng.uniform(0, 1, n)
return x, f(x) + sigma * rng.normal(size=n)
x_tr, y_tr = make_data(12) # 훈련 집합: 우리가 보는 것
x_te, y_te = make_data(5000) # 테스트 집합: 기대 위험 R(θ)의 추정치
def features(x, d):
# [1, t, t², ..., t^d], t = 2x−1 ∈ [−1, 1] (구간을 옮겨 조건수를 줄인다)
return np.vander(2 * x - 1, d + 1, increasing=True)
def fit(x, y, d):
X = features(x, d)
theta, *_ = np.linalg.lstsq(X, y, rcond=None) # argmin ||Xθ − y||²
return theta
def mse(theta, x, y):
return np.mean((features(x, len(theta) - 1) @ theta - y) ** 2)
print(f"잡음 바닥 σ² = {sigma**2:.4f} (어떤 모델도 test MSE를 이보다 줄일 수 없다)\n")
print(" d #param train MSE test MSE ||θ||")
for d in range(0, 12):
theta = fit(x_tr, y_tr, d)
print(f"{d:2d} {d+1:5d} {mse(theta, x_tr, y_tr):9.2e} {mse(theta, x_te, y_te):9.2e} {np.linalg.norm(theta):9.1f}")d=3 근처에서 test MSE가 잡음 바닥 에 가장 가깝고, d=11(= n−1)에서 train MSE는 기계 정밀도 수준의 0, test MSE는 수백 배가 된다. 정규방정식이 정말 같은 답을 주는지, 그리고 왜 실전에서는 쓰지 않는지도 확인해 보자.
for d in [3, 9, 11]:
X = features(x_tr, d)
th_ne = np.linalg.solve(X.T @ X, X.T @ y_tr) # 정규방정식
th_ls = fit(x_tr, y_tr, d)
print(f"d={d:2d} cond(XᵀX)={np.linalg.cond(X.T @ X):9.2e} "
f"|θ_ne − θ_lstsq| = {np.linalg.norm(th_ne - th_ls):.2e}")이므로 정규방정식은 조건수를 제곱으로 악화시킨다. 차수가 높아질수록 두 해의 차이가 커지는 것은 수치 오차 때문이다.
서로 다른 x를 가진 훈련 점 n = 12개에 차수 d = 11 다항식을 최소제곱으로 맞췄다. 다음 중 항상 참인 것은?
매개변수가 개이고 가 서로 다르면 Vandermonde 행렬 는 정사각이고 가역이다. 따라서 를 정확히 푸는 가 있고 train 오차는 0이다. test 오차는 대개 크지만, 잡음이 거의 없고 참 함수가 매끄러우면 작을 수도 있으니 “반드시”는 아니다. 그림에서 σ를 0.05로 내리고 확인해 보자.
정리
- 학습 = 데이터 분포 , 가설 집합 , 손실 , 최적화 알고리즘. 우리가 원하는 것은 기대 위험 , 계산할 수 있는 것은 경험적 위험 다.
- ERM은 을 최소화한다. 데이터를 보고 골랐으므로 는 의 낙관적인 추정치다.
- 오차 = 근사(가설 집합이 작음) + 추정(데이터가 적음) + 최적화(덜 풀었음). 모델 크기는 앞의 둘 사이의 줄다리기다.
- 유한 가설 집합에서 일반화 간극은 규모다. 큰 모델일수록 더 많은 데이터가 필요하다.
- 하이퍼파라미터는 validation으로, 최종 보고는 한 번만 보는 test로. 들여다볼 때마다 그 집합은 조금씩 train이 된다.
더 읽을거리Further reading
- Bishop, Pattern Recognition and Machine Learning §1.1 (Springer, 2006) — sin(2πx)에 다항식을 맞추는 바로 이 예제의 원조. 차수에 따른 과적합 그림이 유명하다.The original of this very example, fitting polynomials to sin(2πx). Its figure of overfitting versus degree is famous.
- Shalev-Shwartz & Ben-David, Understanding Machine Learning, Ch. 2–4 (Cambridge, 2014) — ERM, 가설 집합, 유한 가설 집합의 일반화 경계를 가장 깔끔하게 정리한 교과서.The cleanest textbook treatment of ERM, hypothesis classes and generalisation bounds for finite hypothesis classes.
- Hastie, Tibshirani, Friedman, The Elements of Statistical Learning Ch. 7 (2nd ed., 2009) — 훈련 오차·테스트 오차·모델 선택·교차검증의 표준 레퍼런스.The standard reference on training error, test error, model selection and cross-validation.
- Bottou & Bousquet, The Tradeoffs of Large Scale Learning (NeurIPS 2007) — 오차를 근사·추정·최적화 오차로 나누고, 데이터가 많을 때는 최적화가 병목이 된다는 관점.Splits the error into approximation, estimation and optimisation error, with the view that optimisation becomes the bottleneck when data is plentiful.
- Vapnik, Principles of Risk Minimization for Learning Theory (NeurIPS 1991) — 경험적 위험 최소화(ERM)라는 틀을 정식화한 고전.The classic that formalised the framework of empirical risk minimisation (ERM).