Track I · ML Fundamentals · 09/09

비지도 학습Unsupervised learning

레이블 없이 데이터의 구조를 찾는 두 가지 고전, k-means와 PCA를 "제한된 코드로 재구성 오차를 최소화하기"라는 하나의 관점으로 유도한다. Lloyd 알고리즘의 단조 감소, k-means++, 분산 최대화 ↔ 고유분해 ↔ SVD의 동치, 그리고 soft k-means로서의 GMM/EM을 설명할 수 있게 된다.Derive the two classics for finding structure in data without labels, k-means and PCA, from a single viewpoint: "minimise reconstruction error with a restricted code". Explain the monotone decrease of Lloyd's algorithm, k-means++, the equivalence of variance maximisation ↔ eigendecomposition ↔ SVD, and GMM/EM as soft k-means.

35 분min k-means · Lloyd · k-means++ · PCA · eigendecomposition · SVD · reconstruction error · GMM · EM 먼저 볼 것:Before this: 학습이란 무엇인가What is learning?, 확률로 보는 손실Losses through probability

So far everything has been supervised learning with a target yy. 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 kk representative points” and you get k-means; restrict it to “qq-dimensional linear coordinates” and you get PCA. Both minimise the squared reconstruction error.

min⁡code, decoder 1n∑i=1n∥xi−decode(code(xi))∥2\min_{\text{code},\ \text{decoder}}\ \frac1n\sum_{i=1}^n \big\|x_i - \text{decode}(\text{code}(x_i))\big\|^2

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 x1,…,xn∈Rdx_1, \dots, x_n \in \mathbb R^d into kk clusters. Choose each point’s membership zi∈{1..k}z_i \in \{1..k\} and the cluster centres μ1,…,μk\mu_1, \dots, \mu_k jointly.

J(z,μ)=∑i=1n∥xi−μzi∥2J(z, \mu) = \sum_{i=1}^n \big\|x_i - \mu_{z_i}\big\|^2

zz is discrete and μ\mu 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.

  1. Assign: with μ\mu fixed, each ziz_i can be solved independently — pick the nearest centre: zi=arg⁡min⁡j∥xi−μj∥2z_i = \arg\min_j \|x_i - \mu_j\|^2.
  2. Update: with zz fixed, JJ is a quadratic in each μj\mu_j. From ∇μjJ=−2∑i:zi=j(xi−μj)=0\nabla_{\mu_j} J = -2\sum_{i: z_i = j}(x_i - \mu_j) = 0, μj\mu_j = the mean of its member points.

Both steps minimise JJ exactly with respect to their variable, so JJ never increases. And since there are finitely many possible partitions (at most knk^n) 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 kk 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.

  1. Draw the first centre uniformly from the data.
  2. For each point, compute the distance D(x)D(x) to the nearest existing centre, and draw the next centre with probability D(x)2/∑x′D(x′)2D(x)^2 / \sum_{x'} D(x')^2.
  3. Repeat until there are kk, then run Lloyd.

Arthur & Vassilvitskii (2007) showed that this initialisation alone is, in expectation, within O(log⁡k)O(\log k) 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.

지금까지는 모두 정답 yy가 있는 지도학습이었다. 레이블이 없으면 무엇을 최소화하는가? 가장 오래되고 지금도 쓰이는 답은 “데이터를 제한된 코드로 요약했다가 다시 복원할 때의 오차” 다. 코드를 “kk개의 대표점 중 하나”로 제한하면 k-means, “qq차원 선형 좌표”로 제한하면 PCA가 된다. 둘 다 제곱 재구성 오차를 최소화한다.

min⁡코드, 복원기 1n∑i=1n∥xi−복원(코드(xi))∥2\min_{\text{코드},\ \text{복원기}}\ \frac1n\sum_{i=1}^n \big\|x_i - \text{복원}(\text{코드}(x_i))\big\|^2

사실 LLM 사전학습도 같은 계열이다. 레이블을 따로 만들지 않고 데이터 자신(다음 토큰)을 맞추는 자기지도 학습이기 때문이다. 이 레슨의 두 알고리즘은 그 가장 단순한 형태다.

k-means

데이터 x1,…,xn∈Rdx_1, \dots, x_n \in \mathbb R^d를 kk개의 군집으로 나눈다. 각 점의 소속 zi∈{1..k}z_i \in \{1..k\}와 군집 중심 μ1,…,μk\mu_1, \dots, \mu_k를 동시에 고른다.

