So far everything has been supervised learning with a target . Without labels, what do we minimise? The oldest answer, still in use, is “the error when you summarise the data with a restricted code and then restore it”. Restrict the code to “one of representative points” and you get k-means; restrict it to “-dimensional linear coordinates” and you get PCA. Both minimise the squared reconstruction error.
LLM pre-training is in fact in the same family: it is self-supervised learning that predicts the data itself (the next token) without making separate labels. The two algorithms in this lesson are its simplest forms.
k-means
Split data into clusters. Choose each point’s membership and the cluster centres jointly.
is discrete and is continuous, so solving both at once is hard (NP-hard in general). So we do coordinate descent: fix one side and solve for the other. This is Lloyd’s algorithm.
- Assign: with fixed, each can be solved independently — pick the nearest centre: .
- Update: with fixed, is a quadratic in each . From , = the mean of its member points.
Both steps minimise exactly with respect to their variable, so never increases. And since there are finitely many possible partitions (at most ) and the algorithm stops when it returns to the same partition, it terminates in finitely many steps. But where it stops is only “a point that cannot be improved by changing just one side”; there is no guarantee it is the global minimum. The initial values decide the result.
k-means++: choosing the initial values well
If you pick random points, it often happens that one blob gets two centres while another gets none. Lloyd cannot fix this: even if one centre straddles two blobs, assignment and update justify each other. k-means++ picks the centres one at a time, but makes points farther from the already chosen centres more likely to be picked.
- Draw the first centre uniformly from the data.
- For each point, compute the distance to the nearest existing centre, and draw the next centre with probability .
- Repeat until there are , then run Lloyd.
Arthur & Vassilvitskii (2007) showed that this initialisation alone is, in expectation, within times the optimum. Since a blob that is already covered becomes unlikely to be picked again, the centres are likely to land one per blob.
지금까지는 모두 정답 가 있는 지도학습이었다. 레이블이 없으면 무엇을 최소화하는가? 가장 오래되고 지금도 쓰이는 답은 “데이터를 제한된 코드로 요약했다가 다시 복원할 때의 오차” 다. 코드를 “개의 대표점 중 하나”로 제한하면 k-means, “차원 선형 좌표”로 제한하면 PCA가 된다. 둘 다 제곱 재구성 오차를 최소화한다.
사실 LLM 사전학습도 같은 계열이다. 레이블을 따로 만들지 않고 데이터 자신(다음 토큰)을 맞추는 자기지도 학습이기 때문이다. 이 레슨의 두 알고리즘은 그 가장 단순한 형태다.
k-means
데이터 를 개의 군집으로 나눈다. 각 점의 소속 와 군집 중심 를 동시에 고른다.
는 이산, 는 연속이라 한 번에 풀기 어렵다(일반적으로 NP-hard다). 그래서 한쪽을 고정하고 다른 쪽을 푸는 좌표 하강을 한다. 이것이 Lloyd 알고리즘이다.
- 할당(assign): 를 고정하면 각 는 독립적으로 풀린다. 가장 가까운 중심을 고르면 된다. .
- 갱신(update): 를 고정하면 는 각 에 대한 이차식이다. 에서 = 소속 점들의 평균.
두 단계 모두 를 그 변수에 대해 정확히 최소화하므로 는 절대 증가하지 않는다. 그리고 가능한 분할은 유한 개( 이하)이고 같은 분할로 돌아오면 멈추므로, 알고리즘은 유한 번 안에 끝난다. 다만 끝난 곳은 “어느 한쪽만 바꿔서는 나아지지 않는 점”일 뿐 전역 최소라는 보장이 없다. 초기값이 결과를 좌우한다.
k-means++: 초기값을 잘 고르기
무작위로 개 점을 고르면 한 덩어리에 중심이 둘 들어가고 다른 덩어리에는 하나도 없는 일이 흔하다. Lloyd는 이것을 고치지 못한다. 중심 하나가 두 덩어리 사이에 걸쳐 있어도 할당과 갱신이 서로를 정당화하기 때문이다. k-means++ 는 중심을 하나씩 고르되 이미 고른 중심에서 먼 점일수록 뽑힐 확률을 높인다.
- 첫 중심은 데이터에서 균등하게 뽑는다.
- 각 점에서 가장 가까운 기존 중심까지의 거리 를 구하고, 다음 중심을 확률 로 뽑는다.
- 개가 될 때까지 반복한 뒤 Lloyd를 돌린다.
Arthur & Vassilvitskii(2007)는 이 초기화만으로도 기댓값이 최적의 배 이내임을 보였다. 이미 덮인 덩어리에서 또 뽑힐 확률이 낮아지니, 서로 다른 덩어리에 하나씩 들어갈 가능성이 크다.
- Press ① Assign and ② Update alternately. On the right, the blue dots (after assignment) and red dots (after update) go down like stairs and never go up once.
- Press “Re-initialise” a few times and run ”▶ Run to convergence”. With random initialisation it sometimes ends with one centre occupying two blobs; the final J is clearly larger. Switch to k-means++ and this becomes rare.
- Drag one centre into a blob that already has another centre and let it converge. You can build a bad local minimum yourself.
- Converge “elongated blobs” with k = 3 and you may get regions cut vertically instead of the three long horizontal strips, because that partition has a smaller J. k-means assumes every cluster is round and of the same size. With “blobs of different sizes” it also prefers to split the large blob.
How do you choose k? always decreases as grows ( when ), so by itself it cannot be the criterion. Look for the point where suddenly decreases less (the elbow), use the silhouette score, or use the performance of the downstream task that consumes the clusters.
import numpy as np
rng = np.random.default_rng(0)
# 2-D, 8 blobs on a 4×2 grid
centers = np.array([[i, j] for i in (-3, -1, 1, 3) for j in (-1.5, 1.5)], float)
X = np.concatenate([c + 0.35 * rng.normal(size=(40, 2)) for c in centers])
def kmeans_pp_init(X, k, rng):
C = [X[rng.integers(len(X))]] # first centre: uniform
for _ in range(k - 1):
D2 = np.min(((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1), axis=1) # squared distance to nearest centre
C.append(X[rng.choice(len(X), p=D2 / D2.sum())]) # sample proportional to D²
return np.array(C)
def lloyd(X, C, max_iter=100):
J_hist = []
for it in range(max_iter):
D2 = ((X[:, None, :] - C[None]) ** 2).sum(-1) # (n, k)
z = D2.argmin(1) # ① assign
J_hist.append(D2[np.arange(len(X)), z].sum())
C_new = np.array([X[z == j].mean(0) if np.any(z == j) else C[j] for j in range(len(C))]) # ② update
if np.allclose(C_new, C):
break
C = C_new
return C, z, np.array(J_hist)
k, trials = 8, 20
results = {}
for name in ["random", "k-means++"]:
Js = []
for trial in range(trials):
r = np.random.default_rng(trial)
C0 = X[r.choice(len(X), k, replace=False)] if name == "random" else kmeans_pp_init(X, k, r)
C, z, J = lloyd(X, C0)
assert np.all(np.diff(J) <= 1e-9) # the objective never goes up
Js.append(J[-1])
results[name] = np.array(Js)
best = min(v.min() for v in results.values())
print(f"best J = {best:.1f} (roughly the global minimum)\n")
for name, Js in results.items():
print(f"{name:10s} mean J {Js.mean():6.1f} worst {Js.max():6.1f} "
f"within 1% of best in {np.sum(Js < best * 1.01):2d} of {trials} runs")With around 8 blobs, random initialisation does not reach a good solution even once in 20 runs, while k-means++ reaches it more than half the time. In practice you run k-means++ initialisation several times and keep the result with the smallest J.
GMM and EM: soft k-means
The k-means assignment is 0 or 1; even a point near the boundary belongs 100% to one side. Making it probabilistic gives the Gaussian mixture model (GMM).
We would like to use the MLE of the probability lesson directly, but the leaves no closed-form solution. EM (expectation–maximization) solves it with exactly the same two-step structure as k-means.
E-step (soft assignment): compute the posterior probability that each point came from each cluster, the responsibility.
M-step (weighted update): the mean, covariance and proportion weighted by responsibility. , , , .
The relation to k-means is exact. Fix every cluster’s covariance to and send : the numerator of is , so the nearest centre dominates and the responsibilities harden to 0/1. The E-step then becomes the k-means assignment and the M-step the mean update. k-means is the zero-variance limit of an isotropic GMM. That is why k-means assumes “round clusters of the same size”. A GMM that learns its covariances also captures elongated blobs.
EM is monotone like Lloyd: the log-likelihood never decreases from one iteration to the next. The proof uses the same ingredients as Gibbs’ inequality (Jensen) from the probability lesson: the E-step makes a lower bound on the log-likelihood (the ELBO) tight, and the M-step raises it. This ELBO reappears as the training objective of VAEs and diffusion models.
PCA: the direction of greatest spread
This time we restrict the code to “-dimensional linear coordinates”. Start with . Centre the data (subtract ) and let the covariance be . The variance of the coordinate projected onto a unit vector is
Variance maximisation. Maximise subject to . Differentiating the Lagrangian and setting it to 0 gives
must be an eigenvector of , and then the variance is . So the answer is the eigenvector of the largest eigenvalue. This is the first principal component (PC1). For dimensions, take the top eigenvectors (they are mutually orthogonal because is symmetric).
Reconstruction-error minimisation. The same answer also comes from the opposite direction. Project a point onto and restore it as ; the residual is orthogonal to , so by Pythagoras
Averaging, . The left side is a constant independent of (the total variance), so maximising variance and minimising reconstruction error are the same problem. With components, the mean reconstruction error is the sum of the discarded eigenvalues . When Pearson (1901) first conceived PCA, it was from this “line of closest fit” side.
- ① 할당과 ② 갱신을 번갈아 눌러 보자. 오른쪽에서 파란 점(할당 후)과 빨간 점(갱신 후)이 계단처럼 내려가고 한 번도 올라가지 않는다.
- “다시 초기화”를 몇 번 누르며 ”▶ 수렴까지”를 돌려 보자. 무작위 초기화에서는 가끔 덩어리 두 개를 중심 하나가 차지하고 끝난다. 최종 J가 확연히 크다. k-means++로 바꾸면 이런 일이 드물다.
- 중심 하나를 끌어서 다른 중심이 있는 덩어리 안으로 넣고 수렴시켜 보자. 나쁜 국소 최소를 직접 만들 수 있다.
- “길쭉한 덩어리” 에서 k = 3으로 수렴시키면, 가로로 긴 세 띠 대신 세로로 자른 영역이 나오기도 한다. 그 분할의 J가 더 작기 때문이다. k-means는 모든 군집이 같은 크기의 둥근 모양이라고 가정한다. “크기가 다른 덩어리”에서도 큰 덩어리를 쪼개는 쪽을 선호한다.
k는 어떻게 고르나? 는 를 늘릴수록 무조건 줄어서(이면 0) 그 자체로는 기준이 되지 못한다. 가 갑자기 덜 줄어드는 지점(elbow)을 보거나, 실루엣 점수, 혹은 군집을 쓰는 다운스트림 작업의 성능으로 고른다.
import numpy as np
rng = np.random.default_rng(0)
# 2-D, 4×2 격자 위의 덩어리 8개
centers = np.array([[i, j] for i in (-3, -1, 1, 3) for j in (-1.5, 1.5)], float)
X = np.concatenate([c + 0.35 * rng.normal(size=(40, 2)) for c in centers])
def kmeans_pp_init(X, k, rng):
C = [X[rng.integers(len(X))]] # 첫 중심: 균등하게
for _ in range(k - 1):
D2 = np.min(((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1), axis=1) # 가장 가까운 중심까지 거리²
C.append(X[rng.choice(len(X), p=D2 / D2.sum())]) # D² 에 비례해 뽑는다
return np.array(C)
def lloyd(X, C, max_iter=100):
J_hist = []
for it in range(max_iter):
D2 = ((X[:, None, :] - C[None]) ** 2).sum(-1) # (n, k)
z = D2.argmin(1) # ① 할당
J_hist.append(D2[np.arange(len(X)), z].sum())
C_new = np.array([X[z == j].mean(0) if np.any(z == j) else C[j] for j in range(len(C))]) # ② 갱신
if np.allclose(C_new, C):
break
C = C_new
return C, z, np.array(J_hist)
k, trials = 8, 20
results = {}
for name in ["random", "k-means++"]:
Js = []
for trial in range(trials):
r = np.random.default_rng(trial)
C0 = X[r.choice(len(X), k, replace=False)] if name == "random" else kmeans_pp_init(X, k, r)
C, z, J = lloyd(X, C0)
assert np.all(np.diff(J) <= 1e-9) # 목적함수는 절대 오르지 않는다
Js.append(J[-1])
results[name] = np.array(Js)
best = min(v.min() for v in results.values())
print(f"가장 좋은 J = {best:.1f} (대략 전역 최소)\n")
for name, Js in results.items():
print(f"{name:10s} 평균 J {Js.mean():6.1f} 최악 {Js.max():6.1f} "
f"{trials}회 중 최선의 1% 이내: {np.sum(Js < best * 1.01):2d}회")덩어리가 8개쯤 되면 무작위 초기화는 20번 중 한 번도 좋은 해에 도달하지 못하고, k-means++는 절반 넘게 도달한다. 실전에서는 k-means++ 초기화로 여러 번 돌려 J가 가장 작은 결과를 쓴다.
GMM과 EM: 부드러운 k-means
k-means의 할당은 0 아니면 1이다. 경계 근처의 점도 한쪽에 100% 속한다. 이것을 확률로 풀면 가우시안 혼합 모델(GMM) 이 된다.
확률 레슨의 MLE를 그대로 쓰고 싶지만 때문에 닫힌 해가 없다. EM(expectation–maximization) 은 k-means와 똑같은 두 단계 구조로 푼다.
E-step (부드러운 할당): 각 점이 각 군집에서 나왔을 사후확률, 곧 책임(responsibility) 을 계산한다.
M-step (가중 갱신): 책임을 가중치로 쓴 평균·공분산·비율. , , , .
k-means와의 관계가 정확하다. 모든 군집의 공분산을 로 고정하고 으로 보내면, 의 분자는 이라 가장 가까운 중심 하나가 압도하고 책임이 0/1로 굳는다. 그러면 E-step은 k-means의 할당, M-step은 평균 갱신이 된다. k-means는 등방성 GMM의 영(零)분산 극한이다. 그래서 k-means가 “같은 크기의 둥근 군집”을 가정하는 것이다. 공분산을 학습하는 GMM은 길쭉한 덩어리도 잡는다.
EM도 Lloyd처럼 단조다. 매 반복 로그우도가 줄지 않는다. 증명은 확률 레슨의 Gibbs 부등식(Jensen)과 같은 재료로, 로그우도의 하한(ELBO)을 E-step에서 꽉 맞추고 M-step에서 올리는 구조다. 이 ELBO는 VAE와 확산 모델의 학습 목표로 다시 등장한다.
PCA: 가장 많이 퍼진 방향
이번에는 코드를 “차원 선형 좌표”로 제한한다. 먼저 . 데이터를 중심화하고(를 빼고) 공분산을 라 하자. 단위벡터 방향으로 사영한 좌표 의 분산은
분산 최대화. 제약 아래 를 최대화한다. 라그랑지안 을 미분해 0으로 놓으면
는 의 고유벡터여야 하고, 그때 분산은 다. 그러니 가장 큰 고유값의 고유벡터가 답이다. 이것이 첫 번째 주성분(PC1)이다. 차원이면 위에서부터 개의 고유벡터를 쓴다(가 대칭이라 서로 직교한다).
재구성 오차 최소화. 같은 답이 반대 방향에서도 나온다. 점 를 위로 사영해 로 복원하면, 잔차는 와 직교하므로 피타고라스 정리에 의해
평균을 내면 . 왼쪽은 와 무관한 상수(전체 분산)이므로 분산을 최대화하는 것과 재구성 오차를 최소화하는 것은 같은 문제다. 개를 쓰면 평균 재구성 오차는 버린 고유값의 합 이다. Pearson(1901)이 처음 PCA를 생각한 것도 이 “가장 가깝게 맞는 직선” 쪽이었다.
- Turn the u-angle slider from 0° to 180°. On the right, the blue curve (variance along u) and the red curve (reconstruction error) move like mirror images, and their sum sticks to the dashed line (total variance). The maximum of blue is λ₁ and its minimum is λ₂.
- Press “u ← PC1” and the red line on the left overlaps the long grey arrow, and the thin residual lines become as short as possible.
- Lower the correlation to 0 and the two eigenvalues become similar while the curves on the right go almost flat. For such data the “main direction” is meaningless.
- Drag one point far out. PC1 swings sharply towards it: squared error is sensitive to outliers.
Computing it with the SVD
If the singular value decomposition of the centred data matrix is , then
That is, the columns of are the principal directions, the eigenvalues are , and each point’s principal-component coordinates are . In practice you do not form ; you compute the SVD of directly, because forming squares the condition number (the same reason as the normal equations in the first lesson). Moreover, by the Eckart–Young theorem, keeping only the top singular values, , gives the best rank- approximation in the Frobenius norm. PCA is the same thing as the optimal low-rank approximation of the data matrix.
# 20-dimensional data that actually lies near a 3-dimensional subspace (+ small noise)
n, D, r_true = 500, 20, 3
Z = rng.normal(size=(n, r_true)) * [3.0, 2.0, 1.0]
A = np.linalg.qr(rng.normal(size=(D, r_true)))[0] # orthonormal basis (D × 3)
Xh = Z @ A.T + 0.3 * rng.normal(size=(n, D)) + 5.0 # mean is not 0
Xc = Xh - Xh.mean(0) # 1) centre (skip this and PC1 becomes the mean direction)
S = Xc.T @ Xc / n # 2a) covariance → eigendecomposition
evals, evecs = np.linalg.eigh(S)
evals, evecs = evals[::-1], evecs[:, ::-1] # descending order
U, sv, Vt = np.linalg.svd(Xc, full_matrices=False) # 2b) SVD: Xc = U Σ Vᵀ
print("eigenvalues :", np.round(evals[:6], 3))
print("σ²/n (SVD) :", np.round(sv[:6] ** 2 / n, 3))
print("PC1 agreement |v·v'| =", round(abs(evecs[:, 0] @ Vt[0]), 6))
print("cumulative explained ratio:", np.round(np.cumsum(evals)[:6] / evals.sum(), 3))
for q in [1, 2, 3, 5]:
Vq = Vt[:q].T # (D, q)
Xrec = (Xc @ Vq) @ Vq.T # project, then reconstruct
err = np.mean(np.sum((Xc - Xrec) ** 2, axis=1))
print(f"q={q}: reconstruction error {err:7.3f} = sum of discarded eigenvalues {evals[q:].sum():7.3f}")The eigenvalues drop off a cliff after the third (to around the noise level ). That is the signal that the data’s “true dimension” is 3. The reconstruction error equals the sum of the discarded eigenvalues to three decimal places.
The covariance of 2-D data has eigenvalues 4 and 1. If you project onto PC1 alone and reconstruct, what are the mean squared reconstruction error and PC1's explained-variance ratio?
The reconstruction error is the sum of the discarded eigenvalues, so . The explained ratio is . Total variance 5 = projected variance 4 + reconstruction error 1 (Pythagoras).
Which statement about Lloyd's algorithm (k-means) is correct?
Assignment and update each minimise exactly with respect to and , so never increases, and because the number of partitions is finite it must stop. But where it stops is only coordinate-wise optimal, so it may not be the global minimum. k-means++ only guarantees an approximation in expectation, not the global minimum.
Summary
- k-means and PCA both minimise squared reconstruction error with a restricted code (one centre / -dimensional linear coordinates).
- In Lloyd’s algorithm, assignment and update are each exact minimisations, so J decreases monotonically and stops in finitely many steps, but it stays in local minima. k-means++‘s D² sampling greatly reduces the initialisation problem.
- EM for a GMM is k-means with soft assignment by responsibilities; sending the isotropic covariance to 0 gives exactly k-means.
- PCA: variance maximisation ⇔ ⇔ reconstruction-error minimisation (Pythagoras). Reconstruction error = sum of discarded eigenvalues.
- Compute it with the SVD of the centred data. holds the principal components, are the eigenvalues, and the truncated SVD is the optimal low-rank approximation.
- u 각도 슬라이더를 0°에서 180°까지 돌려 보자. 오른쪽 파란 곡선(u 방향 분산)과 빨간 곡선(재구성 오차)이 거울처럼 움직이고 합은 점선(전체 분산)에 붙어 있다. 파랑의 최댓값은 λ₁, 최솟값은 λ₂이다.
- “u ← PC1”을 누르면 왼쪽 빨간 선이 긴 회색 화살표와 겹치고 가는 잔차 선들이 가장 짧아진다.
- 상관을 0으로 내리면 두 고유값이 비슷해지고 오른쪽 곡선이 거의 평평해진다. 그런 데이터에서는 “주된 방향”이 의미가 없다.
- 점 하나를 멀리 끌어내 보자. PC1이 그 점 쪽으로 홱 돌아간다. 제곱 오차는 이상치에 민감하다.
SVD로 계산하기
중심화한 데이터 행렬 의 특이값 분해를 라 하면
즉 의 열이 주성분 방향이고 고유값은 , 각 점의 주성분 좌표는 다. 실전에서는 를 만들지 않고 의 SVD를 바로 계산한다. 를 만드는 순간 조건수가 제곱되기 때문이다(첫 레슨의 정규방정식과 같은 이유). 또 Eckart–Young 정리에 따르면 상위 개 특이값만 남긴 가 Frobenius 노름에서 가장 좋은 랭크 근사다. PCA는 데이터 행렬의 최적 저랭크 근사와 같은 것이다.
# 20차원 데이터인데 실제로는 3차원 부분공간 근처에 있다 (+ 작은 잡음)
n, D, r_true = 500, 20, 3
Z = rng.normal(size=(n, r_true)) * [3.0, 2.0, 1.0]
A = np.linalg.qr(rng.normal(size=(D, r_true)))[0] # 직교 기저 (D × 3)
Xh = Z @ A.T + 0.3 * rng.normal(size=(n, D)) + 5.0 # 평균이 0이 아님
Xc = Xh - Xh.mean(0) # 1) 중심화 (빼먹으면 PC1이 평균 방향이 된다)
S = Xc.T @ Xc / n # 2a) 공분산 → 고유분해
evals, evecs = np.linalg.eigh(S)
evals, evecs = evals[::-1], evecs[:, ::-1] # 내림차순
U, sv, Vt = np.linalg.svd(Xc, full_matrices=False) # 2b) SVD: Xc = U Σ Vᵀ
print("고유값 :", np.round(evals[:6], 3))
print("σ²/n (SVD) :", np.round(sv[:6] ** 2 / n, 3))
print("PC1 일치 |v·v'| =", round(abs(evecs[:, 0] @ Vt[0]), 6))
print("누적 설명 비율:", np.round(np.cumsum(evals)[:6] / evals.sum(), 3))
for q in [1, 2, 3, 5]:
Vq = Vt[:q].T # (D, q)
Xrec = (Xc @ Vq) @ Vq.T # 사영 후 재구성
err = np.mean(np.sum((Xc - Xrec) ** 2, axis=1))
print(f"q={q}: 재구성 오차 {err:7.3f} = 버린 고유값의 합 {evals[q:].sum():7.3f}")고유값이 3개 뒤에서 뚝 떨어진다(잡음 수준 근처). 데이터의 “진짜 차원”이 3이라는 신호다. 재구성 오차는 버린 고유값의 합과 소수점 셋째 자리까지 같다.
2차원 데이터의 공분산 고유값이 4와 1이다. PC1 하나로 사영했다가 복원할 때 평균 제곱 재구성 오차와 PC1의 설명 분산 비율은?
버린 고유값의 합이 재구성 오차이므로 . 설명 비율은 . 전체 분산 5 = 사영 분산 4 + 재구성 오차 1(피타고라스).
Lloyd 알고리즘(k-means)에 대해 옳은 것은?
할당과 갱신은 각각 와 에 대해 를 정확히 최소화하므로 는 증가하지 않고, 분할의 수가 유한해 반드시 멈춘다. 그러나 멈춘 곳은 좌표별로만 최적인 점이라 전역 최소가 아닐 수 있다. k-means++는 기댓값으로 배 근사를 보장할 뿐 전역 최소를 보장하지 않는다.
정리
- k-means와 PCA는 모두 제한된 코드(중심 하나 / 선형 차원 좌표)로 제곱 재구성 오차를 최소화한다.
- Lloyd 알고리즘은 할당·갱신이 각각 정확한 최소화라 J가 단조 감소하고 유한 번에 멈추지만 국소 최소에 머문다. k-means++의 D² 샘플링이 초기값 문제를 크게 줄인다.
- GMM의 EM은 책임으로 부드럽게 할당하는 k-means이고, 등방성 공분산을 0으로 보내면 정확히 k-means가 된다.
- PCA: 분산 최대화 ⇔ ⇔ 재구성 오차 최소화(피타고라스). 재구성 오차 = 버린 고유값의 합.
- 계산은 중심화한 데이터의 SVD로 한다. 가 주성분, 이 고유값, 절단 SVD가 최적의 저랭크 근사다.
더 읽을거리Further reading
- Bishop, Pattern Recognition and Machine Learning Ch. 9, 12 (Springer, 2006) — k-means·GMM·EM(9장)과 PCA·확률적 PCA(12장). k-means를 EM의 극한으로 보는 유도가 있다.k-means, GMM and EM (Ch. 9) and PCA and probabilistic PCA (Ch. 12). Includes the derivation of k-means as a limit of EM.
- Lloyd, Least Squares Quantization in PCM (IEEE Trans. Information Theory, 1982) — k-means의 할당–갱신 반복(Lloyd 알고리즘). 1957년 Bell Labs 기술 보고서의 출판본.The assign–update iteration of k-means (Lloyd's algorithm). The published version of a 1957 Bell Labs technical report.
- Arthur & Vassilvitskii, k-means++: The Advantages of Careful Seeding (SODA 2007) — D² 샘플링 초기화와 기대 O(log k) 근사 보장.D² sampling initialisation and its expected O(log k) approximation guarantee.
- Pearson, On Lines and Planes of Closest Fit to Systems of Points in Space (Philosophical Magazine, 1901) — PCA의 기원. 분산 최대화가 아니라 "가장 가깝게 맞는 직선/평면", 즉 재구성 오차 최소화로 출발했다.The origin of PCA. It started not from variance maximisation but from "the line/plane of closest fit", i.e. reconstruction-error minimisation.
- Shlens, A Tutorial on Principal Component Analysis (2014) — 공분산·고유분해·SVD의 관계를 차근차근 보여 주는 튜토리얼.A tutorial that walks step by step through the relation between covariance, eigendecomposition and SVD.
- Dempster, Laird, Rubin, Maximum Likelihood from Incomplete Data via the EM Algorithm (JRSS-B, 1977) — EM 알고리즘의 일반적 정식화와 단조성 증명.The general formulation of the EM algorithm and the proof of its monotonicity.
- Abbas et al., SemDeDup: Data-efficient learning at web-scale through semantic deduplication (2023) — 임베딩을 k-means로 묶고 군집 안에서 의미적 중복을 제거하는 대규모 데이터 정제.Large-scale data cleaning that clusters embeddings with k-means and removes semantic duplicates within each cluster.
- Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (ICLR 2022) — 미세조정 업데이트를 저랭크 행렬로 제한한다. 이 레슨의 저랭크 근사가 그대로 쓰이는 곳.Restricts the fine-tuning update to a low-rank matrix. This is where the low-rank approximation of this lesson is used directly.