J(z,μ)=∑i=1n∥xi−μzi∥2J(z, \mu) = \sum_{i=1}^n \big\|x_i - \mu_{z_i}\big\|^2

zz는 이산, μ\mu는 연속이라 한 번에 풀기 어렵다(일반적으로 NP-hard다). 그래서 한쪽을 고정하고 다른 쪽을 푸는 좌표 하강을 한다. 이것이 Lloyd 알고리즘이다.

  1. 할당(assign): μ\mu를 고정하면 각 ziz_i는 독립적으로 풀린다. 가장 가까운 중심을 고르면 된다. zi=arg⁡min⁡j∥xi−μj∥2z_i = \arg\min_j \|x_i - \mu_j\|^2.
  2. 갱신(update): zz를 고정하면 JJ는 각 μj\mu_j에 대한 이차식이다. ∇μjJ=−2∑i:zi=j(xi−μj)=0\nabla_{\mu_j} J = -2\sum_{i: z_i = j}(x_i - \mu_j) = 0에서 μj\mu_j = 소속 점들의 평균.

두 단계 모두 JJ를 그 변수에 대해 정확히 최소화하므로 JJ는 절대 증가하지 않는다. 그리고 가능한 분할은 유한 개(knk^n 이하)이고 같은 분할로 돌아오면 멈추므로, 알고리즘은 유한 번 안에 끝난다. 다만 끝난 곳은 “어느 한쪽만 바꿔서는 나아지지 않는 점”일 뿐 전역 최소라는 보장이 없다. 초기값이 결과를 좌우한다.

k-means++: 초기값을 잘 고르기

무작위로 kk개 점을 고르면 한 덩어리에 중심이 둘 들어가고 다른 덩어리에는 하나도 없는 일이 흔하다. Lloyd는 이것을 고치지 못한다. 중심 하나가 두 덩어리 사이에 걸쳐 있어도 할당과 갱신이 서로를 정당화하기 때문이다. k-means++ 는 중심을 하나씩 고르되 이미 고른 중심에서 먼 점일수록 뽑힐 확률을 높인다.

  1. 첫 중심은 데이터에서 균등하게 뽑는다.
  2. 각 점에서 가장 가까운 기존 중심까지의 거리 D(x)D(x)를 구하고, 다음 중심을 확률 D(x)2/∑x′D(x′)2D(x)^2 / \sum_{x'} D(x')^2로 뽑는다.
  3. kk개가 될 때까지 반복한 뒤 Lloyd를 돌린다.

Arthur & Vassilvitskii(2007)는 이 초기화만으로도 기댓값이 최적의 O(log⁡k)O(\log k)배 이내임을 보였다. 이미 덮인 덩어리에서 또 뽑힐 확률이 낮아지니, 서로 다른 덩어리에 하나씩 들어갈 가능성이 크다.

반복iteration 0 목적함수objective J –
① Assign attaches each point to its nearest centre (×), and ② Update moves each centre to the mean of its points. The graph on the right shows the objective J (sum of squared point–centre distances) after every half-step, and it never goes up. Drag a centre (×) to build a bad initialisation yourself: herd two centres into one blob and you get a local minimum that converges in that state. k-means++ initialisation makes this much rarer. With "elongated blobs", even at minimum J the result differs from the clusters our eyes see: k-means assumes round clusters. Click on empty space to add a point. ① 할당은 각 점을 가장 가까운 중심(×)에 붙이고, ② 갱신은 각 중심을 자기 점들의 평균으로 옮긴다. 오른쪽 그래프는 반 걸음마다의 목적함수 J(점과 중심 거리 제곱의 합)이며 절대 올라가지 않는다. 중심(×)을 끌어 나쁜 초기값을 직접 만들어 보자. 두 중심을 한 덩어리에 몰아 두면 그 상태로 수렴하는 국소 최소가 생긴다. k-means++ 초기화는 이런 상황을 크게 줄인다. "길쭉한 덩어리"에서는 J가 최소여도 우리 눈의 군집과 다르다. k-means는 둥근 군집을 가정한다. 빈 곳을 클릭하면 점이 추가된다.
  1. 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.
  2. 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.
  3. Drag one centre into a blob that already has another centre and let it converge. You can build a bad local minimum yourself.
  4. 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? JJ always decreases as kk grows (J=0J = 0 when k=nk = n), so by itself it cannot be the criterion. Look for the point where JJ suddenly decreases less (the elbow), use the silhouette score, or use the performance of the downstream task that consumes the clusters.

NumPy k-means++ and Lloyd's algorithm
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).

p(x)=∑j=1kπj N(x; μj,Σj)p(x) = \sum_{j=1}^k \pi_j\, \mathcal N(x;\, \mu_j, \Sigma_j)

We would like to use the MLE of the probability lesson directly, but the log⁡∑\log\sum 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.

rij=πj N(xi;μj,Σj)∑lπl N(xi;μl,Σl)r_{ij} = \frac{\pi_j\, \mathcal N(x_i; \mu_j, \Sigma_j)}{\sum_{l} \pi_l\, \mathcal N(x_i; \mu_l, \Sigma_l)}

M-step (weighted update): the mean, covariance and proportion weighted by responsibility. Nj=∑irijN_j = \sum_i r_{ij}, μj=1Nj∑irijxi\mu_j = \frac{1}{N_j}\sum_i r_{ij}x_i, Σj=1Nj∑irij(xi−μj)(xi−μj)⊤\Sigma_j = \frac{1}{N_j}\sum_i r_{ij}(x_i - \mu_j)(x_i - \mu_j)^\top, πj=Nj/n\pi_j = N_j / n.

The relation to k-means is exact. Fix every cluster’s covariance to Σj=σ2I\Sigma_j = \sigma^2 I and send σ→0\sigma \to 0: the numerator of rijr_{ij} is exp⁡(−∥xi−μj∥2/2σ2)\exp(-\|x_i - \mu_j\|^2 / 2\sigma^2), 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 “qq-dimensional linear coordinates”. Start with q=1q = 1. Centre the data (subtract xˉ\bar x) and let the covariance be S=1n∑i(xi−xˉ)(xi−xˉ)⊤S = \frac1n\sum_i (x_i - \bar x)(x_i - \bar x)^\top. The variance of the coordinate u⊤(xi−xˉ)u^\top(x_i - \bar x) projected onto a unit vector uu is

1n∑i(u⊤(xi−xˉ))2=u⊤Su.\frac1n\sum_i \big(u^\top(x_i - \bar x)\big)^2 = u^\top S u .

Variance maximisation. Maximise u⊤Suu^\top S u subject to ∥u∥=1\|u\| = 1. Differentiating the Lagrangian u⊤Su−λ(u⊤u−1)u^\top S u - \lambda(u^\top u - 1) and setting it to 0 gives

Su=λu.S u = \lambda u .

uu must be an eigenvector of SS, and then the variance is u⊤Su=λu^\top S u = \lambda. So the answer is the eigenvector of the largest eigenvalue. This is the first principal component (PC1). For qq dimensions, take the top qq eigenvectors (they are mutually orthogonal because SS is symmetric).

Reconstruction-error minimisation. The same answer also comes from the opposite direction. Project a point xx onto uu and restore it as x^=xˉ+uu⊤(x−xˉ)\hat x = \bar x + u u^\top(x - \bar x); the residual is orthogonal to uu, so by Pythagoras

∥x−xˉ∥2=(u⊤(x−xˉ))2⏟projection length2+∥x−x^∥2⏟reconstruction error.\|x - \bar x\|^2 = \underbrace{\big(u^\top(x - \bar x)\big)^2}_{\text{projection length}^2} + \underbrace{\|x - \hat x\|^2}_{\text{reconstruction error}} .

Averaging, tr⁡S=u⊤Su+mean reconstruction error\operatorname{tr}S = u^\top S u + \text{mean reconstruction error}. The left side is a constant independent of uu (the total variance), so maximising variance and minimising reconstruction error are the same problem. With qq components, the mean reconstruction error is the sum of the discarded eigenvalues ∑j>qλj\sum_{j > q}\lambda_j. When Pearson (1901) first conceived PCA, it was from this “line of closest fit” side.

  1. ① 할당과 ② 갱신을 번갈아 눌러 보자. 오른쪽에서 파란 점(할당 후)과 빨간 점(갱신 후)이 계단처럼 내려가고 한 번도 올라가지 않는다.
  2. “다시 초기화”를 몇 번 누르며 ”▶ 수렴까지”를 돌려 보자. 무작위 초기화에서는 가끔 덩어리 두 개를 중심 하나가 차지하고 끝난다. 최종 J가 확연히 크다. k-means++로 바꾸면 이런 일이 드물다.
  3. 중심 하나를 끌어서 다른 중심이 있는 덩어리 안으로 넣고 수렴시켜 보자. 나쁜 국소 최소를 직접 만들 수 있다.
  4. “길쭉한 덩어리” 에서 k = 3으로 수렴시키면, 가로로 긴 세 띠 대신 세로로 자른 영역이 나오기도 한다. 그 분할의 J가 더 작기 때문이다. k-means는 모든 군집이 같은 크기의 둥근 모양이라고 가정한다. “크기가 다른 덩어리”에서도 큰 덩어리를 쪼개는 쪽을 선호한다.

k는 어떻게 고르나? JJ는 kk를 늘릴수록 무조건 줄어서(k=nk = n이면 0) 그 자체로는 기준이 되지 못한다. JJ가 갑자기 덜 줄어드는 지점(elbow)을 보거나, 실루엣 점수, 혹은 군집을 쓰는 다운스트림 작업의 성능으로 고른다.

NumPy k-means++ 와 Lloyd 알고리즘
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) 이 된다.

p(x)=∑j=1kπj N(x; μj,Σj)p(x) = \sum_{j=1}^k \pi_j\, \mathcal N(x;\, \mu_j, \Sigma_j)

확률 레슨의 MLE를 그대로 쓰고 싶지만 log⁡∑\log\sum 때문에 닫힌 해가 없다. EM(expectation–maximization) 은 k-means와 똑같은 두 단계 구조로 푼다.

E-step (부드러운 할당): 각 점이 각 군집에서 나왔을 사후확률, 곧 책임(responsibility) 을 계산한다.

rij=πj N(xi;μj,Σj)∑lπl N(xi;μl,Σl)r_{ij} = \frac{\pi_j\, \mathcal N(x_i; \mu_j, \Sigma_j)}{\sum_{l} \pi_l\, \mathcal N(x_i; \mu_l, \Sigma_l)}

M-step (가중 갱신): 책임을 가중치로 쓴 평균·공분산·비율. Nj=∑irijN_j = \sum_i r_{ij}, μj=1Nj∑irijxi\mu_j = \frac{1}{N_j}\sum_i r_{ij}x_i, Σj=1Nj∑irij(xi−μj)(xi−μj)⊤\Sigma_j = \frac{1}{N_j}\sum_i r_{ij}(x_i - \mu_j)(x_i - \mu_j)^\top, πj=Nj/n\pi_j = N_j / n.

k-means와의 관계가 정확하다. 모든 군집의 공분산을 Σj=σ2I\Sigma_j = \sigma^2 I로 고정하고 σ→0\sigma \to 0으로 보내면, rijr_{ij}의 분자는 exp⁡(−∥xi−μj∥2/2σ2)\exp(-\|x_i - \mu_j\|^2 / 2\sigma^2)이라 가장 가까운 중심 하나가 압도하고 책임이 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: 가장 많이 퍼진 방향

이번에는 코드를 “qq차원 선형 좌표”로 제한한다. 먼저 q=1q = 1. 데이터를 중심화하고(xˉ\bar x를 빼고) 공분산을 S=1n∑i(xi−xˉ)(xi−xˉ)⊤S = \frac1n\sum_i (x_i - \bar x)(x_i - \bar x)^\top라 하자. 단위벡터 uu 방향으로 사영한 좌표 u⊤(xi−xˉ)u^\top(x_i - \bar x)의 분산은

1n∑i(u⊤(xi−xˉ))2=u⊤Su.\frac1n\sum_i \big(u^\top(x_i - \bar x)\big)^2 = u^\top S u .

분산 최대화. ∥u∥=1\|u\| = 1 제약 아래 u⊤Suu^\top S u를 최대화한다. 라그랑지안 u⊤Su−λ(u⊤u−1)u^\top S u - \lambda(u^\top u - 1)을 미분해 0으로 놓으면

Su=λu.S u = \lambda u .

uu는 SS의 고유벡터여야 하고, 그때 분산은 u⊤Su=λu^\top S u = \lambda다. 그러니 가장 큰 고유값의 고유벡터가 답이다. 이것이 첫 번째 주성분(PC1)이다. qq차원이면 위에서부터 qq개의 고유벡터를 쓴다(SS가 대칭이라 서로 직교한다).

재구성 오차 최소화. 같은 답이 반대 방향에서도 나온다. 점 xx를 uu 위로 사영해 x^=xˉ+uu⊤(x−xˉ)\hat x = \bar x + u u^\top(x - \bar x)로 복원하면, 잔차는 uu와 직교하므로 피타고라스 정리에 의해

∥x−xˉ∥2=(u⊤(x−xˉ))2⏟사영의 길이2+∥x−x^∥2⏟재구성 오차.\|x - \bar x\|^2 = \underbrace{\big(u^\top(x - \bar x)\big)^2}_{\text{사영의 길이}^2} + \underbrace{\|x - \hat x\|^2}_{\text{재구성 오차}} .

평균을 내면 tr⁡S=u⊤Su+평균 재구성 오차\operatorname{tr}S = u^\top S u + \text{평균 재구성 오차}. 왼쪽은 uu와 무관한 상수(전체 분산)이므로 분산을 최대화하는 것과 재구성 오차를 최소화하는 것은 같은 문제다. qq개를 쓰면 평균 재구성 오차는 버린 고유값의 합 ∑j>qλj\sum_{j > q}\lambda_j이다. Pearson(1901)이 처음 PCA를 생각한 것도 이 “가장 가깝게 맞는 직선” 쪽이었다.

λ₁ – λ₂ – PC1 설명 비율PC1 explained ratio – u 방향 분산variance along u – 재구성 오차reconstruction error –
The grey arrows are the eigenvectors of the covariance (length 2√λ); the red line is the 1-D direction u you have chosen. Each point is replaced by its projection onto u, and the thin line is its reconstruction error. Turn u's angle and on the right the variance along u (blue) and the mean reconstruction error (red) move exactly opposite to each other, while their sum (dashed) is always the total variance. Angle of maximum variance = angle of minimum error = PC1. Drag a point to make an outlier and PC1 swings sharply towards it: a squared-error criterion is fragile against outliers. 회색 화살표는 공분산의 고유벡터(길이 2√λ), 빨간 선은 지금 고른 1차원 방향 u다. 각 점은 u 위의 사영(projection)으로 대체되고, 가는 선이 그 재구성 오차다. u의 각도를 돌리면 오른쪽에서 u 방향 분산(파랑)과 평균 재구성 오차(빨강)가 정확히 반대로 움직이고 그 합(점선)은 항상 전체 분산이다. 분산이 최대인 각도 = 오차가 최소인 각도 = PC1. 점을 끌어 이상치를 하나 만들면 PC1이 그쪽으로 크게 돌아간다. 제곱 오차 기준이라 이상치에 약하다.
  1. 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 λ₂.
  2. 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.
  3. 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.
  4. 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 Xc∈Rn×dX_c \in \mathbb R^{n \times d} is Xc=UΣV⊤X_c = U\Sigma V^\top, then

S=1nXc⊤Xc=VΣ2nV⊤.S = \frac1n X_c^\top X_c = V \frac{\Sigma^2}{n} V^\top .

That is, the columns of VV are the principal directions, the eigenvalues are λj=σj2/n\lambda_j = \sigma_j^2 / n, and each point’s principal-component coordinates are XcV=UΣX_c V = U\Sigma. In practice you do not form SS; you compute the SVD of XcX_c directly, because forming Xc⊤XcX_c^\top X_c 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 qq singular values, UqΣqVq⊤U_q\Sigma_q V_q^\top, gives the best rank-qq approximation in the Frobenius norm. PCA is the same thing as the optimal low-rank approximation of the data matrix.

NumPy PCA: eigendecomposition = SVD, reconstruction error = sum of discarded eigenvalues
# 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 0.32=0.090.3^2 = 0.09). 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.

확인 문제Check yourself

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 λ2=1\lambda_2 = 1. The explained ratio is λ1/(λ1+λ2)=4/5=80%\lambda_1/(\lambda_1 + \lambda_2) = 4/5 = 80\%. Total variance 5 = projected variance 4 + reconstruction error 1 (Pythagoras).

확인 문제Check yourself

Which statement about Lloyd's algorithm (k-means) is correct?

Assignment and update each minimise JJ exactly with respect to zz and μ\mu, so JJ 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 O(log⁡k)O(\log k) approximation in expectation, not the global minimum.

Summary

  • k-means and PCA both minimise squared reconstruction error with a restricted code (one centre / qq-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 ⇔ Su=λuSu = \lambda u ⇔ reconstruction-error minimisation (Pythagoras). Reconstruction error = sum of discarded eigenvalues.
  • Compute it with the SVD of the centred data. VV holds the principal components, σj2/n\sigma_j^2/n are the eigenvalues, and the truncated SVD is the optimal low-rank approximation.
  1. u 각도 슬라이더를 0°에서 180°까지 돌려 보자. 오른쪽 파란 곡선(u 방향 분산)과 빨간 곡선(재구성 오차)이 거울처럼 움직이고 합은 점선(전체 분산)에 붙어 있다. 파랑의 최댓값은 λ₁, 최솟값은 λ₂이다.
  2. “u ← PC1”을 누르면 왼쪽 빨간 선이 긴 회색 화살표와 겹치고 가는 잔차 선들이 가장 짧아진다.
  3. 상관을 0으로 내리면 두 고유값이 비슷해지고 오른쪽 곡선이 거의 평평해진다. 그런 데이터에서는 “주된 방향”이 의미가 없다.
  4. 점 하나를 멀리 끌어내 보자. PC1이 그 점 쪽으로 홱 돌아간다. 제곱 오차는 이상치에 민감하다.

SVD로 계산하기

중심화한 데이터 행렬 Xc∈Rn×dX_c \in \mathbb R^{n \times d}의 특이값 분해를 Xc=UΣV⊤X_c = U\Sigma V^\top라 하면

S=1nXc⊤Xc=VΣ2nV⊤.S = \frac1n X_c^\top X_c = V \frac{\Sigma^2}{n} V^\top .

즉 VV의 열이 주성분 방향이고 고유값은 λj=σj2/n\lambda_j = \sigma_j^2 / n, 각 점의 주성분 좌표는 XcV=UΣX_c V = U\Sigma다. 실전에서는 SS를 만들지 않고 XcX_c의 SVD를 바로 계산한다. Xc⊤XcX_c^\top X_c를 만드는 순간 조건수가 제곱되기 때문이다(첫 레슨의 정규방정식과 같은 이유). 또 Eckart–Young 정리에 따르면 상위 qq개 특이값만 남긴 UqΣqVq⊤U_q\Sigma_q V_q^\top가 Frobenius 노름에서 가장 좋은 랭크 qq 근사다. PCA는 데이터 행렬의 최적 저랭크 근사와 같은 것이다.

NumPy PCA: 고유분해 = SVD, 재구성 오차 = 버린 고유값의 합
# 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개 뒤에서 뚝 떨어진다(잡음 수준 0.32=0.090.3^2 = 0.09 근처). 데이터의 “진짜 차원”이 3이라는 신호다. 재구성 오차는 버린 고유값의 합과 소수점 셋째 자리까지 같다.

확인 문제Check yourself

2차원 데이터의 공분산 고유값이 4와 1이다. PC1 하나로 사영했다가 복원할 때 평균 제곱 재구성 오차와 PC1의 설명 분산 비율은?

버린 고유값의 합이 재구성 오차이므로 λ2=1\lambda_2 = 1. 설명 비율은 λ1/(λ1+λ2)=4/5=80%\lambda_1/(\lambda_1 + \lambda_2) = 4/5 = 80\%. 전체 분산 5 = 사영 분산 4 + 재구성 오차 1(피타고라스).

확인 문제Check yourself

Lloyd 알고리즘(k-means)에 대해 옳은 것은?

할당과 갱신은 각각 zz와 μ\mu에 대해 JJ를 정확히 최소화하므로 JJ는 증가하지 않고, 분할의 수가 유한해 반드시 멈춘다. 그러나 멈춘 곳은 좌표별로만 최적인 점이라 전역 최소가 아닐 수 있다. k-means++는 기댓값으로 O(log⁡k)O(\log k)배 근사를 보장할 뿐 전역 최소를 보장하지 않는다.

정리

  • k-means와 PCA는 모두 제한된 코드(중심 하나 / 선형 qq차원 좌표)로 제곱 재구성 오차를 최소화한다.
  • Lloyd 알고리즘은 할당·갱신이 각각 정확한 최소화라 J가 단조 감소하고 유한 번에 멈추지만 국소 최소에 머문다. k-means++의 D² 샘플링이 초기값 문제를 크게 줄인다.
  • GMM의 EM은 책임으로 부드럽게 할당하는 k-means이고, 등방성 공분산을 0으로 보내면 정확히 k-means가 된다.
  • PCA: 분산 최대화 ⇔ Su=λuSu = \lambda u ⇔ 재구성 오차 최소화(피타고라스). 재구성 오차 = 버린 고유값의 합.
  • 계산은 중심화한 데이터의 SVD로 한다. VV가 주성분, σj2/n\sigma_j^2/n이 고유값, 절단 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.